exceljs.bare.js 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ExcelJS = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. "use strict";
  3. const fs = require('fs');
  4. const fastCsv = require('fast-csv');
  5. const customParseFormat = require('dayjs/plugin/customParseFormat');
  6. const utc = require('dayjs/plugin/utc');
  7. const dayjs = require('dayjs').extend(customParseFormat).extend(utc);
  8. const StreamBuf = require('../utils/stream-buf');
  9. const {
  10. fs: {
  11. exists
  12. }
  13. } = require('../utils/utils');
  14. /* eslint-disable quote-props */
  15. const SpecialValues = {
  16. true: true,
  17. false: false,
  18. '#N/A': {
  19. error: '#N/A'
  20. },
  21. '#REF!': {
  22. error: '#REF!'
  23. },
  24. '#NAME?': {
  25. error: '#NAME?'
  26. },
  27. '#DIV/0!': {
  28. error: '#DIV/0!'
  29. },
  30. '#NULL!': {
  31. error: '#NULL!'
  32. },
  33. '#VALUE!': {
  34. error: '#VALUE!'
  35. },
  36. '#NUM!': {
  37. error: '#NUM!'
  38. }
  39. };
  40. /* eslint-ensable quote-props */
  41. class CSV {
  42. constructor(workbook) {
  43. this.workbook = workbook;
  44. this.worksheet = null;
  45. }
  46. async readFile(filename, options) {
  47. options = options || {};
  48. if (!(await exists(filename))) {
  49. throw new Error(`File not found: ${filename}`);
  50. }
  51. const stream = fs.createReadStream(filename);
  52. const worksheet = await this.read(stream, options);
  53. stream.close();
  54. return worksheet;
  55. }
  56. read(stream, options) {
  57. options = options || {};
  58. return new Promise((resolve, reject) => {
  59. const worksheet = this.workbook.addWorksheet(options.sheetName);
  60. const dateFormats = options.dateFormats || ['YYYY-MM-DD[T]HH:mm:ssZ', 'YYYY-MM-DD[T]HH:mm:ss', 'MM-DD-YYYY', 'YYYY-MM-DD'];
  61. const map = options.map || function (datum) {
  62. if (datum === '') {
  63. return null;
  64. }
  65. const datumNumber = Number(datum);
  66. if (!Number.isNaN(datumNumber) && datumNumber !== Infinity) {
  67. return datumNumber;
  68. }
  69. const dt = dateFormats.reduce((matchingDate, currentDateFormat) => {
  70. if (matchingDate) {
  71. return matchingDate;
  72. }
  73. const dayjsObj = dayjs(datum, currentDateFormat, true);
  74. if (dayjsObj.isValid()) {
  75. return dayjsObj;
  76. }
  77. return null;
  78. }, null);
  79. if (dt) {
  80. return new Date(dt.valueOf());
  81. }
  82. const special = SpecialValues[datum];
  83. if (special !== undefined) {
  84. return special;
  85. }
  86. return datum;
  87. };
  88. const csvStream = fastCsv.parse(options.parserOptions).on('data', data => {
  89. worksheet.addRow(data.map(map));
  90. }).on('end', () => {
  91. csvStream.emit('worksheet', worksheet);
  92. });
  93. csvStream.on('worksheet', resolve).on('error', reject);
  94. stream.pipe(csvStream);
  95. });
  96. }
  97. /**
  98. * @deprecated since version 4.0. You should use `CSV#read` instead. Please follow upgrade instruction: https://github.com/exceljs/exceljs/blob/master/UPGRADE-4.0.md
  99. */
  100. createInputStream() {
  101. throw new Error('`CSV#createInputStream` is deprecated. You should use `CSV#read` instead. This method will be removed in version 5.0. Please follow upgrade instruction: https://github.com/exceljs/exceljs/blob/master/UPGRADE-4.0.md');
  102. }
  103. write(stream, options) {
  104. return new Promise((resolve, reject) => {
  105. options = options || {};
  106. // const encoding = options.encoding || 'utf8';
  107. // const separator = options.separator || ',';
  108. // const quoteChar = options.quoteChar || '\'';
  109. const worksheet = this.workbook.getWorksheet(options.sheetName || options.sheetId);
  110. const csvStream = fastCsv.format(options.formatterOptions);
  111. stream.on('finish', () => {
  112. resolve();
  113. });
  114. csvStream.on('error', reject);
  115. csvStream.pipe(stream);
  116. const {
  117. dateFormat,
  118. dateUTC
  119. } = options;
  120. const map = options.map || (value => {
  121. if (value) {
  122. if (value.text || value.hyperlink) {
  123. return value.hyperlink || value.text || '';
  124. }
  125. if (value.formula || value.result) {
  126. return value.result || '';
  127. }
  128. if (value instanceof Date) {
  129. if (dateFormat) {
  130. return dateUTC ? dayjs.utc(value).format(dateFormat) : dayjs(value).format(dateFormat);
  131. }
  132. return dateUTC ? dayjs.utc(value).format() : dayjs(value).format();
  133. }
  134. if (value.error) {
  135. return value.error;
  136. }
  137. if (typeof value === 'object') {
  138. return JSON.stringify(value);
  139. }
  140. }
  141. return value;
  142. });
  143. const includeEmptyRows = options.includeEmptyRows === undefined || options.includeEmptyRows;
  144. let lastRow = 1;
  145. if (worksheet) {
  146. worksheet.eachRow((row, rowNumber) => {
  147. if (includeEmptyRows) {
  148. while (lastRow++ < rowNumber - 1) {
  149. csvStream.write([]);
  150. }
  151. }
  152. const {
  153. values
  154. } = row;
  155. values.shift();
  156. csvStream.write(values.map(map));
  157. lastRow = rowNumber;
  158. });
  159. }
  160. csvStream.end();
  161. });
  162. }
  163. writeFile(filename, options) {
  164. options = options || {};
  165. const streamOptions = {
  166. encoding: options.encoding || 'utf8'
  167. };
  168. const stream = fs.createWriteStream(filename, streamOptions);
  169. return this.write(stream, options);
  170. }
  171. async writeBuffer(options) {
  172. const stream = new StreamBuf();
  173. await this.write(stream, options);
  174. return stream.read();
  175. }
  176. }
  177. module.exports = CSV;
  178. },{"../utils/stream-buf":24,"../utils/utils":27,"dayjs":230,"dayjs/plugin/customParseFormat":231,"dayjs/plugin/utc":232,"fast-csv":263,"fs":216}],2:[function(require,module,exports){
  179. 'use strict';
  180. const colCache = require('../utils/col-cache');
  181. class Anchor {
  182. constructor(worksheet, address) {
  183. let offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  184. this.worksheet = worksheet;
  185. if (!address) {
  186. this.nativeCol = 0;
  187. this.nativeColOff = 0;
  188. this.nativeRow = 0;
  189. this.nativeRowOff = 0;
  190. } else if (typeof address === 'string') {
  191. const decoded = colCache.decodeAddress(address);
  192. this.nativeCol = decoded.col + offset;
  193. this.nativeColOff = 0;
  194. this.nativeRow = decoded.row + offset;
  195. this.nativeRowOff = 0;
  196. } else if (address.nativeCol !== undefined) {
  197. this.nativeCol = address.nativeCol || 0;
  198. this.nativeColOff = address.nativeColOff || 0;
  199. this.nativeRow = address.nativeRow || 0;
  200. this.nativeRowOff = address.nativeRowOff || 0;
  201. } else if (address.col !== undefined) {
  202. this.col = address.col + offset;
  203. this.row = address.row + offset;
  204. } else {
  205. this.nativeCol = 0;
  206. this.nativeColOff = 0;
  207. this.nativeRow = 0;
  208. this.nativeRowOff = 0;
  209. }
  210. }
  211. static asInstance(model) {
  212. return model instanceof Anchor || model == null ? model : new Anchor(model);
  213. }
  214. get col() {
  215. return this.nativeCol + Math.min(this.colWidth - 1, this.nativeColOff) / this.colWidth;
  216. }
  217. set col(v) {
  218. this.nativeCol = Math.floor(v);
  219. this.nativeColOff = Math.floor((v - this.nativeCol) * this.colWidth);
  220. }
  221. get row() {
  222. return this.nativeRow + Math.min(this.rowHeight - 1, this.nativeRowOff) / this.rowHeight;
  223. }
  224. set row(v) {
  225. this.nativeRow = Math.floor(v);
  226. this.nativeRowOff = Math.floor((v - this.nativeRow) * this.rowHeight);
  227. }
  228. get colWidth() {
  229. return this.worksheet && this.worksheet.getColumn(this.nativeCol + 1) && this.worksheet.getColumn(this.nativeCol + 1).isCustomWidth ? Math.floor(this.worksheet.getColumn(this.nativeCol + 1).width * 10000) : 640000;
  230. }
  231. get rowHeight() {
  232. return this.worksheet && this.worksheet.getRow(this.nativeRow + 1) && this.worksheet.getRow(this.nativeRow + 1).height ? Math.floor(this.worksheet.getRow(this.nativeRow + 1).height * 10000) : 180000;
  233. }
  234. get model() {
  235. return {
  236. nativeCol: this.nativeCol,
  237. nativeColOff: this.nativeColOff,
  238. nativeRow: this.nativeRow,
  239. nativeRowOff: this.nativeRowOff
  240. };
  241. }
  242. set model(value) {
  243. this.nativeCol = value.nativeCol;
  244. this.nativeColOff = value.nativeColOff;
  245. this.nativeRow = value.nativeRow;
  246. this.nativeRowOff = value.nativeRowOff;
  247. }
  248. }
  249. module.exports = Anchor;
  250. },{"../utils/col-cache":19}],3:[function(require,module,exports){
  251. "use strict";
  252. /* eslint-disable max-classes-per-file */
  253. const colCache = require('../utils/col-cache');
  254. const _ = require('../utils/under-dash');
  255. const Enums = require('./enums');
  256. const {
  257. slideFormula
  258. } = require('../utils/shared-formula');
  259. const Note = require('./note');
  260. // Cell requirements
  261. // Operate inside a worksheet
  262. // Store and retrieve a value with a range of types: text, number, date, hyperlink, reference, formula, etc.
  263. // Manage/use and manipulate cell format either as local to cell or inherited from column or row.
  264. class Cell {
  265. constructor(row, column, address) {
  266. if (!row || !column) {
  267. throw new Error('A Cell needs a Row');
  268. }
  269. this._row = row;
  270. this._column = column;
  271. colCache.validateAddress(address);
  272. this._address = address;
  273. // TODO: lazy evaluation of this._value
  274. this._value = Value.create(Cell.Types.Null, this);
  275. this.style = this._mergeStyle(row.style, column.style, {});
  276. this._mergeCount = 0;
  277. }
  278. get worksheet() {
  279. return this._row.worksheet;
  280. }
  281. get workbook() {
  282. return this._row.worksheet.workbook;
  283. }
  284. // help GC by removing cyclic (and other) references
  285. destroy() {
  286. delete this.style;
  287. delete this._value;
  288. delete this._row;
  289. delete this._column;
  290. delete this._address;
  291. }
  292. // =========================================================================
  293. // Styles stuff
  294. get numFmt() {
  295. return this.style.numFmt;
  296. }
  297. set numFmt(value) {
  298. this.style.numFmt = value;
  299. }
  300. get font() {
  301. return this.style.font;
  302. }
  303. set font(value) {
  304. this.style.font = value;
  305. }
  306. get alignment() {
  307. return this.style.alignment;
  308. }
  309. set alignment(value) {
  310. this.style.alignment = value;
  311. }
  312. get border() {
  313. return this.style.border;
  314. }
  315. set border(value) {
  316. this.style.border = value;
  317. }
  318. get fill() {
  319. return this.style.fill;
  320. }
  321. set fill(value) {
  322. this.style.fill = value;
  323. }
  324. get protection() {
  325. return this.style.protection;
  326. }
  327. set protection(value) {
  328. this.style.protection = value;
  329. }
  330. _mergeStyle(rowStyle, colStyle, style) {
  331. const numFmt = rowStyle && rowStyle.numFmt || colStyle && colStyle.numFmt;
  332. if (numFmt) style.numFmt = numFmt;
  333. const font = rowStyle && rowStyle.font || colStyle && colStyle.font;
  334. if (font) style.font = font;
  335. const alignment = rowStyle && rowStyle.alignment || colStyle && colStyle.alignment;
  336. if (alignment) style.alignment = alignment;
  337. const border = rowStyle && rowStyle.border || colStyle && colStyle.border;
  338. if (border) style.border = border;
  339. const fill = rowStyle && rowStyle.fill || colStyle && colStyle.fill;
  340. if (fill) style.fill = fill;
  341. const protection = rowStyle && rowStyle.protection || colStyle && colStyle.protection;
  342. if (protection) style.protection = protection;
  343. return style;
  344. }
  345. // =========================================================================
  346. // return the address for this cell
  347. get address() {
  348. return this._address;
  349. }
  350. get row() {
  351. return this._row.number;
  352. }
  353. get col() {
  354. return this._column.number;
  355. }
  356. get $col$row() {
  357. return `$${this._column.letter}$${this.row}`;
  358. }
  359. // =========================================================================
  360. // Value stuff
  361. get type() {
  362. return this._value.type;
  363. }
  364. get effectiveType() {
  365. return this._value.effectiveType;
  366. }
  367. toCsvString() {
  368. return this._value.toCsvString();
  369. }
  370. // =========================================================================
  371. // Merge stuff
  372. addMergeRef() {
  373. this._mergeCount++;
  374. }
  375. releaseMergeRef() {
  376. this._mergeCount--;
  377. }
  378. get isMerged() {
  379. return this._mergeCount > 0 || this.type === Cell.Types.Merge;
  380. }
  381. merge(master, ignoreStyle) {
  382. this._value.release();
  383. this._value = Value.create(Cell.Types.Merge, this, master);
  384. if (!ignoreStyle) {
  385. this.style = master.style;
  386. }
  387. }
  388. unmerge() {
  389. if (this.type === Cell.Types.Merge) {
  390. this._value.release();
  391. this._value = Value.create(Cell.Types.Null, this);
  392. this.style = this._mergeStyle(this._row.style, this._column.style, {});
  393. }
  394. }
  395. isMergedTo(master) {
  396. if (this._value.type !== Cell.Types.Merge) return false;
  397. return this._value.isMergedTo(master);
  398. }
  399. get master() {
  400. if (this.type === Cell.Types.Merge) {
  401. return this._value.master;
  402. }
  403. return this; // an unmerged cell is its own master
  404. }
  405. get isHyperlink() {
  406. return this._value.type === Cell.Types.Hyperlink;
  407. }
  408. get hyperlink() {
  409. return this._value.hyperlink;
  410. }
  411. // return the value
  412. get value() {
  413. return this._value.value;
  414. }
  415. // set the value - can be number, string or raw
  416. set value(v) {
  417. // special case - merge cells set their master's value
  418. if (this.type === Cell.Types.Merge) {
  419. this._value.master.value = v;
  420. return;
  421. }
  422. this._value.release();
  423. // assign value
  424. this._value = Value.create(Value.getType(v), this, v);
  425. }
  426. get note() {
  427. return this._comment && this._comment.note;
  428. }
  429. set note(note) {
  430. this._comment = new Note(note);
  431. }
  432. get text() {
  433. return this._value.toString();
  434. }
  435. get html() {
  436. return _.escapeHtml(this.text);
  437. }
  438. toString() {
  439. return this.text;
  440. }
  441. _upgradeToHyperlink(hyperlink) {
  442. // if this cell is a string, turn it into a Hyperlink
  443. if (this.type === Cell.Types.String) {
  444. this._value = Value.create(Cell.Types.Hyperlink, this, {
  445. text: this._value.value,
  446. hyperlink
  447. });
  448. }
  449. }
  450. // =========================================================================
  451. // Formula stuff
  452. get formula() {
  453. return this._value.formula;
  454. }
  455. get result() {
  456. return this._value.result;
  457. }
  458. get formulaType() {
  459. return this._value.formulaType;
  460. }
  461. // =========================================================================
  462. // Name stuff
  463. get fullAddress() {
  464. const {
  465. worksheet
  466. } = this._row;
  467. return {
  468. sheetName: worksheet.name,
  469. address: this.address,
  470. row: this.row,
  471. col: this.col
  472. };
  473. }
  474. get name() {
  475. return this.names[0];
  476. }
  477. set name(value) {
  478. this.names = [value];
  479. }
  480. get names() {
  481. return this.workbook.definedNames.getNamesEx(this.fullAddress);
  482. }
  483. set names(value) {
  484. const {
  485. definedNames
  486. } = this.workbook;
  487. definedNames.removeAllNames(this.fullAddress);
  488. value.forEach(name => {
  489. definedNames.addEx(this.fullAddress, name);
  490. });
  491. }
  492. addName(name) {
  493. this.workbook.definedNames.addEx(this.fullAddress, name);
  494. }
  495. removeName(name) {
  496. this.workbook.definedNames.removeEx(this.fullAddress, name);
  497. }
  498. removeAllNames() {
  499. this.workbook.definedNames.removeAllNames(this.fullAddress);
  500. }
  501. // =========================================================================
  502. // Data Validation stuff
  503. get _dataValidations() {
  504. return this.worksheet.dataValidations;
  505. }
  506. get dataValidation() {
  507. return this._dataValidations.find(this.address);
  508. }
  509. set dataValidation(value) {
  510. this._dataValidations.add(this.address, value);
  511. }
  512. // =========================================================================
  513. // Model stuff
  514. get model() {
  515. const {
  516. model
  517. } = this._value;
  518. model.style = this.style;
  519. if (this._comment) {
  520. model.comment = this._comment.model;
  521. }
  522. return model;
  523. }
  524. set model(value) {
  525. this._value.release();
  526. this._value = Value.create(value.type, this);
  527. this._value.model = value;
  528. if (value.comment) {
  529. switch (value.comment.type) {
  530. case 'note':
  531. this._comment = Note.fromModel(value.comment);
  532. break;
  533. }
  534. }
  535. if (value.style) {
  536. this.style = value.style;
  537. } else {
  538. this.style = {};
  539. }
  540. }
  541. }
  542. Cell.Types = Enums.ValueType;
  543. // =============================================================================
  544. // Internal Value Types
  545. class NullValue {
  546. constructor(cell) {
  547. this.model = {
  548. address: cell.address,
  549. type: Cell.Types.Null
  550. };
  551. }
  552. get value() {
  553. return null;
  554. }
  555. set value(value) {
  556. // nothing to do
  557. }
  558. get type() {
  559. return Cell.Types.Null;
  560. }
  561. get effectiveType() {
  562. return Cell.Types.Null;
  563. }
  564. get address() {
  565. return this.model.address;
  566. }
  567. set address(value) {
  568. this.model.address = value;
  569. }
  570. toCsvString() {
  571. return '';
  572. }
  573. release() {}
  574. toString() {
  575. return '';
  576. }
  577. }
  578. class NumberValue {
  579. constructor(cell, value) {
  580. this.model = {
  581. address: cell.address,
  582. type: Cell.Types.Number,
  583. value
  584. };
  585. }
  586. get value() {
  587. return this.model.value;
  588. }
  589. set value(value) {
  590. this.model.value = value;
  591. }
  592. get type() {
  593. return Cell.Types.Number;
  594. }
  595. get effectiveType() {
  596. return Cell.Types.Number;
  597. }
  598. get address() {
  599. return this.model.address;
  600. }
  601. set address(value) {
  602. this.model.address = value;
  603. }
  604. toCsvString() {
  605. return this.model.value.toString();
  606. }
  607. release() {}
  608. toString() {
  609. return this.model.value.toString();
  610. }
  611. }
  612. class StringValue {
  613. constructor(cell, value) {
  614. this.model = {
  615. address: cell.address,
  616. type: Cell.Types.String,
  617. value
  618. };
  619. }
  620. get value() {
  621. return this.model.value;
  622. }
  623. set value(value) {
  624. this.model.value = value;
  625. }
  626. get type() {
  627. return Cell.Types.String;
  628. }
  629. get effectiveType() {
  630. return Cell.Types.String;
  631. }
  632. get address() {
  633. return this.model.address;
  634. }
  635. set address(value) {
  636. this.model.address = value;
  637. }
  638. toCsvString() {
  639. return `"${this.model.value.replace(/"/g, '""')}"`;
  640. }
  641. release() {}
  642. toString() {
  643. return this.model.value;
  644. }
  645. }
  646. class RichTextValue {
  647. constructor(cell, value) {
  648. this.model = {
  649. address: cell.address,
  650. type: Cell.Types.String,
  651. value
  652. };
  653. }
  654. get value() {
  655. return this.model.value;
  656. }
  657. set value(value) {
  658. this.model.value = value;
  659. }
  660. toString() {
  661. return this.model.value.richText.map(t => t.text).join('');
  662. }
  663. get type() {
  664. return Cell.Types.RichText;
  665. }
  666. get effectiveType() {
  667. return Cell.Types.RichText;
  668. }
  669. get address() {
  670. return this.model.address;
  671. }
  672. set address(value) {
  673. this.model.address = value;
  674. }
  675. toCsvString() {
  676. return `"${this.text.replace(/"/g, '""')}"`;
  677. }
  678. release() {}
  679. }
  680. class DateValue {
  681. constructor(cell, value) {
  682. this.model = {
  683. address: cell.address,
  684. type: Cell.Types.Date,
  685. value
  686. };
  687. }
  688. get value() {
  689. return this.model.value;
  690. }
  691. set value(value) {
  692. this.model.value = value;
  693. }
  694. get type() {
  695. return Cell.Types.Date;
  696. }
  697. get effectiveType() {
  698. return Cell.Types.Date;
  699. }
  700. get address() {
  701. return this.model.address;
  702. }
  703. set address(value) {
  704. this.model.address = value;
  705. }
  706. toCsvString() {
  707. return this.model.value.toISOString();
  708. }
  709. release() {}
  710. toString() {
  711. return this.model.value.toString();
  712. }
  713. }
  714. class HyperlinkValue {
  715. constructor(cell, value) {
  716. this.model = {
  717. address: cell.address,
  718. type: Cell.Types.Hyperlink,
  719. text: value ? value.text : undefined,
  720. hyperlink: value ? value.hyperlink : undefined
  721. };
  722. if (value && value.tooltip) {
  723. this.model.tooltip = value.tooltip;
  724. }
  725. }
  726. get value() {
  727. const v = {
  728. text: this.model.text,
  729. hyperlink: this.model.hyperlink
  730. };
  731. if (this.model.tooltip) {
  732. v.tooltip = this.model.tooltip;
  733. }
  734. return v;
  735. }
  736. set value(value) {
  737. this.model = {
  738. text: value.text,
  739. hyperlink: value.hyperlink
  740. };
  741. if (value.tooltip) {
  742. this.model.tooltip = value.tooltip;
  743. }
  744. }
  745. get text() {
  746. return this.model.text;
  747. }
  748. set text(value) {
  749. this.model.text = value;
  750. }
  751. /*
  752. get tooltip() {
  753. return this.model.tooltip;
  754. }
  755. set tooltip(value) {
  756. this.model.tooltip = value;
  757. } */
  758. get hyperlink() {
  759. return this.model.hyperlink;
  760. }
  761. set hyperlink(value) {
  762. this.model.hyperlink = value;
  763. }
  764. get type() {
  765. return Cell.Types.Hyperlink;
  766. }
  767. get effectiveType() {
  768. return Cell.Types.Hyperlink;
  769. }
  770. get address() {
  771. return this.model.address;
  772. }
  773. set address(value) {
  774. this.model.address = value;
  775. }
  776. toCsvString() {
  777. return this.model.hyperlink;
  778. }
  779. release() {}
  780. toString() {
  781. return this.model.text;
  782. }
  783. }
  784. class MergeValue {
  785. constructor(cell, master) {
  786. this.model = {
  787. address: cell.address,
  788. type: Cell.Types.Merge,
  789. master: master ? master.address : undefined
  790. };
  791. this._master = master;
  792. if (master) {
  793. master.addMergeRef();
  794. }
  795. }
  796. get value() {
  797. return this._master.value;
  798. }
  799. set value(value) {
  800. if (value instanceof Cell) {
  801. if (this._master) {
  802. this._master.releaseMergeRef();
  803. }
  804. value.addMergeRef();
  805. this._master = value;
  806. } else {
  807. this._master.value = value;
  808. }
  809. }
  810. isMergedTo(master) {
  811. return master === this._master;
  812. }
  813. get master() {
  814. return this._master;
  815. }
  816. get type() {
  817. return Cell.Types.Merge;
  818. }
  819. get effectiveType() {
  820. return this._master.effectiveType;
  821. }
  822. get address() {
  823. return this.model.address;
  824. }
  825. set address(value) {
  826. this.model.address = value;
  827. }
  828. toCsvString() {
  829. return '';
  830. }
  831. release() {
  832. this._master.releaseMergeRef();
  833. }
  834. toString() {
  835. return this.value.toString();
  836. }
  837. }
  838. class FormulaValue {
  839. constructor(cell, value) {
  840. this.cell = cell;
  841. this.model = {
  842. address: cell.address,
  843. type: Cell.Types.Formula,
  844. shareType: value ? value.shareType : undefined,
  845. ref: value ? value.ref : undefined,
  846. formula: value ? value.formula : undefined,
  847. sharedFormula: value ? value.sharedFormula : undefined,
  848. result: value ? value.result : undefined
  849. };
  850. }
  851. _copyModel(model) {
  852. const copy = {};
  853. const cp = name => {
  854. const value = model[name];
  855. if (value) {
  856. copy[name] = value;
  857. }
  858. };
  859. cp('formula');
  860. cp('result');
  861. cp('ref');
  862. cp('shareType');
  863. cp('sharedFormula');
  864. return copy;
  865. }
  866. get value() {
  867. return this._copyModel(this.model);
  868. }
  869. set value(value) {
  870. this.model = this._copyModel(value);
  871. }
  872. validate(value) {
  873. switch (Value.getType(value)) {
  874. case Cell.Types.Null:
  875. case Cell.Types.String:
  876. case Cell.Types.Number:
  877. case Cell.Types.Date:
  878. break;
  879. case Cell.Types.Hyperlink:
  880. case Cell.Types.Formula:
  881. default:
  882. throw new Error('Cannot process that type of result value');
  883. }
  884. }
  885. get dependencies() {
  886. // find all the ranges and cells mentioned in the formula
  887. const ranges = this.formula.match(/([a-zA-Z0-9]+!)?[A-Z]{1,3}\d{1,4}:[A-Z]{1,3}\d{1,4}/g);
  888. const cells = this.formula.replace(/([a-zA-Z0-9]+!)?[A-Z]{1,3}\d{1,4}:[A-Z]{1,3}\d{1,4}/g, '').match(/([a-zA-Z0-9]+!)?[A-Z]{1,3}\d{1,4}/g);
  889. return {
  890. ranges,
  891. cells
  892. };
  893. }
  894. get formula() {
  895. return this.model.formula || this._getTranslatedFormula();
  896. }
  897. set formula(value) {
  898. this.model.formula = value;
  899. }
  900. get formulaType() {
  901. if (this.model.formula) {
  902. return Enums.FormulaType.Master;
  903. }
  904. if (this.model.sharedFormula) {
  905. return Enums.FormulaType.Shared;
  906. }
  907. return Enums.FormulaType.None;
  908. }
  909. get result() {
  910. return this.model.result;
  911. }
  912. set result(value) {
  913. this.model.result = value;
  914. }
  915. get type() {
  916. return Cell.Types.Formula;
  917. }
  918. get effectiveType() {
  919. const v = this.model.result;
  920. if (v === null || v === undefined) {
  921. return Enums.ValueType.Null;
  922. }
  923. if (v instanceof String || typeof v === 'string') {
  924. return Enums.ValueType.String;
  925. }
  926. if (typeof v === 'number') {
  927. return Enums.ValueType.Number;
  928. }
  929. if (v instanceof Date) {
  930. return Enums.ValueType.Date;
  931. }
  932. if (v.text && v.hyperlink) {
  933. return Enums.ValueType.Hyperlink;
  934. }
  935. if (v.formula) {
  936. return Enums.ValueType.Formula;
  937. }
  938. return Enums.ValueType.Null;
  939. }
  940. get address() {
  941. return this.model.address;
  942. }
  943. set address(value) {
  944. this.model.address = value;
  945. }
  946. _getTranslatedFormula() {
  947. if (!this._translatedFormula && this.model.sharedFormula) {
  948. const {
  949. worksheet
  950. } = this.cell;
  951. const master = worksheet.findCell(this.model.sharedFormula);
  952. this._translatedFormula = master && slideFormula(master.formula, master.address, this.model.address);
  953. }
  954. return this._translatedFormula;
  955. }
  956. toCsvString() {
  957. return `${this.model.result || ''}`;
  958. }
  959. release() {}
  960. toString() {
  961. return this.model.result ? this.model.result.toString() : '';
  962. }
  963. }
  964. class SharedStringValue {
  965. constructor(cell, value) {
  966. this.model = {
  967. address: cell.address,
  968. type: Cell.Types.SharedString,
  969. value
  970. };
  971. }
  972. get value() {
  973. return this.model.value;
  974. }
  975. set value(value) {
  976. this.model.value = value;
  977. }
  978. get type() {
  979. return Cell.Types.SharedString;
  980. }
  981. get effectiveType() {
  982. return Cell.Types.SharedString;
  983. }
  984. get address() {
  985. return this.model.address;
  986. }
  987. set address(value) {
  988. this.model.address = value;
  989. }
  990. toCsvString() {
  991. return this.model.value.toString();
  992. }
  993. release() {}
  994. toString() {
  995. return this.model.value.toString();
  996. }
  997. }
  998. class BooleanValue {
  999. constructor(cell, value) {
  1000. this.model = {
  1001. address: cell.address,
  1002. type: Cell.Types.Boolean,
  1003. value
  1004. };
  1005. }
  1006. get value() {
  1007. return this.model.value;
  1008. }
  1009. set value(value) {
  1010. this.model.value = value;
  1011. }
  1012. get type() {
  1013. return Cell.Types.Boolean;
  1014. }
  1015. get effectiveType() {
  1016. return Cell.Types.Boolean;
  1017. }
  1018. get address() {
  1019. return this.model.address;
  1020. }
  1021. set address(value) {
  1022. this.model.address = value;
  1023. }
  1024. toCsvString() {
  1025. return this.model.value ? 1 : 0;
  1026. }
  1027. release() {}
  1028. toString() {
  1029. return this.model.value.toString();
  1030. }
  1031. }
  1032. class ErrorValue {
  1033. constructor(cell, value) {
  1034. this.model = {
  1035. address: cell.address,
  1036. type: Cell.Types.Error,
  1037. value
  1038. };
  1039. }
  1040. get value() {
  1041. return this.model.value;
  1042. }
  1043. set value(value) {
  1044. this.model.value = value;
  1045. }
  1046. get type() {
  1047. return Cell.Types.Error;
  1048. }
  1049. get effectiveType() {
  1050. return Cell.Types.Error;
  1051. }
  1052. get address() {
  1053. return this.model.address;
  1054. }
  1055. set address(value) {
  1056. this.model.address = value;
  1057. }
  1058. toCsvString() {
  1059. return this.toString();
  1060. }
  1061. release() {}
  1062. toString() {
  1063. return this.model.value.error.toString();
  1064. }
  1065. }
  1066. class JSONValue {
  1067. constructor(cell, value) {
  1068. this.model = {
  1069. address: cell.address,
  1070. type: Cell.Types.String,
  1071. value: JSON.stringify(value),
  1072. rawValue: value
  1073. };
  1074. }
  1075. get value() {
  1076. return this.model.rawValue;
  1077. }
  1078. set value(value) {
  1079. this.model.rawValue = value;
  1080. this.model.value = JSON.stringify(value);
  1081. }
  1082. get type() {
  1083. return Cell.Types.String;
  1084. }
  1085. get effectiveType() {
  1086. return Cell.Types.String;
  1087. }
  1088. get address() {
  1089. return this.model.address;
  1090. }
  1091. set address(value) {
  1092. this.model.address = value;
  1093. }
  1094. toCsvString() {
  1095. return this.model.value;
  1096. }
  1097. release() {}
  1098. toString() {
  1099. return this.model.value;
  1100. }
  1101. }
  1102. // Value is a place to hold common static Value type functions
  1103. const Value = {
  1104. getType(value) {
  1105. if (value === null || value === undefined) {
  1106. return Cell.Types.Null;
  1107. }
  1108. if (value instanceof String || typeof value === 'string') {
  1109. return Cell.Types.String;
  1110. }
  1111. if (typeof value === 'number') {
  1112. return Cell.Types.Number;
  1113. }
  1114. if (typeof value === 'boolean') {
  1115. return Cell.Types.Boolean;
  1116. }
  1117. if (value instanceof Date) {
  1118. return Cell.Types.Date;
  1119. }
  1120. if (value.text && value.hyperlink) {
  1121. return Cell.Types.Hyperlink;
  1122. }
  1123. if (value.formula || value.sharedFormula) {
  1124. return Cell.Types.Formula;
  1125. }
  1126. if (value.richText) {
  1127. return Cell.Types.RichText;
  1128. }
  1129. if (value.sharedString) {
  1130. return Cell.Types.SharedString;
  1131. }
  1132. if (value.error) {
  1133. return Cell.Types.Error;
  1134. }
  1135. return Cell.Types.JSON;
  1136. },
  1137. // map valueType to constructor
  1138. types: [{
  1139. t: Cell.Types.Null,
  1140. f: NullValue
  1141. }, {
  1142. t: Cell.Types.Number,
  1143. f: NumberValue
  1144. }, {
  1145. t: Cell.Types.String,
  1146. f: StringValue
  1147. }, {
  1148. t: Cell.Types.Date,
  1149. f: DateValue
  1150. }, {
  1151. t: Cell.Types.Hyperlink,
  1152. f: HyperlinkValue
  1153. }, {
  1154. t: Cell.Types.Formula,
  1155. f: FormulaValue
  1156. }, {
  1157. t: Cell.Types.Merge,
  1158. f: MergeValue
  1159. }, {
  1160. t: Cell.Types.JSON,
  1161. f: JSONValue
  1162. }, {
  1163. t: Cell.Types.SharedString,
  1164. f: SharedStringValue
  1165. }, {
  1166. t: Cell.Types.RichText,
  1167. f: RichTextValue
  1168. }, {
  1169. t: Cell.Types.Boolean,
  1170. f: BooleanValue
  1171. }, {
  1172. t: Cell.Types.Error,
  1173. f: ErrorValue
  1174. }].reduce((p, t) => {
  1175. p[t.t] = t.f;
  1176. return p;
  1177. }, []),
  1178. create(type, cell, value) {
  1179. const T = this.types[type];
  1180. if (!T) {
  1181. throw new Error(`Could not create Value of type ${type}`);
  1182. }
  1183. return new T(cell, value);
  1184. }
  1185. };
  1186. module.exports = Cell;
  1187. },{"../utils/col-cache":19,"../utils/shared-formula":23,"../utils/under-dash":26,"./enums":7,"./note":9}],4:[function(require,module,exports){
  1188. 'use strict';
  1189. const _ = require('../utils/under-dash');
  1190. const Enums = require('./enums');
  1191. const colCache = require('../utils/col-cache');
  1192. const DEFAULT_COLUMN_WIDTH = 9;
  1193. // Column defines the column properties for 1 column.
  1194. // This includes header rows, widths, key, (style), etc.
  1195. // Worksheet will condense the columns as appropriate during serialization
  1196. class Column {
  1197. constructor(worksheet, number, defn) {
  1198. this._worksheet = worksheet;
  1199. this._number = number;
  1200. if (defn !== false) {
  1201. // sometimes defn will follow
  1202. this.defn = defn;
  1203. }
  1204. }
  1205. get number() {
  1206. return this._number;
  1207. }
  1208. get worksheet() {
  1209. return this._worksheet;
  1210. }
  1211. get letter() {
  1212. return colCache.n2l(this._number);
  1213. }
  1214. get isCustomWidth() {
  1215. return this.width !== undefined && this.width !== DEFAULT_COLUMN_WIDTH;
  1216. }
  1217. get defn() {
  1218. return {
  1219. header: this._header,
  1220. key: this.key,
  1221. width: this.width,
  1222. style: this.style,
  1223. hidden: this.hidden,
  1224. outlineLevel: this.outlineLevel
  1225. };
  1226. }
  1227. set defn(value) {
  1228. if (value) {
  1229. this.key = value.key;
  1230. this.width = value.width !== undefined ? value.width : DEFAULT_COLUMN_WIDTH;
  1231. this.outlineLevel = value.outlineLevel;
  1232. if (value.style) {
  1233. this.style = value.style;
  1234. } else {
  1235. this.style = {};
  1236. }
  1237. // headers must be set after style
  1238. this.header = value.header;
  1239. this._hidden = !!value.hidden;
  1240. } else {
  1241. delete this._header;
  1242. delete this._key;
  1243. delete this.width;
  1244. this.style = {};
  1245. this.outlineLevel = 0;
  1246. }
  1247. }
  1248. get headers() {
  1249. return this._header && this._header instanceof Array ? this._header : [this._header];
  1250. }
  1251. get header() {
  1252. return this._header;
  1253. }
  1254. set header(value) {
  1255. if (value !== undefined) {
  1256. this._header = value;
  1257. this.headers.forEach((text, index) => {
  1258. this._worksheet.getCell(index + 1, this.number).value = text;
  1259. });
  1260. } else {
  1261. this._header = undefined;
  1262. }
  1263. }
  1264. get key() {
  1265. return this._key;
  1266. }
  1267. set key(value) {
  1268. const column = this._key && this._worksheet.getColumnKey(this._key);
  1269. if (column === this) {
  1270. this._worksheet.deleteColumnKey(this._key);
  1271. }
  1272. this._key = value;
  1273. if (value) {
  1274. this._worksheet.setColumnKey(this._key, this);
  1275. }
  1276. }
  1277. get hidden() {
  1278. return !!this._hidden;
  1279. }
  1280. set hidden(value) {
  1281. this._hidden = value;
  1282. }
  1283. get outlineLevel() {
  1284. return this._outlineLevel || 0;
  1285. }
  1286. set outlineLevel(value) {
  1287. this._outlineLevel = value;
  1288. }
  1289. get collapsed() {
  1290. return !!(this._outlineLevel && this._outlineLevel >= this._worksheet.properties.outlineLevelCol);
  1291. }
  1292. toString() {
  1293. return JSON.stringify({
  1294. key: this.key,
  1295. width: this.width,
  1296. headers: this.headers.length ? this.headers : undefined
  1297. });
  1298. }
  1299. equivalentTo(other) {
  1300. return this.width === other.width && this.hidden === other.hidden && this.outlineLevel === other.outlineLevel && _.isEqual(this.style, other.style);
  1301. }
  1302. get isDefault() {
  1303. if (this.isCustomWidth) {
  1304. return false;
  1305. }
  1306. if (this.hidden) {
  1307. return false;
  1308. }
  1309. if (this.outlineLevel) {
  1310. return false;
  1311. }
  1312. const s = this.style;
  1313. if (s && (s.font || s.numFmt || s.alignment || s.border || s.fill || s.protection)) {
  1314. return false;
  1315. }
  1316. return true;
  1317. }
  1318. get headerCount() {
  1319. return this.headers.length;
  1320. }
  1321. eachCell(options, iteratee) {
  1322. const colNumber = this.number;
  1323. if (!iteratee) {
  1324. iteratee = options;
  1325. options = null;
  1326. }
  1327. this._worksheet.eachRow(options, (row, rowNumber) => {
  1328. iteratee(row.getCell(colNumber), rowNumber);
  1329. });
  1330. }
  1331. get values() {
  1332. const v = [];
  1333. this.eachCell((cell, rowNumber) => {
  1334. if (cell && cell.type !== Enums.ValueType.Null) {
  1335. v[rowNumber] = cell.value;
  1336. }
  1337. });
  1338. return v;
  1339. }
  1340. set values(v) {
  1341. if (!v) {
  1342. return;
  1343. }
  1344. const colNumber = this.number;
  1345. let offset = 0;
  1346. if (v.hasOwnProperty('0')) {
  1347. // assume contiguous array, start at row 1
  1348. offset = 1;
  1349. }
  1350. v.forEach((value, index) => {
  1351. this._worksheet.getCell(index + offset, colNumber).value = value;
  1352. });
  1353. }
  1354. // =========================================================================
  1355. // styles
  1356. _applyStyle(name, value) {
  1357. this.style[name] = value;
  1358. this.eachCell(cell => {
  1359. cell[name] = value;
  1360. });
  1361. return value;
  1362. }
  1363. get numFmt() {
  1364. return this.style.numFmt;
  1365. }
  1366. set numFmt(value) {
  1367. this._applyStyle('numFmt', value);
  1368. }
  1369. get font() {
  1370. return this.style.font;
  1371. }
  1372. set font(value) {
  1373. this._applyStyle('font', value);
  1374. }
  1375. get alignment() {
  1376. return this.style.alignment;
  1377. }
  1378. set alignment(value) {
  1379. this._applyStyle('alignment', value);
  1380. }
  1381. get protection() {
  1382. return this.style.protection;
  1383. }
  1384. set protection(value) {
  1385. this._applyStyle('protection', value);
  1386. }
  1387. get border() {
  1388. return this.style.border;
  1389. }
  1390. set border(value) {
  1391. this._applyStyle('border', value);
  1392. }
  1393. get fill() {
  1394. return this.style.fill;
  1395. }
  1396. set fill(value) {
  1397. this._applyStyle('fill', value);
  1398. }
  1399. // =============================================================================
  1400. // static functions
  1401. static toModel(columns) {
  1402. // Convert array of Column into compressed list cols
  1403. const cols = [];
  1404. let col = null;
  1405. if (columns) {
  1406. columns.forEach((column, index) => {
  1407. if (column.isDefault) {
  1408. if (col) {
  1409. col = null;
  1410. }
  1411. } else if (!col || !column.equivalentTo(col)) {
  1412. col = {
  1413. min: index + 1,
  1414. max: index + 1,
  1415. width: column.width !== undefined ? column.width : DEFAULT_COLUMN_WIDTH,
  1416. style: column.style,
  1417. isCustomWidth: column.isCustomWidth,
  1418. hidden: column.hidden,
  1419. outlineLevel: column.outlineLevel,
  1420. collapsed: column.collapsed
  1421. };
  1422. cols.push(col);
  1423. } else {
  1424. col.max = index + 1;
  1425. }
  1426. });
  1427. }
  1428. return cols.length ? cols : undefined;
  1429. }
  1430. static fromModel(worksheet, cols) {
  1431. cols = cols || [];
  1432. const columns = [];
  1433. let count = 1;
  1434. let index = 0;
  1435. /**
  1436. * sort cols by min
  1437. * If it is not sorted, the subsequent column configuration will be overwritten
  1438. * */
  1439. cols = cols.sort(function (pre, next) {
  1440. return pre.min - next.min;
  1441. });
  1442. while (index < cols.length) {
  1443. const col = cols[index++];
  1444. while (count < col.min) {
  1445. columns.push(new Column(worksheet, count++));
  1446. }
  1447. while (count <= col.max) {
  1448. columns.push(new Column(worksheet, count++, col));
  1449. }
  1450. }
  1451. return columns.length ? columns : null;
  1452. }
  1453. }
  1454. module.exports = Column;
  1455. },{"../utils/col-cache":19,"../utils/under-dash":26,"./enums":7}],5:[function(require,module,exports){
  1456. "use strict";
  1457. class DataValidations {
  1458. constructor(model) {
  1459. this.model = model || {};
  1460. }
  1461. add(address, validation) {
  1462. return this.model[address] = validation;
  1463. }
  1464. find(address) {
  1465. return this.model[address];
  1466. }
  1467. remove(address) {
  1468. this.model[address] = undefined;
  1469. }
  1470. }
  1471. module.exports = DataValidations;
  1472. },{}],6:[function(require,module,exports){
  1473. 'use strict';
  1474. const _ = require('../utils/under-dash');
  1475. const colCache = require('../utils/col-cache');
  1476. const CellMatrix = require('../utils/cell-matrix');
  1477. const Range = require('./range');
  1478. const rangeRegexp = /[$](\w+)[$](\d+)(:[$](\w+)[$](\d+))?/;
  1479. class DefinedNames {
  1480. constructor() {
  1481. this.matrixMap = {};
  1482. }
  1483. getMatrix(name) {
  1484. const matrix = this.matrixMap[name] || (this.matrixMap[name] = new CellMatrix());
  1485. return matrix;
  1486. }
  1487. // add a name to a cell. locStr in the form SheetName!$col$row or SheetName!$c1$r1:$c2:$r2
  1488. add(locStr, name) {
  1489. const location = colCache.decodeEx(locStr);
  1490. this.addEx(location, name);
  1491. }
  1492. addEx(location, name) {
  1493. const matrix = this.getMatrix(name);
  1494. if (location.top) {
  1495. for (let col = location.left; col <= location.right; col++) {
  1496. for (let row = location.top; row <= location.bottom; row++) {
  1497. const address = {
  1498. sheetName: location.sheetName,
  1499. address: colCache.n2l(col) + row,
  1500. row,
  1501. col
  1502. };
  1503. matrix.addCellEx(address);
  1504. }
  1505. }
  1506. } else {
  1507. matrix.addCellEx(location);
  1508. }
  1509. }
  1510. remove(locStr, name) {
  1511. const location = colCache.decodeEx(locStr);
  1512. this.removeEx(location, name);
  1513. }
  1514. removeEx(location, name) {
  1515. const matrix = this.getMatrix(name);
  1516. matrix.removeCellEx(location);
  1517. }
  1518. removeAllNames(location) {
  1519. _.each(this.matrixMap, matrix => {
  1520. matrix.removeCellEx(location);
  1521. });
  1522. }
  1523. forEach(callback) {
  1524. _.each(this.matrixMap, (matrix, name) => {
  1525. matrix.forEach(cell => {
  1526. callback(name, cell);
  1527. });
  1528. });
  1529. }
  1530. // get all the names of a cell
  1531. getNames(addressStr) {
  1532. return this.getNamesEx(colCache.decodeEx(addressStr));
  1533. }
  1534. getNamesEx(address) {
  1535. return _.map(this.matrixMap, (matrix, name) => matrix.findCellEx(address) && name).filter(Boolean);
  1536. }
  1537. _explore(matrix, cell) {
  1538. cell.mark = false;
  1539. const {
  1540. sheetName
  1541. } = cell;
  1542. const range = new Range(cell.row, cell.col, cell.row, cell.col, sheetName);
  1543. let x;
  1544. let y;
  1545. // grow vertical - only one col to worry about
  1546. function vGrow(yy, edge) {
  1547. const c = matrix.findCellAt(sheetName, yy, cell.col);
  1548. if (!c || !c.mark) {
  1549. return false;
  1550. }
  1551. range[edge] = yy;
  1552. c.mark = false;
  1553. return true;
  1554. }
  1555. for (y = cell.row - 1; vGrow(y, 'top'); y--);
  1556. for (y = cell.row + 1; vGrow(y, 'bottom'); y++);
  1557. // grow horizontal - ensure all rows can grow
  1558. function hGrow(xx, edge) {
  1559. const cells = [];
  1560. for (y = range.top; y <= range.bottom; y++) {
  1561. const c = matrix.findCellAt(sheetName, y, xx);
  1562. if (c && c.mark) {
  1563. cells.push(c);
  1564. } else {
  1565. return false;
  1566. }
  1567. }
  1568. range[edge] = xx;
  1569. for (let i = 0; i < cells.length; i++) {
  1570. cells[i].mark = false;
  1571. }
  1572. return true;
  1573. }
  1574. for (x = cell.col - 1; hGrow(x, 'left'); x--);
  1575. for (x = cell.col + 1; hGrow(x, 'right'); x++);
  1576. return range;
  1577. }
  1578. getRanges(name, matrix) {
  1579. matrix = matrix || this.matrixMap[name];
  1580. if (!matrix) {
  1581. return {
  1582. name,
  1583. ranges: []
  1584. };
  1585. }
  1586. // mark and sweep!
  1587. matrix.forEach(cell => {
  1588. cell.mark = true;
  1589. });
  1590. const ranges = matrix.map(cell => cell.mark && this._explore(matrix, cell)).filter(Boolean).map(range => range.$shortRange);
  1591. return {
  1592. name,
  1593. ranges
  1594. };
  1595. }
  1596. normaliseMatrix(matrix, sheetName) {
  1597. // some of the cells might have shifted on specified sheet
  1598. // need to reassign rows, cols
  1599. matrix.forEachInSheet(sheetName, (cell, row, col) => {
  1600. if (cell) {
  1601. if (cell.row !== row || cell.col !== col) {
  1602. cell.row = row;
  1603. cell.col = col;
  1604. cell.address = colCache.n2l(col) + row;
  1605. }
  1606. }
  1607. });
  1608. }
  1609. spliceRows(sheetName, start, numDelete, numInsert) {
  1610. _.each(this.matrixMap, matrix => {
  1611. matrix.spliceRows(sheetName, start, numDelete, numInsert);
  1612. this.normaliseMatrix(matrix, sheetName);
  1613. });
  1614. }
  1615. spliceColumns(sheetName, start, numDelete, numInsert) {
  1616. _.each(this.matrixMap, matrix => {
  1617. matrix.spliceColumns(sheetName, start, numDelete, numInsert);
  1618. this.normaliseMatrix(matrix, sheetName);
  1619. });
  1620. }
  1621. get model() {
  1622. // To get names per cell - just iterate over all names finding cells if they exist
  1623. return _.map(this.matrixMap, (matrix, name) => this.getRanges(name, matrix)).filter(definedName => definedName.ranges.length);
  1624. }
  1625. set model(value) {
  1626. // value is [ { name, ranges }, ... ]
  1627. const matrixMap = this.matrixMap = {};
  1628. value.forEach(definedName => {
  1629. const matrix = matrixMap[definedName.name] = new CellMatrix();
  1630. definedName.ranges.forEach(rangeStr => {
  1631. if (rangeRegexp.test(rangeStr.split('!').pop() || '')) {
  1632. matrix.addCell(rangeStr);
  1633. }
  1634. });
  1635. });
  1636. }
  1637. }
  1638. module.exports = DefinedNames;
  1639. },{"../utils/cell-matrix":18,"../utils/col-cache":19,"../utils/under-dash":26,"./range":10}],7:[function(require,module,exports){
  1640. 'use strict';
  1641. module.exports = {
  1642. ValueType: {
  1643. Null: 0,
  1644. Merge: 1,
  1645. Number: 2,
  1646. String: 3,
  1647. Date: 4,
  1648. Hyperlink: 5,
  1649. Formula: 6,
  1650. SharedString: 7,
  1651. RichText: 8,
  1652. Boolean: 9,
  1653. Error: 10
  1654. },
  1655. FormulaType: {
  1656. None: 0,
  1657. Master: 1,
  1658. Shared: 2
  1659. },
  1660. RelationshipType: {
  1661. None: 0,
  1662. OfficeDocument: 1,
  1663. Worksheet: 2,
  1664. CalcChain: 3,
  1665. SharedStrings: 4,
  1666. Styles: 5,
  1667. Theme: 6,
  1668. Hyperlink: 7
  1669. },
  1670. DocumentType: {
  1671. Xlsx: 1
  1672. },
  1673. ReadingOrder: {
  1674. LeftToRight: 1,
  1675. RightToLeft: 2
  1676. },
  1677. ErrorValue: {
  1678. NotApplicable: '#N/A',
  1679. Ref: '#REF!',
  1680. Name: '#NAME?',
  1681. DivZero: '#DIV/0!',
  1682. Null: '#NULL!',
  1683. Value: '#VALUE!',
  1684. Num: '#NUM!'
  1685. }
  1686. };
  1687. },{}],8:[function(require,module,exports){
  1688. "use strict";
  1689. const colCache = require('../utils/col-cache');
  1690. const Anchor = require('./anchor');
  1691. class Image {
  1692. constructor(worksheet, model) {
  1693. this.worksheet = worksheet;
  1694. this.model = model;
  1695. }
  1696. get model() {
  1697. switch (this.type) {
  1698. case 'background':
  1699. return {
  1700. type: this.type,
  1701. imageId: this.imageId
  1702. };
  1703. case 'image':
  1704. return {
  1705. type: this.type,
  1706. imageId: this.imageId,
  1707. hyperlinks: this.range.hyperlinks,
  1708. range: {
  1709. tl: this.range.tl.model,
  1710. br: this.range.br && this.range.br.model,
  1711. ext: this.range.ext,
  1712. editAs: this.range.editAs
  1713. }
  1714. };
  1715. default:
  1716. throw new Error('Invalid Image Type');
  1717. }
  1718. }
  1719. set model(_ref) {
  1720. let {
  1721. type,
  1722. imageId,
  1723. range,
  1724. hyperlinks
  1725. } = _ref;
  1726. this.type = type;
  1727. this.imageId = imageId;
  1728. if (type === 'image') {
  1729. if (typeof range === 'string') {
  1730. const decoded = colCache.decode(range);
  1731. this.range = {
  1732. tl: new Anchor(this.worksheet, {
  1733. col: decoded.left,
  1734. row: decoded.top
  1735. }, -1),
  1736. br: new Anchor(this.worksheet, {
  1737. col: decoded.right,
  1738. row: decoded.bottom
  1739. }, 0),
  1740. editAs: 'oneCell'
  1741. };
  1742. } else {
  1743. this.range = {
  1744. tl: new Anchor(this.worksheet, range.tl, 0),
  1745. br: range.br && new Anchor(this.worksheet, range.br, 0),
  1746. ext: range.ext,
  1747. editAs: range.editAs,
  1748. hyperlinks: hyperlinks || range.hyperlinks
  1749. };
  1750. }
  1751. }
  1752. }
  1753. }
  1754. module.exports = Image;
  1755. },{"../utils/col-cache":19,"./anchor":2}],9:[function(require,module,exports){
  1756. "use strict";
  1757. const _ = require('../utils/under-dash');
  1758. class Note {
  1759. constructor(note) {
  1760. this.note = note;
  1761. }
  1762. get model() {
  1763. let value = null;
  1764. switch (typeof this.note) {
  1765. case 'string':
  1766. value = {
  1767. type: 'note',
  1768. note: {
  1769. texts: [{
  1770. text: this.note
  1771. }]
  1772. }
  1773. };
  1774. break;
  1775. default:
  1776. value = {
  1777. type: 'note',
  1778. note: this.note
  1779. };
  1780. break;
  1781. }
  1782. // Suitable for all cell comments
  1783. return _.deepMerge({}, Note.DEFAULT_CONFIGS, value);
  1784. }
  1785. set model(value) {
  1786. const {
  1787. note
  1788. } = value;
  1789. const {
  1790. texts
  1791. } = note;
  1792. if (texts.length === 1 && Object.keys(texts[0]).length === 1) {
  1793. this.note = texts[0].text;
  1794. } else {
  1795. this.note = note;
  1796. }
  1797. }
  1798. static fromModel(model) {
  1799. const note = new Note();
  1800. note.model = model;
  1801. return note;
  1802. }
  1803. }
  1804. Note.DEFAULT_CONFIGS = {
  1805. note: {
  1806. margins: {
  1807. insetmode: 'auto',
  1808. inset: [0.13, 0.13, 0.25, 0.25]
  1809. },
  1810. protection: {
  1811. locked: 'True',
  1812. lockText: 'True'
  1813. },
  1814. editAs: 'absolute'
  1815. }
  1816. };
  1817. module.exports = Note;
  1818. },{"../utils/under-dash":26}],10:[function(require,module,exports){
  1819. "use strict";
  1820. const colCache = require('../utils/col-cache');
  1821. // used by worksheet to calculate sheet dimensions
  1822. class Range {
  1823. constructor() {
  1824. this.decode(arguments);
  1825. }
  1826. setTLBR(t, l, b, r, s) {
  1827. if (arguments.length < 4) {
  1828. // setTLBR(tl, br, s)
  1829. const tl = colCache.decodeAddress(t);
  1830. const br = colCache.decodeAddress(l);
  1831. this.model = {
  1832. top: Math.min(tl.row, br.row),
  1833. left: Math.min(tl.col, br.col),
  1834. bottom: Math.max(tl.row, br.row),
  1835. right: Math.max(tl.col, br.col),
  1836. sheetName: b
  1837. };
  1838. this.setTLBR(tl.row, tl.col, br.row, br.col, s);
  1839. } else {
  1840. // setTLBR(t, l, b, r, s)
  1841. this.model = {
  1842. top: Math.min(t, b),
  1843. left: Math.min(l, r),
  1844. bottom: Math.max(t, b),
  1845. right: Math.max(l, r),
  1846. sheetName: s
  1847. };
  1848. }
  1849. }
  1850. decode(argv) {
  1851. switch (argv.length) {
  1852. case 5:
  1853. // [t,l,b,r,s]
  1854. this.setTLBR(argv[0], argv[1], argv[2], argv[3], argv[4]);
  1855. break;
  1856. case 4:
  1857. // [t,l,b,r]
  1858. this.setTLBR(argv[0], argv[1], argv[2], argv[3]);
  1859. break;
  1860. case 3:
  1861. // [tl,br,s]
  1862. this.setTLBR(argv[0], argv[1], argv[2]);
  1863. break;
  1864. case 2:
  1865. // [tl,br]
  1866. this.setTLBR(argv[0], argv[1]);
  1867. break;
  1868. case 1:
  1869. {
  1870. const value = argv[0];
  1871. if (value instanceof Range) {
  1872. // copy constructor
  1873. this.model = {
  1874. top: value.model.top,
  1875. left: value.model.left,
  1876. bottom: value.model.bottom,
  1877. right: value.model.right,
  1878. sheetName: value.sheetName
  1879. };
  1880. } else if (value instanceof Array) {
  1881. // an arguments array
  1882. this.decode(value);
  1883. } else if (value.top && value.left && value.bottom && value.right) {
  1884. // a model
  1885. this.model = {
  1886. top: value.top,
  1887. left: value.left,
  1888. bottom: value.bottom,
  1889. right: value.right,
  1890. sheetName: value.sheetName
  1891. };
  1892. } else {
  1893. // [sheetName!]tl:br
  1894. const tlbr = colCache.decodeEx(value);
  1895. if (tlbr.top) {
  1896. this.model = {
  1897. top: tlbr.top,
  1898. left: tlbr.left,
  1899. bottom: tlbr.bottom,
  1900. right: tlbr.right,
  1901. sheetName: tlbr.sheetName
  1902. };
  1903. } else {
  1904. this.model = {
  1905. top: tlbr.row,
  1906. left: tlbr.col,
  1907. bottom: tlbr.row,
  1908. right: tlbr.col,
  1909. sheetName: tlbr.sheetName
  1910. };
  1911. }
  1912. }
  1913. break;
  1914. }
  1915. case 0:
  1916. this.model = {
  1917. top: 0,
  1918. left: 0,
  1919. bottom: 0,
  1920. right: 0
  1921. };
  1922. break;
  1923. default:
  1924. throw new Error(`Invalid number of arguments to _getDimensions() - ${argv.length}`);
  1925. }
  1926. }
  1927. get top() {
  1928. return this.model.top || 1;
  1929. }
  1930. set top(value) {
  1931. this.model.top = value;
  1932. }
  1933. get left() {
  1934. return this.model.left || 1;
  1935. }
  1936. set left(value) {
  1937. this.model.left = value;
  1938. }
  1939. get bottom() {
  1940. return this.model.bottom || 1;
  1941. }
  1942. set bottom(value) {
  1943. this.model.bottom = value;
  1944. }
  1945. get right() {
  1946. return this.model.right || 1;
  1947. }
  1948. set right(value) {
  1949. this.model.right = value;
  1950. }
  1951. get sheetName() {
  1952. return this.model.sheetName;
  1953. }
  1954. set sheetName(value) {
  1955. this.model.sheetName = value;
  1956. }
  1957. get _serialisedSheetName() {
  1958. const {
  1959. sheetName
  1960. } = this.model;
  1961. if (sheetName) {
  1962. if (/^[a-zA-Z0-9]*$/.test(sheetName)) {
  1963. return `${sheetName}!`;
  1964. }
  1965. return `'${sheetName}'!`;
  1966. }
  1967. return '';
  1968. }
  1969. expand(top, left, bottom, right) {
  1970. if (!this.model.top || top < this.top) this.top = top;
  1971. if (!this.model.left || left < this.left) this.left = left;
  1972. if (!this.model.bottom || bottom > this.bottom) this.bottom = bottom;
  1973. if (!this.model.right || right > this.right) this.right = right;
  1974. }
  1975. expandRow(row) {
  1976. if (row) {
  1977. const {
  1978. dimensions,
  1979. number
  1980. } = row;
  1981. if (dimensions) {
  1982. this.expand(number, dimensions.min, number, dimensions.max);
  1983. }
  1984. }
  1985. }
  1986. expandToAddress(addressStr) {
  1987. const address = colCache.decodeEx(addressStr);
  1988. this.expand(address.row, address.col, address.row, address.col);
  1989. }
  1990. get tl() {
  1991. return colCache.n2l(this.left) + this.top;
  1992. }
  1993. get $t$l() {
  1994. return `$${colCache.n2l(this.left)}$${this.top}`;
  1995. }
  1996. get br() {
  1997. return colCache.n2l(this.right) + this.bottom;
  1998. }
  1999. get $b$r() {
  2000. return `$${colCache.n2l(this.right)}$${this.bottom}`;
  2001. }
  2002. get range() {
  2003. return `${this._serialisedSheetName + this.tl}:${this.br}`;
  2004. }
  2005. get $range() {
  2006. return `${this._serialisedSheetName + this.$t$l}:${this.$b$r}`;
  2007. }
  2008. get shortRange() {
  2009. return this.count > 1 ? this.range : this._serialisedSheetName + this.tl;
  2010. }
  2011. get $shortRange() {
  2012. return this.count > 1 ? this.$range : this._serialisedSheetName + this.$t$l;
  2013. }
  2014. get count() {
  2015. return (1 + this.bottom - this.top) * (1 + this.right - this.left);
  2016. }
  2017. toString() {
  2018. return this.range;
  2019. }
  2020. intersects(other) {
  2021. if (other.sheetName && this.sheetName && other.sheetName !== this.sheetName) return false;
  2022. if (other.bottom < this.top) return false;
  2023. if (other.top > this.bottom) return false;
  2024. if (other.right < this.left) return false;
  2025. if (other.left > this.right) return false;
  2026. return true;
  2027. }
  2028. contains(addressStr) {
  2029. const address = colCache.decodeEx(addressStr);
  2030. return this.containsEx(address);
  2031. }
  2032. containsEx(address) {
  2033. if (address.sheetName && this.sheetName && address.sheetName !== this.sheetName) return false;
  2034. return address.row >= this.top && address.row <= this.bottom && address.col >= this.left && address.col <= this.right;
  2035. }
  2036. forEachAddress(cb) {
  2037. for (let col = this.left; col <= this.right; col++) {
  2038. for (let row = this.top; row <= this.bottom; row++) {
  2039. cb(colCache.encodeAddress(row, col), row, col);
  2040. }
  2041. }
  2042. }
  2043. }
  2044. module.exports = Range;
  2045. },{"../utils/col-cache":19}],11:[function(require,module,exports){
  2046. 'use strict';
  2047. const _ = require('../utils/under-dash');
  2048. const Enums = require('./enums');
  2049. const colCache = require('../utils/col-cache');
  2050. const Cell = require('./cell');
  2051. class Row {
  2052. constructor(worksheet, number) {
  2053. this._worksheet = worksheet;
  2054. this._number = number;
  2055. this._cells = [];
  2056. this.style = {};
  2057. this.outlineLevel = 0;
  2058. }
  2059. // return the row number
  2060. get number() {
  2061. return this._number;
  2062. }
  2063. get worksheet() {
  2064. return this._worksheet;
  2065. }
  2066. // Inform Streaming Writer that this row (and all rows before it) are complete
  2067. // and ready to write. Has no effect on Worksheet document
  2068. commit() {
  2069. this._worksheet._commitRow(this); // eslint-disable-line no-underscore-dangle
  2070. }
  2071. // helps GC by breaking cyclic references
  2072. destroy() {
  2073. delete this._worksheet;
  2074. delete this._cells;
  2075. delete this.style;
  2076. }
  2077. findCell(colNumber) {
  2078. return this._cells[colNumber - 1];
  2079. }
  2080. // given {address, row, col}, find or create new cell
  2081. getCellEx(address) {
  2082. let cell = this._cells[address.col - 1];
  2083. if (!cell) {
  2084. const column = this._worksheet.getColumn(address.col);
  2085. cell = new Cell(this, column, address.address);
  2086. this._cells[address.col - 1] = cell;
  2087. }
  2088. return cell;
  2089. }
  2090. // get cell by key, letter or column number
  2091. getCell(col) {
  2092. if (typeof col === 'string') {
  2093. // is it a key?
  2094. const column = this._worksheet.getColumnKey(col);
  2095. if (column) {
  2096. col = column.number;
  2097. } else {
  2098. col = colCache.l2n(col);
  2099. }
  2100. }
  2101. return this._cells[col - 1] || this.getCellEx({
  2102. address: colCache.encodeAddress(this._number, col),
  2103. row: this._number,
  2104. col
  2105. });
  2106. }
  2107. // remove cell(s) and shift all higher cells down by count
  2108. splice(start, count) {
  2109. const nKeep = start + count;
  2110. for (var _len = arguments.length, inserts = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  2111. inserts[_key - 2] = arguments[_key];
  2112. }
  2113. const nExpand = inserts.length - count;
  2114. const nEnd = this._cells.length;
  2115. let i;
  2116. let cSrc;
  2117. let cDst;
  2118. if (nExpand < 0) {
  2119. // remove cells
  2120. for (i = start + inserts.length; i <= nEnd; i++) {
  2121. cDst = this._cells[i - 1];
  2122. cSrc = this._cells[i - nExpand - 1];
  2123. if (cSrc) {
  2124. cDst = this.getCell(i);
  2125. cDst.value = cSrc.value;
  2126. cDst.style = cSrc.style;
  2127. // eslint-disable-next-line no-underscore-dangle
  2128. cDst._comment = cSrc._comment;
  2129. } else if (cDst) {
  2130. cDst.value = null;
  2131. cDst.style = {};
  2132. // eslint-disable-next-line no-underscore-dangle
  2133. cDst._comment = undefined;
  2134. }
  2135. }
  2136. } else if (nExpand > 0) {
  2137. // insert new cells
  2138. for (i = nEnd; i >= nKeep; i--) {
  2139. cSrc = this._cells[i - 1];
  2140. if (cSrc) {
  2141. cDst = this.getCell(i + nExpand);
  2142. cDst.value = cSrc.value;
  2143. cDst.style = cSrc.style;
  2144. // eslint-disable-next-line no-underscore-dangle
  2145. cDst._comment = cSrc._comment;
  2146. } else {
  2147. this._cells[i + nExpand - 1] = undefined;
  2148. }
  2149. }
  2150. }
  2151. // now add the new values
  2152. for (i = 0; i < inserts.length; i++) {
  2153. cDst = this.getCell(start + i);
  2154. cDst.value = inserts[i];
  2155. cDst.style = {};
  2156. // eslint-disable-next-line no-underscore-dangle
  2157. cDst._comment = undefined;
  2158. }
  2159. }
  2160. // Iterate over all non-null cells in this row
  2161. eachCell(options, iteratee) {
  2162. if (!iteratee) {
  2163. iteratee = options;
  2164. options = null;
  2165. }
  2166. if (options && options.includeEmpty) {
  2167. const n = this._cells.length;
  2168. for (let i = 1; i <= n; i++) {
  2169. iteratee(this.getCell(i), i);
  2170. }
  2171. } else {
  2172. this._cells.forEach((cell, index) => {
  2173. if (cell && cell.type !== Enums.ValueType.Null) {
  2174. iteratee(cell, index + 1);
  2175. }
  2176. });
  2177. }
  2178. }
  2179. // ===========================================================================
  2180. // Page Breaks
  2181. addPageBreak(lft, rght) {
  2182. const ws = this._worksheet;
  2183. const left = Math.max(0, lft - 1) || 0;
  2184. const right = Math.max(0, rght - 1) || 16838;
  2185. const pb = {
  2186. id: this._number,
  2187. max: right,
  2188. man: 1
  2189. };
  2190. if (left) pb.min = left;
  2191. ws.rowBreaks.push(pb);
  2192. }
  2193. // return a sparse array of cell values
  2194. get values() {
  2195. const values = [];
  2196. this._cells.forEach(cell => {
  2197. if (cell && cell.type !== Enums.ValueType.Null) {
  2198. values[cell.col] = cell.value;
  2199. }
  2200. });
  2201. return values;
  2202. }
  2203. // set the values by contiguous or sparse array, or by key'd object literal
  2204. set values(value) {
  2205. // this operation is not additive - any prior cells are removed
  2206. this._cells = [];
  2207. if (!value) {
  2208. // empty row
  2209. } else if (value instanceof Array) {
  2210. let offset = 0;
  2211. if (value.hasOwnProperty('0')) {
  2212. // contiguous array - start at column 1
  2213. offset = 1;
  2214. }
  2215. value.forEach((item, index) => {
  2216. if (item !== undefined) {
  2217. this.getCellEx({
  2218. address: colCache.encodeAddress(this._number, index + offset),
  2219. row: this._number,
  2220. col: index + offset
  2221. }).value = item;
  2222. }
  2223. });
  2224. } else {
  2225. // assume object with column keys
  2226. this._worksheet.eachColumnKey((column, key) => {
  2227. if (value[key] !== undefined) {
  2228. this.getCellEx({
  2229. address: colCache.encodeAddress(this._number, column.number),
  2230. row: this._number,
  2231. col: column.number
  2232. }).value = value[key];
  2233. }
  2234. });
  2235. }
  2236. }
  2237. // returns true if the row includes at least one cell with a value
  2238. get hasValues() {
  2239. return _.some(this._cells, cell => cell && cell.type !== Enums.ValueType.Null);
  2240. }
  2241. get cellCount() {
  2242. return this._cells.length;
  2243. }
  2244. get actualCellCount() {
  2245. let count = 0;
  2246. this.eachCell(() => {
  2247. count++;
  2248. });
  2249. return count;
  2250. }
  2251. // get the min and max column number for the non-null cells in this row or null
  2252. get dimensions() {
  2253. let min = 0;
  2254. let max = 0;
  2255. this._cells.forEach(cell => {
  2256. if (cell && cell.type !== Enums.ValueType.Null) {
  2257. if (!min || min > cell.col) {
  2258. min = cell.col;
  2259. }
  2260. if (max < cell.col) {
  2261. max = cell.col;
  2262. }
  2263. }
  2264. });
  2265. return min > 0 ? {
  2266. min,
  2267. max
  2268. } : null;
  2269. }
  2270. // =========================================================================
  2271. // styles
  2272. _applyStyle(name, value) {
  2273. this.style[name] = value;
  2274. this._cells.forEach(cell => {
  2275. if (cell) {
  2276. cell[name] = value;
  2277. }
  2278. });
  2279. return value;
  2280. }
  2281. get numFmt() {
  2282. return this.style.numFmt;
  2283. }
  2284. set numFmt(value) {
  2285. this._applyStyle('numFmt', value);
  2286. }
  2287. get font() {
  2288. return this.style.font;
  2289. }
  2290. set font(value) {
  2291. this._applyStyle('font', value);
  2292. }
  2293. get alignment() {
  2294. return this.style.alignment;
  2295. }
  2296. set alignment(value) {
  2297. this._applyStyle('alignment', value);
  2298. }
  2299. get protection() {
  2300. return this.style.protection;
  2301. }
  2302. set protection(value) {
  2303. this._applyStyle('protection', value);
  2304. }
  2305. get border() {
  2306. return this.style.border;
  2307. }
  2308. set border(value) {
  2309. this._applyStyle('border', value);
  2310. }
  2311. get fill() {
  2312. return this.style.fill;
  2313. }
  2314. set fill(value) {
  2315. this._applyStyle('fill', value);
  2316. }
  2317. get hidden() {
  2318. return !!this._hidden;
  2319. }
  2320. set hidden(value) {
  2321. this._hidden = value;
  2322. }
  2323. get outlineLevel() {
  2324. return this._outlineLevel || 0;
  2325. }
  2326. set outlineLevel(value) {
  2327. this._outlineLevel = value;
  2328. }
  2329. get collapsed() {
  2330. return !!(this._outlineLevel && this._outlineLevel >= this._worksheet.properties.outlineLevelRow);
  2331. }
  2332. // =========================================================================
  2333. get model() {
  2334. const cells = [];
  2335. let min = 0;
  2336. let max = 0;
  2337. this._cells.forEach(cell => {
  2338. if (cell) {
  2339. const cellModel = cell.model;
  2340. if (cellModel) {
  2341. if (!min || min > cell.col) {
  2342. min = cell.col;
  2343. }
  2344. if (max < cell.col) {
  2345. max = cell.col;
  2346. }
  2347. cells.push(cellModel);
  2348. }
  2349. }
  2350. });
  2351. return this.height || cells.length ? {
  2352. cells,
  2353. number: this.number,
  2354. min,
  2355. max,
  2356. height: this.height,
  2357. style: this.style,
  2358. hidden: this.hidden,
  2359. outlineLevel: this.outlineLevel,
  2360. collapsed: this.collapsed
  2361. } : null;
  2362. }
  2363. set model(value) {
  2364. if (value.number !== this._number) {
  2365. throw new Error('Invalid row number in model');
  2366. }
  2367. this._cells = [];
  2368. let previousAddress;
  2369. value.cells.forEach(cellModel => {
  2370. switch (cellModel.type) {
  2371. case Cell.Types.Merge:
  2372. // special case - don't add this types
  2373. break;
  2374. default:
  2375. {
  2376. let address;
  2377. if (cellModel.address) {
  2378. address = colCache.decodeAddress(cellModel.address);
  2379. } else if (previousAddress) {
  2380. // This is a <c> element without an r attribute
  2381. // Assume that it's the cell for the next column
  2382. const {
  2383. row
  2384. } = previousAddress;
  2385. const col = previousAddress.col + 1;
  2386. address = {
  2387. row,
  2388. col,
  2389. address: colCache.encodeAddress(row, col),
  2390. $col$row: `$${colCache.n2l(col)}$${row}`
  2391. };
  2392. }
  2393. previousAddress = address;
  2394. const cell = this.getCellEx(address);
  2395. cell.model = cellModel;
  2396. break;
  2397. }
  2398. }
  2399. });
  2400. if (value.height) {
  2401. this.height = value.height;
  2402. } else {
  2403. delete this.height;
  2404. }
  2405. this.hidden = value.hidden;
  2406. this.outlineLevel = value.outlineLevel || 0;
  2407. this.style = value.style && JSON.parse(JSON.stringify(value.style)) || {};
  2408. }
  2409. }
  2410. module.exports = Row;
  2411. },{"../utils/col-cache":19,"../utils/under-dash":26,"./cell":3,"./enums":7}],12:[function(require,module,exports){
  2412. "use strict";
  2413. /* eslint-disable max-classes-per-file */
  2414. const colCache = require('../utils/col-cache');
  2415. class Column {
  2416. // wrapper around column model, allowing access and manipulation
  2417. constructor(table, column, index) {
  2418. this.table = table;
  2419. this.column = column;
  2420. this.index = index;
  2421. }
  2422. _set(name, value) {
  2423. this.table.cacheState();
  2424. this.column[name] = value;
  2425. }
  2426. /* eslint-disable lines-between-class-members */
  2427. get name() {
  2428. return this.column.name;
  2429. }
  2430. set name(value) {
  2431. this._set('name', value);
  2432. }
  2433. get filterButton() {
  2434. return this.column.filterButton;
  2435. }
  2436. set filterButton(value) {
  2437. this.column.filterButton = value;
  2438. }
  2439. get style() {
  2440. return this.column.style;
  2441. }
  2442. set style(value) {
  2443. this.column.style = value;
  2444. }
  2445. get totalsRowLabel() {
  2446. return this.column.totalsRowLabel;
  2447. }
  2448. set totalsRowLabel(value) {
  2449. this._set('totalsRowLabel', value);
  2450. }
  2451. get totalsRowFunction() {
  2452. return this.column.totalsRowFunction;
  2453. }
  2454. set totalsRowFunction(value) {
  2455. this._set('totalsRowFunction', value);
  2456. }
  2457. get totalsRowResult() {
  2458. return this.column.totalsRowResult;
  2459. }
  2460. set totalsRowResult(value) {
  2461. this._set('totalsRowResult', value);
  2462. }
  2463. get totalsRowFormula() {
  2464. return this.column.totalsRowFormula;
  2465. }
  2466. set totalsRowFormula(value) {
  2467. this._set('totalsRowFormula', value);
  2468. }
  2469. /* eslint-enable lines-between-class-members */
  2470. }
  2471. class Table {
  2472. constructor(worksheet, table) {
  2473. this.worksheet = worksheet;
  2474. if (table) {
  2475. this.table = table;
  2476. // check things are ok first
  2477. this.validate();
  2478. this.store();
  2479. }
  2480. }
  2481. getFormula(column) {
  2482. // get the correct formula to apply to the totals row
  2483. switch (column.totalsRowFunction) {
  2484. case 'none':
  2485. return null;
  2486. case 'average':
  2487. return `SUBTOTAL(101,${this.table.name}[${column.name}])`;
  2488. case 'countNums':
  2489. return `SUBTOTAL(102,${this.table.name}[${column.name}])`;
  2490. case 'count':
  2491. return `SUBTOTAL(103,${this.table.name}[${column.name}])`;
  2492. case 'max':
  2493. return `SUBTOTAL(104,${this.table.name}[${column.name}])`;
  2494. case 'min':
  2495. return `SUBTOTAL(105,${this.table.name}[${column.name}])`;
  2496. case 'stdDev':
  2497. return `SUBTOTAL(106,${this.table.name}[${column.name}])`;
  2498. case 'var':
  2499. return `SUBTOTAL(107,${this.table.name}[${column.name}])`;
  2500. case 'sum':
  2501. return `SUBTOTAL(109,${this.table.name}[${column.name}])`;
  2502. case 'custom':
  2503. return column.totalsRowFormula;
  2504. default:
  2505. throw new Error(`Invalid Totals Row Function: ${column.totalsRowFunction}`);
  2506. }
  2507. }
  2508. get width() {
  2509. // width of the table
  2510. return this.table.columns.length;
  2511. }
  2512. get height() {
  2513. // height of the table data
  2514. return this.table.rows.length;
  2515. }
  2516. get filterHeight() {
  2517. // height of the table data plus optional header row
  2518. return this.height + (this.table.headerRow ? 1 : 0);
  2519. }
  2520. get tableHeight() {
  2521. // full height of the table on the sheet
  2522. return this.filterHeight + (this.table.totalsRow ? 1 : 0);
  2523. }
  2524. validate() {
  2525. const {
  2526. table
  2527. } = this;
  2528. // set defaults and check is valid
  2529. const assign = (o, name, dflt) => {
  2530. if (o[name] === undefined) {
  2531. o[name] = dflt;
  2532. }
  2533. };
  2534. assign(table, 'headerRow', true);
  2535. assign(table, 'totalsRow', false);
  2536. assign(table, 'style', {});
  2537. assign(table.style, 'theme', 'TableStyleMedium2');
  2538. assign(table.style, 'showFirstColumn', false);
  2539. assign(table.style, 'showLastColumn', false);
  2540. assign(table.style, 'showRowStripes', false);
  2541. assign(table.style, 'showColumnStripes', false);
  2542. const assert = (test, message) => {
  2543. if (!test) {
  2544. throw new Error(message);
  2545. }
  2546. };
  2547. assert(table.ref, 'Table must have ref');
  2548. assert(table.columns, 'Table must have column definitions');
  2549. assert(table.rows, 'Table must have row definitions');
  2550. table.tl = colCache.decodeAddress(table.ref);
  2551. const {
  2552. row,
  2553. col
  2554. } = table.tl;
  2555. assert(row > 0, 'Table must be on valid row');
  2556. assert(col > 0, 'Table must be on valid col');
  2557. const {
  2558. width,
  2559. filterHeight,
  2560. tableHeight
  2561. } = this;
  2562. // autoFilterRef is a range that includes optional headers only
  2563. table.autoFilterRef = colCache.encode(row, col, row + filterHeight - 1, col + width - 1);
  2564. // tableRef is a range that includes optional headers and totals
  2565. table.tableRef = colCache.encode(row, col, row + tableHeight - 1, col + width - 1);
  2566. table.columns.forEach((column, i) => {
  2567. assert(column.name, `Column ${i} must have a name`);
  2568. if (i === 0) {
  2569. assign(column, 'totalsRowLabel', 'Total');
  2570. } else {
  2571. assign(column, 'totalsRowFunction', 'none');
  2572. column.totalsRowFormula = this.getFormula(column);
  2573. }
  2574. });
  2575. }
  2576. store() {
  2577. // where the table needs to store table data, headers, footers in
  2578. // the sheet...
  2579. const assignStyle = (cell, style) => {
  2580. if (style) {
  2581. Object.keys(style).forEach(key => {
  2582. cell[key] = style[key];
  2583. });
  2584. }
  2585. };
  2586. const {
  2587. worksheet,
  2588. table
  2589. } = this;
  2590. const {
  2591. row,
  2592. col
  2593. } = table.tl;
  2594. let count = 0;
  2595. if (table.headerRow) {
  2596. const r = worksheet.getRow(row + count++);
  2597. table.columns.forEach((column, j) => {
  2598. const {
  2599. style,
  2600. name
  2601. } = column;
  2602. const cell = r.getCell(col + j);
  2603. cell.value = name;
  2604. assignStyle(cell, style);
  2605. });
  2606. }
  2607. table.rows.forEach(data => {
  2608. const r = worksheet.getRow(row + count++);
  2609. data.forEach((value, j) => {
  2610. const cell = r.getCell(col + j);
  2611. cell.value = value;
  2612. assignStyle(cell, table.columns[j].style);
  2613. });
  2614. });
  2615. if (table.totalsRow) {
  2616. const r = worksheet.getRow(row + count++);
  2617. table.columns.forEach((column, j) => {
  2618. const cell = r.getCell(col + j);
  2619. if (j === 0) {
  2620. cell.value = column.totalsRowLabel;
  2621. } else {
  2622. const formula = this.getFormula(column);
  2623. if (formula) {
  2624. cell.value = {
  2625. formula: column.totalsRowFormula,
  2626. result: column.totalsRowResult
  2627. };
  2628. } else {
  2629. cell.value = null;
  2630. }
  2631. }
  2632. assignStyle(cell, column.style);
  2633. });
  2634. }
  2635. }
  2636. load(worksheet) {
  2637. // where the table will read necessary features from a loaded sheet
  2638. const {
  2639. table
  2640. } = this;
  2641. const {
  2642. row,
  2643. col
  2644. } = table.tl;
  2645. let count = 0;
  2646. if (table.headerRow) {
  2647. const r = worksheet.getRow(row + count++);
  2648. table.columns.forEach((column, j) => {
  2649. const cell = r.getCell(col + j);
  2650. cell.value = column.name;
  2651. });
  2652. }
  2653. table.rows.forEach(data => {
  2654. const r = worksheet.getRow(row + count++);
  2655. data.forEach((value, j) => {
  2656. const cell = r.getCell(col + j);
  2657. cell.value = value;
  2658. });
  2659. });
  2660. if (table.totalsRow) {
  2661. const r = worksheet.getRow(row + count++);
  2662. table.columns.forEach((column, j) => {
  2663. const cell = r.getCell(col + j);
  2664. if (j === 0) {
  2665. cell.value = column.totalsRowLabel;
  2666. } else {
  2667. const formula = this.getFormula(column);
  2668. if (formula) {
  2669. cell.value = {
  2670. formula: column.totalsRowFormula,
  2671. result: column.totalsRowResult
  2672. };
  2673. }
  2674. }
  2675. });
  2676. }
  2677. }
  2678. get model() {
  2679. return this.table;
  2680. }
  2681. set model(value) {
  2682. this.table = value;
  2683. }
  2684. // ================================================================
  2685. // TODO: Mutating methods
  2686. cacheState() {
  2687. if (!this._cache) {
  2688. this._cache = {
  2689. ref: this.ref,
  2690. width: this.width,
  2691. tableHeight: this.tableHeight
  2692. };
  2693. }
  2694. }
  2695. commit() {
  2696. // changes may have been made that might have on-sheet effects
  2697. if (!this._cache) {
  2698. return;
  2699. }
  2700. // check things are ok first
  2701. this.validate();
  2702. const ref = colCache.decodeAddress(this._cache.ref);
  2703. if (this.ref !== this._cache.ref) {
  2704. // wipe out whole table footprint at previous location
  2705. for (let i = 0; i < this._cache.tableHeight; i++) {
  2706. const row = this.worksheet.getRow(ref.row + i);
  2707. for (let j = 0; j < this._cache.width; j++) {
  2708. const cell = row.getCell(ref.col + j);
  2709. cell.value = null;
  2710. }
  2711. }
  2712. } else {
  2713. // clear out below table if it has shrunk
  2714. for (let i = this.tableHeight; i < this._cache.tableHeight; i++) {
  2715. const row = this.worksheet.getRow(ref.row + i);
  2716. for (let j = 0; j < this._cache.width; j++) {
  2717. const cell = row.getCell(ref.col + j);
  2718. cell.value = null;
  2719. }
  2720. }
  2721. // clear out to right of table if it has lost columns
  2722. for (let i = 0; i < this.tableHeight; i++) {
  2723. const row = this.worksheet.getRow(ref.row + i);
  2724. for (let j = this.width; j < this._cache.width; j++) {
  2725. const cell = row.getCell(ref.col + j);
  2726. cell.value = null;
  2727. }
  2728. }
  2729. }
  2730. this.store();
  2731. }
  2732. addRow(values, rowNumber) {
  2733. // Add a row of data, either insert at rowNumber or append
  2734. this.cacheState();
  2735. if (rowNumber === undefined) {
  2736. this.table.rows.push(values);
  2737. } else {
  2738. this.table.rows.splice(rowNumber, 0, values);
  2739. }
  2740. }
  2741. removeRows(rowIndex) {
  2742. let count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  2743. // Remove a rows of data
  2744. this.cacheState();
  2745. this.table.rows.splice(rowIndex, count);
  2746. }
  2747. getColumn(colIndex) {
  2748. const column = this.table.columns[colIndex];
  2749. return new Column(this, column, colIndex);
  2750. }
  2751. addColumn(column, values, colIndex) {
  2752. // Add a new column, including column defn and values
  2753. // Inserts at colNumber or adds to the right
  2754. this.cacheState();
  2755. if (colIndex === undefined) {
  2756. this.table.columns.push(column);
  2757. this.table.rows.forEach((row, i) => {
  2758. row.push(values[i]);
  2759. });
  2760. } else {
  2761. this.table.columns.splice(colIndex, 0, column);
  2762. this.table.rows.forEach((row, i) => {
  2763. row.splice(colIndex, 0, values[i]);
  2764. });
  2765. }
  2766. }
  2767. removeColumns(colIndex) {
  2768. let count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  2769. // Remove a column with data
  2770. this.cacheState();
  2771. this.table.columns.splice(colIndex, count);
  2772. this.table.rows.forEach(row => {
  2773. row.splice(colIndex, count);
  2774. });
  2775. }
  2776. _assign(target, prop, value) {
  2777. this.cacheState();
  2778. target[prop] = value;
  2779. }
  2780. /* eslint-disable lines-between-class-members */
  2781. get ref() {
  2782. return this.table.ref;
  2783. }
  2784. set ref(value) {
  2785. this._assign(this.table, 'ref', value);
  2786. }
  2787. get name() {
  2788. return this.table.name;
  2789. }
  2790. set name(value) {
  2791. this.table.name = value;
  2792. }
  2793. get displayName() {
  2794. return this.table.displyName || this.table.name;
  2795. }
  2796. set displayNamename(value) {
  2797. this.table.displayName = value;
  2798. }
  2799. get headerRow() {
  2800. return this.table.headerRow;
  2801. }
  2802. set headerRow(value) {
  2803. this._assign(this.table, 'headerRow', value);
  2804. }
  2805. get totalsRow() {
  2806. return this.table.totalsRow;
  2807. }
  2808. set totalsRow(value) {
  2809. this._assign(this.table, 'totalsRow', value);
  2810. }
  2811. get theme() {
  2812. return this.table.style.name;
  2813. }
  2814. set theme(value) {
  2815. this.table.style.name = value;
  2816. }
  2817. get showFirstColumn() {
  2818. return this.table.style.showFirstColumn;
  2819. }
  2820. set showFirstColumn(value) {
  2821. this.table.style.showFirstColumn = value;
  2822. }
  2823. get showLastColumn() {
  2824. return this.table.style.showLastColumn;
  2825. }
  2826. set showLastColumn(value) {
  2827. this.table.style.showLastColumn = value;
  2828. }
  2829. get showRowStripes() {
  2830. return this.table.style.showRowStripes;
  2831. }
  2832. set showRowStripes(value) {
  2833. this.table.style.showRowStripes = value;
  2834. }
  2835. get showColumnStripes() {
  2836. return this.table.style.showColumnStripes;
  2837. }
  2838. set showColumnStripes(value) {
  2839. this.table.style.showColumnStripes = value;
  2840. }
  2841. /* eslint-enable lines-between-class-members */
  2842. }
  2843. module.exports = Table;
  2844. },{"../utils/col-cache":19}],13:[function(require,module,exports){
  2845. 'use strict';
  2846. const Worksheet = require('./worksheet');
  2847. const DefinedNames = require('./defined-names');
  2848. const XLSX = require('../xlsx/xlsx');
  2849. const CSV = require('../csv/csv');
  2850. // Workbook requirements
  2851. // Load and Save from file and stream
  2852. // Access/Add/Delete individual worksheets
  2853. // Manage String table, Hyperlink table, etc.
  2854. // Manage scaffolding for contained objects to write to/read from
  2855. class Workbook {
  2856. constructor() {
  2857. this.category = '';
  2858. this.company = '';
  2859. this.created = new Date();
  2860. this.description = '';
  2861. this.keywords = '';
  2862. this.manager = '';
  2863. this.modified = this.created;
  2864. this.properties = {};
  2865. this.calcProperties = {};
  2866. this._worksheets = [];
  2867. this.subject = '';
  2868. this.title = '';
  2869. this.views = [];
  2870. this.media = [];
  2871. this._definedNames = new DefinedNames();
  2872. }
  2873. get xlsx() {
  2874. if (!this._xlsx) this._xlsx = new XLSX(this);
  2875. return this._xlsx;
  2876. }
  2877. get csv() {
  2878. if (!this._csv) this._csv = new CSV(this);
  2879. return this._csv;
  2880. }
  2881. get nextId() {
  2882. // find the next unique spot to add worksheet
  2883. for (let i = 1; i < this._worksheets.length; i++) {
  2884. if (!this._worksheets[i]) {
  2885. return i;
  2886. }
  2887. }
  2888. return this._worksheets.length || 1;
  2889. }
  2890. addWorksheet(name, options) {
  2891. const id = this.nextId;
  2892. // if options is a color, call it tabColor (and signal deprecated message)
  2893. if (options) {
  2894. if (typeof options === 'string') {
  2895. // eslint-disable-next-line no-console
  2896. console.trace('tabColor argument is now deprecated. Please use workbook.addWorksheet(name, {properties: { tabColor: { argb: "rbg value" } }');
  2897. options = {
  2898. properties: {
  2899. tabColor: {
  2900. argb: options
  2901. }
  2902. }
  2903. };
  2904. } else if (options.argb || options.theme || options.indexed) {
  2905. // eslint-disable-next-line no-console
  2906. console.trace('tabColor argument is now deprecated. Please use workbook.addWorksheet(name, {properties: { tabColor: { ... } }');
  2907. options = {
  2908. properties: {
  2909. tabColor: options
  2910. }
  2911. };
  2912. }
  2913. }
  2914. const lastOrderNo = this._worksheets.reduce((acc, ws) => (ws && ws.orderNo) > acc ? ws.orderNo : acc, 0);
  2915. const worksheetOptions = Object.assign({}, options, {
  2916. id,
  2917. name,
  2918. orderNo: lastOrderNo + 1,
  2919. workbook: this
  2920. });
  2921. const worksheet = new Worksheet(worksheetOptions);
  2922. this._worksheets[id] = worksheet;
  2923. return worksheet;
  2924. }
  2925. removeWorksheetEx(worksheet) {
  2926. delete this._worksheets[worksheet.id];
  2927. }
  2928. removeWorksheet(id) {
  2929. const worksheet = this.getWorksheet(id);
  2930. if (worksheet) {
  2931. worksheet.destroy();
  2932. }
  2933. }
  2934. getWorksheet(id) {
  2935. if (id === undefined) {
  2936. return this._worksheets.find(Boolean);
  2937. }
  2938. if (typeof id === 'number') {
  2939. return this._worksheets[id];
  2940. }
  2941. if (typeof id === 'string') {
  2942. return this._worksheets.find(worksheet => worksheet && worksheet.name === id);
  2943. }
  2944. return undefined;
  2945. }
  2946. get worksheets() {
  2947. // return a clone of _worksheets
  2948. return this._worksheets.slice(1).sort((a, b) => a.orderNo - b.orderNo).filter(Boolean);
  2949. }
  2950. eachSheet(iteratee) {
  2951. this.worksheets.forEach(sheet => {
  2952. iteratee(sheet, sheet.id);
  2953. });
  2954. }
  2955. get definedNames() {
  2956. return this._definedNames;
  2957. }
  2958. clearThemes() {
  2959. // Note: themes are not an exposed feature, meddle at your peril!
  2960. this._themes = undefined;
  2961. }
  2962. addImage(image) {
  2963. // TODO: validation?
  2964. const id = this.media.length;
  2965. this.media.push(Object.assign({}, image, {
  2966. type: 'image'
  2967. }));
  2968. return id;
  2969. }
  2970. getImage(id) {
  2971. return this.media[id];
  2972. }
  2973. get model() {
  2974. return {
  2975. creator: this.creator || 'Unknown',
  2976. lastModifiedBy: this.lastModifiedBy || 'Unknown',
  2977. lastPrinted: this.lastPrinted,
  2978. created: this.created,
  2979. modified: this.modified,
  2980. properties: this.properties,
  2981. worksheets: this.worksheets.map(worksheet => worksheet.model),
  2982. sheets: this.worksheets.map(ws => ws.model).filter(Boolean),
  2983. definedNames: this._definedNames.model,
  2984. views: this.views,
  2985. company: this.company,
  2986. manager: this.manager,
  2987. title: this.title,
  2988. subject: this.subject,
  2989. keywords: this.keywords,
  2990. category: this.category,
  2991. description: this.description,
  2992. language: this.language,
  2993. revision: this.revision,
  2994. contentStatus: this.contentStatus,
  2995. themes: this._themes,
  2996. media: this.media,
  2997. calcProperties: this.calcProperties
  2998. };
  2999. }
  3000. set model(value) {
  3001. this.creator = value.creator;
  3002. this.lastModifiedBy = value.lastModifiedBy;
  3003. this.lastPrinted = value.lastPrinted;
  3004. this.created = value.created;
  3005. this.modified = value.modified;
  3006. this.company = value.company;
  3007. this.manager = value.manager;
  3008. this.title = value.title;
  3009. this.subject = value.subject;
  3010. this.keywords = value.keywords;
  3011. this.category = value.category;
  3012. this.description = value.description;
  3013. this.language = value.language;
  3014. this.revision = value.revision;
  3015. this.contentStatus = value.contentStatus;
  3016. this.properties = value.properties;
  3017. this.calcProperties = value.calcProperties;
  3018. this._worksheets = [];
  3019. value.worksheets.forEach(worksheetModel => {
  3020. const {
  3021. id,
  3022. name,
  3023. state
  3024. } = worksheetModel;
  3025. const orderNo = value.sheets && value.sheets.findIndex(ws => ws.id === id);
  3026. const worksheet = this._worksheets[id] = new Worksheet({
  3027. id,
  3028. name,
  3029. orderNo,
  3030. state,
  3031. workbook: this
  3032. });
  3033. worksheet.model = worksheetModel;
  3034. });
  3035. this._definedNames.model = value.definedNames;
  3036. this.views = value.views;
  3037. this._themes = value.themes;
  3038. this.media = value.media || [];
  3039. }
  3040. }
  3041. module.exports = Workbook;
  3042. },{"../csv/csv":1,"../xlsx/xlsx":144,"./defined-names":6,"./worksheet":14}],14:[function(require,module,exports){
  3043. "use strict";
  3044. const _ = require('../utils/under-dash');
  3045. const colCache = require('../utils/col-cache');
  3046. const Range = require('./range');
  3047. const Row = require('./row');
  3048. const Column = require('./column');
  3049. const Enums = require('./enums');
  3050. const Image = require('./image');
  3051. const Table = require('./table');
  3052. const DataValidations = require('./data-validations');
  3053. const Encryptor = require('../utils/encryptor');
  3054. const {
  3055. copyStyle
  3056. } = require('../utils/copy-style');
  3057. // Worksheet requirements
  3058. // Operate as sheet inside workbook or standalone
  3059. // Load and Save from file and stream
  3060. // Access/Add/Delete individual cells
  3061. // Manage column widths and row heights
  3062. class Worksheet {
  3063. constructor(options) {
  3064. options = options || {};
  3065. this._workbook = options.workbook;
  3066. // in a workbook, each sheet will have a number
  3067. this.id = options.id;
  3068. this.orderNo = options.orderNo;
  3069. // and a name
  3070. this.name = options.name;
  3071. // add a state
  3072. this.state = options.state || 'visible';
  3073. // rows allows access organised by row. Sparse array of arrays indexed by row-1, col
  3074. // Note: _rows is zero based. Must subtract 1 to go from cell.row to index
  3075. this._rows = [];
  3076. // column definitions
  3077. this._columns = null;
  3078. // column keys (addRow convenience): key ==> this._collumns index
  3079. this._keys = {};
  3080. // keep record of all merges
  3081. this._merges = {};
  3082. // record of all row and column pageBreaks
  3083. this.rowBreaks = [];
  3084. // for tabColor, default row height, outline levels, etc
  3085. this.properties = Object.assign({}, {
  3086. defaultRowHeight: 15,
  3087. dyDescent: 55,
  3088. outlineLevelCol: 0,
  3089. outlineLevelRow: 0
  3090. }, options.properties);
  3091. // for all things printing
  3092. this.pageSetup = Object.assign({}, {
  3093. margins: {
  3094. left: 0.7,
  3095. right: 0.7,
  3096. top: 0.75,
  3097. bottom: 0.75,
  3098. header: 0.3,
  3099. footer: 0.3
  3100. },
  3101. orientation: 'portrait',
  3102. horizontalDpi: 4294967295,
  3103. verticalDpi: 4294967295,
  3104. fitToPage: !!(options.pageSetup && (options.pageSetup.fitToWidth || options.pageSetup.fitToHeight) && !options.pageSetup.scale),
  3105. pageOrder: 'downThenOver',
  3106. blackAndWhite: false,
  3107. draft: false,
  3108. cellComments: 'None',
  3109. errors: 'displayed',
  3110. scale: 100,
  3111. fitToWidth: 1,
  3112. fitToHeight: 1,
  3113. paperSize: undefined,
  3114. showRowColHeaders: false,
  3115. showGridLines: false,
  3116. firstPageNumber: undefined,
  3117. horizontalCentered: false,
  3118. verticalCentered: false,
  3119. rowBreaks: null,
  3120. colBreaks: null
  3121. }, options.pageSetup);
  3122. this.headerFooter = Object.assign({}, {
  3123. differentFirst: false,
  3124. differentOddEven: false,
  3125. oddHeader: null,
  3126. oddFooter: null,
  3127. evenHeader: null,
  3128. evenFooter: null,
  3129. firstHeader: null,
  3130. firstFooter: null
  3131. }, options.headerFooter);
  3132. this.dataValidations = new DataValidations();
  3133. // for freezepanes, split, zoom, gridlines, etc
  3134. this.views = options.views || [];
  3135. this.autoFilter = options.autoFilter || null;
  3136. // for images, etc
  3137. this._media = [];
  3138. // worksheet protection
  3139. this.sheetProtection = null;
  3140. // for tables
  3141. this.tables = {};
  3142. this.conditionalFormattings = [];
  3143. }
  3144. get name() {
  3145. return this._name;
  3146. }
  3147. set name(name) {
  3148. if (name === undefined) {
  3149. name = `sheet${this.id}`;
  3150. }
  3151. if (this._name === name) return;
  3152. if (typeof name !== 'string') {
  3153. throw new Error('The name has to be a string.');
  3154. }
  3155. if (name === '') {
  3156. throw new Error('The name can\'t be empty.');
  3157. }
  3158. if (name === 'History') {
  3159. throw new Error('The name "History" is protected. Please use a different name.');
  3160. }
  3161. // Illegal character in worksheet name: asterisk (*), question mark (?),
  3162. // colon (:), forward slash (/ \), or bracket ([])
  3163. if (/[*?:/\\[\]]/.test(name)) {
  3164. throw new Error(`Worksheet name ${name} cannot include any of the following characters: * ? : \\ / [ ]`);
  3165. }
  3166. if (/(^')|('$)/.test(name)) {
  3167. throw new Error(`The first or last character of worksheet name cannot be a single quotation mark: ${name}`);
  3168. }
  3169. if (name && name.length > 31) {
  3170. // eslint-disable-next-line no-console
  3171. console.warn(`Worksheet name ${name} exceeds 31 chars. This will be truncated`);
  3172. name = name.substring(0, 31);
  3173. }
  3174. if (this._workbook._worksheets.find(ws => ws && ws.name.toLowerCase() === name.toLowerCase())) {
  3175. throw new Error(`Worksheet name already exists: ${name}`);
  3176. }
  3177. this._name = name;
  3178. }
  3179. get workbook() {
  3180. return this._workbook;
  3181. }
  3182. // when you're done with this worksheet, call this to remove from workbook
  3183. destroy() {
  3184. this._workbook.removeWorksheetEx(this);
  3185. }
  3186. // Get the bounding range of the cells in this worksheet
  3187. get dimensions() {
  3188. const dimensions = new Range();
  3189. this._rows.forEach(row => {
  3190. if (row) {
  3191. const rowDims = row.dimensions;
  3192. if (rowDims) {
  3193. dimensions.expand(row.number, rowDims.min, row.number, rowDims.max);
  3194. }
  3195. }
  3196. });
  3197. return dimensions;
  3198. }
  3199. // =========================================================================
  3200. // Columns
  3201. // get the current columns array.
  3202. get columns() {
  3203. return this._columns;
  3204. }
  3205. // set the columns from an array of column definitions.
  3206. // Note: any headers defined will overwrite existing values.
  3207. set columns(value) {
  3208. // calculate max header row count
  3209. this._headerRowCount = value.reduce((pv, cv) => {
  3210. const headerCount = cv.header && 1 || cv.headers && cv.headers.length || 0;
  3211. return Math.max(pv, headerCount);
  3212. }, 0);
  3213. // construct Column objects
  3214. let count = 1;
  3215. const columns = this._columns = [];
  3216. value.forEach(defn => {
  3217. const column = new Column(this, count++, false);
  3218. columns.push(column);
  3219. column.defn = defn;
  3220. });
  3221. }
  3222. getColumnKey(key) {
  3223. return this._keys[key];
  3224. }
  3225. setColumnKey(key, value) {
  3226. this._keys[key] = value;
  3227. }
  3228. deleteColumnKey(key) {
  3229. delete this._keys[key];
  3230. }
  3231. eachColumnKey(f) {
  3232. _.each(this._keys, f);
  3233. }
  3234. // get a single column by col number. If it doesn't exist, create it and any gaps before it
  3235. getColumn(c) {
  3236. if (typeof c === 'string') {
  3237. // if it matches a key'd column, return that
  3238. const col = this._keys[c];
  3239. if (col) return col;
  3240. // otherwise, assume letter
  3241. c = colCache.l2n(c);
  3242. }
  3243. if (!this._columns) {
  3244. this._columns = [];
  3245. }
  3246. if (c > this._columns.length) {
  3247. let n = this._columns.length + 1;
  3248. while (n <= c) {
  3249. this._columns.push(new Column(this, n++));
  3250. }
  3251. }
  3252. return this._columns[c - 1];
  3253. }
  3254. spliceColumns(start, count) {
  3255. const rows = this._rows;
  3256. const nRows = rows.length;
  3257. for (var _len = arguments.length, inserts = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  3258. inserts[_key - 2] = arguments[_key];
  3259. }
  3260. if (inserts.length > 0) {
  3261. // must iterate over all rows whether they exist yet or not
  3262. for (let i = 0; i < nRows; i++) {
  3263. const rowArguments = [start, count];
  3264. // eslint-disable-next-line no-loop-func
  3265. inserts.forEach(insert => {
  3266. rowArguments.push(insert[i] || null);
  3267. });
  3268. const row = this.getRow(i + 1);
  3269. // eslint-disable-next-line prefer-spread
  3270. row.splice.apply(row, rowArguments);
  3271. }
  3272. } else {
  3273. // nothing to insert, so just splice all rows
  3274. this._rows.forEach(r => {
  3275. if (r) {
  3276. r.splice(start, count);
  3277. }
  3278. });
  3279. }
  3280. // splice column definitions
  3281. const nExpand = inserts.length - count;
  3282. const nKeep = start + count;
  3283. const nEnd = this._columns.length;
  3284. if (nExpand < 0) {
  3285. for (let i = start + inserts.length; i <= nEnd; i++) {
  3286. this.getColumn(i).defn = this.getColumn(i - nExpand).defn;
  3287. }
  3288. } else if (nExpand > 0) {
  3289. for (let i = nEnd; i >= nKeep; i--) {
  3290. this.getColumn(i + nExpand).defn = this.getColumn(i).defn;
  3291. }
  3292. }
  3293. for (let i = start; i < start + inserts.length; i++) {
  3294. this.getColumn(i).defn = null;
  3295. }
  3296. // account for defined names
  3297. this.workbook.definedNames.spliceColumns(this.name, start, count, inserts.length);
  3298. }
  3299. get lastColumn() {
  3300. return this.getColumn(this.columnCount);
  3301. }
  3302. get columnCount() {
  3303. let maxCount = 0;
  3304. this.eachRow(row => {
  3305. maxCount = Math.max(maxCount, row.cellCount);
  3306. });
  3307. return maxCount;
  3308. }
  3309. get actualColumnCount() {
  3310. // performance nightmare - for each row, counts all the columns used
  3311. const counts = [];
  3312. let count = 0;
  3313. this.eachRow(row => {
  3314. row.eachCell(_ref => {
  3315. let {
  3316. col
  3317. } = _ref;
  3318. if (!counts[col]) {
  3319. counts[col] = true;
  3320. count++;
  3321. }
  3322. });
  3323. });
  3324. return count;
  3325. }
  3326. // =========================================================================
  3327. // Rows
  3328. _commitRow() {
  3329. // nop - allows streaming reader to fill a document
  3330. }
  3331. get _lastRowNumber() {
  3332. // need to cope with results of splice
  3333. const rows = this._rows;
  3334. let n = rows.length;
  3335. while (n > 0 && rows[n - 1] === undefined) {
  3336. n--;
  3337. }
  3338. return n;
  3339. }
  3340. get _nextRow() {
  3341. return this._lastRowNumber + 1;
  3342. }
  3343. get lastRow() {
  3344. if (this._rows.length) {
  3345. return this._rows[this._rows.length - 1];
  3346. }
  3347. return undefined;
  3348. }
  3349. // find a row (if exists) by row number
  3350. findRow(r) {
  3351. return this._rows[r - 1];
  3352. }
  3353. // find multiple rows (if exists) by row number
  3354. findRows(start, length) {
  3355. return this._rows.slice(start - 1, start - 1 + length);
  3356. }
  3357. get rowCount() {
  3358. return this._lastRowNumber;
  3359. }
  3360. get actualRowCount() {
  3361. // counts actual rows that have actual data
  3362. let count = 0;
  3363. this.eachRow(() => {
  3364. count++;
  3365. });
  3366. return count;
  3367. }
  3368. // get a row by row number.
  3369. getRow(r) {
  3370. let row = this._rows[r - 1];
  3371. if (!row) {
  3372. row = this._rows[r - 1] = new Row(this, r);
  3373. }
  3374. return row;
  3375. }
  3376. // get multiple rows by row number.
  3377. getRows(start, length) {
  3378. if (length < 1) return undefined;
  3379. const rows = [];
  3380. for (let i = start; i < start + length; i++) {
  3381. rows.push(this.getRow(i));
  3382. }
  3383. return rows;
  3384. }
  3385. addRow(value) {
  3386. let style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'n';
  3387. const rowNo = this._nextRow;
  3388. const row = this.getRow(rowNo);
  3389. row.values = value;
  3390. this._setStyleOption(rowNo, style[0] === 'i' ? style : 'n');
  3391. return row;
  3392. }
  3393. addRows(value) {
  3394. let style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'n';
  3395. const rows = [];
  3396. value.forEach(row => {
  3397. rows.push(this.addRow(row, style));
  3398. });
  3399. return rows;
  3400. }
  3401. insertRow(pos, value) {
  3402. let style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'n';
  3403. this.spliceRows(pos, 0, value);
  3404. this._setStyleOption(pos, style);
  3405. return this.getRow(pos);
  3406. }
  3407. insertRows(pos, values) {
  3408. let style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'n';
  3409. this.spliceRows(pos, 0, ...values);
  3410. if (style !== 'n') {
  3411. // copy over the styles
  3412. for (let i = 0; i < values.length; i++) {
  3413. if (style[0] === 'o' && this.findRow(values.length + pos + i) !== undefined) {
  3414. this._copyStyle(values.length + pos + i, pos + i, style[1] === '+');
  3415. } else if (style[0] === 'i' && this.findRow(pos - 1) !== undefined) {
  3416. this._copyStyle(pos - 1, pos + i, style[1] === '+');
  3417. }
  3418. }
  3419. }
  3420. return this.getRows(pos, values.length);
  3421. }
  3422. // set row at position to same style as of either pervious row (option 'i') or next row (option 'o')
  3423. _setStyleOption(pos) {
  3424. let style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'n';
  3425. if (style[0] === 'o' && this.findRow(pos + 1) !== undefined) {
  3426. this._copyStyle(pos + 1, pos, style[1] === '+');
  3427. } else if (style[0] === 'i' && this.findRow(pos - 1) !== undefined) {
  3428. this._copyStyle(pos - 1, pos, style[1] === '+');
  3429. }
  3430. }
  3431. _copyStyle(src, dest) {
  3432. let styleEmpty = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  3433. const rSrc = this.getRow(src);
  3434. const rDst = this.getRow(dest);
  3435. rDst.style = copyStyle(rSrc.style);
  3436. // eslint-disable-next-line no-loop-func
  3437. rSrc.eachCell({
  3438. includeEmpty: styleEmpty
  3439. }, (cell, colNumber) => {
  3440. rDst.getCell(colNumber).style = copyStyle(cell.style);
  3441. });
  3442. rDst.height = rSrc.height;
  3443. }
  3444. duplicateRow(rowNum, count) {
  3445. let insert = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  3446. // create count duplicates of rowNum
  3447. // either inserting new or overwriting existing rows
  3448. const rSrc = this._rows[rowNum - 1];
  3449. const inserts = new Array(count).fill(rSrc.values);
  3450. this.spliceRows(rowNum + 1, insert ? 0 : count, ...inserts);
  3451. // now copy styles...
  3452. for (let i = 0; i < count; i++) {
  3453. const rDst = this._rows[rowNum + i];
  3454. rDst.style = rSrc.style;
  3455. rDst.height = rSrc.height;
  3456. // eslint-disable-next-line no-loop-func
  3457. rSrc.eachCell({
  3458. includeEmpty: true
  3459. }, (cell, colNumber) => {
  3460. rDst.getCell(colNumber).style = cell.style;
  3461. });
  3462. }
  3463. }
  3464. spliceRows(start, count) {
  3465. // same problem as row.splice, except worse.
  3466. const nKeep = start + count;
  3467. for (var _len2 = arguments.length, inserts = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
  3468. inserts[_key2 - 2] = arguments[_key2];
  3469. }
  3470. const nInserts = inserts.length;
  3471. const nExpand = nInserts - count;
  3472. const nEnd = this._rows.length;
  3473. let i;
  3474. let rSrc;
  3475. if (nExpand < 0) {
  3476. // remove rows
  3477. if (start === nEnd) {
  3478. this._rows[nEnd - 1] = undefined;
  3479. }
  3480. for (i = nKeep; i <= nEnd; i++) {
  3481. rSrc = this._rows[i - 1];
  3482. if (rSrc) {
  3483. const rDst = this.getRow(i + nExpand);
  3484. rDst.values = rSrc.values;
  3485. rDst.style = rSrc.style;
  3486. rDst.height = rSrc.height;
  3487. // eslint-disable-next-line no-loop-func
  3488. rSrc.eachCell({
  3489. includeEmpty: true
  3490. }, (cell, colNumber) => {
  3491. rDst.getCell(colNumber).style = cell.style;
  3492. });
  3493. this._rows[i - 1] = undefined;
  3494. } else {
  3495. this._rows[i + nExpand - 1] = undefined;
  3496. }
  3497. }
  3498. } else if (nExpand > 0) {
  3499. // insert new cells
  3500. for (i = nEnd; i >= nKeep; i--) {
  3501. rSrc = this._rows[i - 1];
  3502. if (rSrc) {
  3503. const rDst = this.getRow(i + nExpand);
  3504. rDst.values = rSrc.values;
  3505. rDst.style = rSrc.style;
  3506. rDst.height = rSrc.height;
  3507. // eslint-disable-next-line no-loop-func
  3508. rSrc.eachCell({
  3509. includeEmpty: true
  3510. }, (cell, colNumber) => {
  3511. rDst.getCell(colNumber).style = cell.style;
  3512. // remerge cells accounting for insert offset
  3513. if (cell._value.constructor.name === 'MergeValue') {
  3514. const cellToBeMerged = this.getRow(cell._row._number + nInserts).getCell(colNumber);
  3515. const prevMaster = cell._value._master;
  3516. const newMaster = this.getRow(prevMaster._row._number + nInserts).getCell(prevMaster._column._number);
  3517. cellToBeMerged.merge(newMaster);
  3518. }
  3519. });
  3520. } else {
  3521. this._rows[i + nExpand - 1] = undefined;
  3522. }
  3523. }
  3524. }
  3525. // now copy over the new values
  3526. for (i = 0; i < nInserts; i++) {
  3527. const rDst = this.getRow(start + i);
  3528. rDst.style = {};
  3529. rDst.values = inserts[i];
  3530. }
  3531. // account for defined names
  3532. this.workbook.definedNames.spliceRows(this.name, start, count, nInserts);
  3533. }
  3534. // iterate over every row in the worksheet, including maybe empty rows
  3535. eachRow(options, iteratee) {
  3536. if (!iteratee) {
  3537. iteratee = options;
  3538. options = undefined;
  3539. }
  3540. if (options && options.includeEmpty) {
  3541. const n = this._rows.length;
  3542. for (let i = 1; i <= n; i++) {
  3543. iteratee(this.getRow(i), i);
  3544. }
  3545. } else {
  3546. this._rows.forEach(row => {
  3547. if (row && row.hasValues) {
  3548. iteratee(row, row.number);
  3549. }
  3550. });
  3551. }
  3552. }
  3553. // return all rows as sparse array
  3554. getSheetValues() {
  3555. const rows = [];
  3556. this._rows.forEach(row => {
  3557. if (row) {
  3558. rows[row.number] = row.values;
  3559. }
  3560. });
  3561. return rows;
  3562. }
  3563. // =========================================================================
  3564. // Cells
  3565. // returns the cell at [r,c] or address given by r. If not found, return undefined
  3566. findCell(r, c) {
  3567. const address = colCache.getAddress(r, c);
  3568. const row = this._rows[address.row - 1];
  3569. return row ? row.findCell(address.col) : undefined;
  3570. }
  3571. // return the cell at [r,c] or address given by r. If not found, create a new one.
  3572. getCell(r, c) {
  3573. const address = colCache.getAddress(r, c);
  3574. const row = this.getRow(address.row);
  3575. return row.getCellEx(address);
  3576. }
  3577. // =========================================================================
  3578. // Merge
  3579. // convert the range defined by ['tl:br'], [tl,br] or [t,l,b,r] into a single 'merged' cell
  3580. mergeCells() {
  3581. for (var _len3 = arguments.length, cells = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  3582. cells[_key3] = arguments[_key3];
  3583. }
  3584. const dimensions = new Range(cells);
  3585. this._mergeCellsInternal(dimensions);
  3586. }
  3587. mergeCellsWithoutStyle() {
  3588. for (var _len4 = arguments.length, cells = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  3589. cells[_key4] = arguments[_key4];
  3590. }
  3591. const dimensions = new Range(cells);
  3592. this._mergeCellsInternal(dimensions, true);
  3593. }
  3594. _mergeCellsInternal(dimensions, ignoreStyle) {
  3595. // check cells aren't already merged
  3596. _.each(this._merges, merge => {
  3597. if (merge.intersects(dimensions)) {
  3598. throw new Error('Cannot merge already merged cells');
  3599. }
  3600. });
  3601. // apply merge
  3602. const master = this.getCell(dimensions.top, dimensions.left);
  3603. for (let i = dimensions.top; i <= dimensions.bottom; i++) {
  3604. for (let j = dimensions.left; j <= dimensions.right; j++) {
  3605. // merge all but the master cell
  3606. if (i > dimensions.top || j > dimensions.left) {
  3607. this.getCell(i, j).merge(master, ignoreStyle);
  3608. }
  3609. }
  3610. }
  3611. // index merge
  3612. this._merges[master.address] = dimensions;
  3613. }
  3614. _unMergeMaster(master) {
  3615. // master is always top left of a rectangle
  3616. const merge = this._merges[master.address];
  3617. if (merge) {
  3618. for (let i = merge.top; i <= merge.bottom; i++) {
  3619. for (let j = merge.left; j <= merge.right; j++) {
  3620. this.getCell(i, j).unmerge();
  3621. }
  3622. }
  3623. delete this._merges[master.address];
  3624. }
  3625. }
  3626. get hasMerges() {
  3627. // return true if this._merges has a merge object
  3628. return _.some(this._merges, Boolean);
  3629. }
  3630. // scan the range defined by ['tl:br'], [tl,br] or [t,l,b,r] and if any cell is part of a merge,
  3631. // un-merge the group. Note this function can affect multiple merges and merge-blocks are
  3632. // atomic - either they're all merged or all un-merged.
  3633. unMergeCells() {
  3634. for (var _len5 = arguments.length, cells = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
  3635. cells[_key5] = arguments[_key5];
  3636. }
  3637. const dimensions = new Range(cells);
  3638. // find any cells in that range and unmerge them
  3639. for (let i = dimensions.top; i <= dimensions.bottom; i++) {
  3640. for (let j = dimensions.left; j <= dimensions.right; j++) {
  3641. const cell = this.findCell(i, j);
  3642. if (cell) {
  3643. if (cell.type === Enums.ValueType.Merge) {
  3644. // this cell merges to another master
  3645. this._unMergeMaster(cell.master);
  3646. } else if (this._merges[cell.address]) {
  3647. // this cell is a master
  3648. this._unMergeMaster(cell);
  3649. }
  3650. }
  3651. }
  3652. }
  3653. }
  3654. // ===========================================================================
  3655. // Shared/Array Formula
  3656. fillFormula(range, formula, results) {
  3657. let shareType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'shared';
  3658. // Define formula for top-left cell and share to rest
  3659. const decoded = colCache.decode(range);
  3660. const {
  3661. top,
  3662. left,
  3663. bottom,
  3664. right
  3665. } = decoded;
  3666. const width = right - left + 1;
  3667. const masterAddress = colCache.encodeAddress(top, left);
  3668. const isShared = shareType === 'shared';
  3669. // work out result accessor
  3670. let getResult;
  3671. if (typeof results === 'function') {
  3672. getResult = results;
  3673. } else if (Array.isArray(results)) {
  3674. if (Array.isArray(results[0])) {
  3675. getResult = (row, col) => results[row - top][col - left];
  3676. } else {
  3677. // eslint-disable-next-line no-mixed-operators
  3678. getResult = (row, col) => results[(row - top) * width + (col - left)];
  3679. }
  3680. } else {
  3681. getResult = () => undefined;
  3682. }
  3683. let first = true;
  3684. for (let r = top; r <= bottom; r++) {
  3685. for (let c = left; c <= right; c++) {
  3686. if (first) {
  3687. this.getCell(r, c).value = {
  3688. shareType,
  3689. formula,
  3690. ref: range,
  3691. result: getResult(r, c)
  3692. };
  3693. first = false;
  3694. } else {
  3695. this.getCell(r, c).value = isShared ? {
  3696. sharedFormula: masterAddress,
  3697. result: getResult(r, c)
  3698. } : getResult(r, c);
  3699. }
  3700. }
  3701. }
  3702. }
  3703. // =========================================================================
  3704. // Images
  3705. addImage(imageId, range) {
  3706. const model = {
  3707. type: 'image',
  3708. imageId,
  3709. range
  3710. };
  3711. this._media.push(new Image(this, model));
  3712. }
  3713. getImages() {
  3714. return this._media.filter(m => m.type === 'image');
  3715. }
  3716. addBackgroundImage(imageId) {
  3717. const model = {
  3718. type: 'background',
  3719. imageId
  3720. };
  3721. this._media.push(new Image(this, model));
  3722. }
  3723. getBackgroundImageId() {
  3724. const image = this._media.find(m => m.type === 'background');
  3725. return image && image.imageId;
  3726. }
  3727. // =========================================================================
  3728. // Worksheet Protection
  3729. protect(password, options) {
  3730. // TODO: make this function truly async
  3731. // perhaps marshal to worker thread or something
  3732. return new Promise(resolve => {
  3733. this.sheetProtection = {
  3734. sheet: true
  3735. };
  3736. if (options && 'spinCount' in options) {
  3737. // force spinCount to be integer >= 0
  3738. options.spinCount = Number.isFinite(options.spinCount) ? Math.round(Math.max(0, options.spinCount)) : 100000;
  3739. }
  3740. if (password) {
  3741. this.sheetProtection.algorithmName = 'SHA-512';
  3742. this.sheetProtection.saltValue = Encryptor.randomBytes(16).toString('base64');
  3743. this.sheetProtection.spinCount = options && 'spinCount' in options ? options.spinCount : 100000; // allow user specified spinCount
  3744. this.sheetProtection.hashValue = Encryptor.convertPasswordToHash(password, 'SHA512', this.sheetProtection.saltValue, this.sheetProtection.spinCount);
  3745. }
  3746. if (options) {
  3747. this.sheetProtection = Object.assign(this.sheetProtection, options);
  3748. if (!password && 'spinCount' in options) {
  3749. delete this.sheetProtection.spinCount;
  3750. }
  3751. }
  3752. resolve();
  3753. });
  3754. }
  3755. unprotect() {
  3756. this.sheetProtection = null;
  3757. }
  3758. // =========================================================================
  3759. // Tables
  3760. addTable(model) {
  3761. const table = new Table(this, model);
  3762. this.tables[model.name] = table;
  3763. return table;
  3764. }
  3765. getTable(name) {
  3766. return this.tables[name];
  3767. }
  3768. removeTable(name) {
  3769. delete this.tables[name];
  3770. }
  3771. getTables() {
  3772. return Object.values(this.tables);
  3773. }
  3774. // ===========================================================================
  3775. // Conditional Formatting
  3776. addConditionalFormatting(cf) {
  3777. this.conditionalFormattings.push(cf);
  3778. }
  3779. removeConditionalFormatting(filter) {
  3780. if (typeof filter === 'number') {
  3781. this.conditionalFormattings.splice(filter, 1);
  3782. } else if (filter instanceof Function) {
  3783. this.conditionalFormattings = this.conditionalFormattings.filter(filter);
  3784. } else {
  3785. this.conditionalFormattings = [];
  3786. }
  3787. }
  3788. // ===========================================================================
  3789. // Deprecated
  3790. get tabColor() {
  3791. // eslint-disable-next-line no-console
  3792. console.trace('worksheet.tabColor property is now deprecated. Please use worksheet.properties.tabColor');
  3793. return this.properties.tabColor;
  3794. }
  3795. set tabColor(value) {
  3796. // eslint-disable-next-line no-console
  3797. console.trace('worksheet.tabColor property is now deprecated. Please use worksheet.properties.tabColor');
  3798. this.properties.tabColor = value;
  3799. }
  3800. // ===========================================================================
  3801. // Model
  3802. get model() {
  3803. const model = {
  3804. id: this.id,
  3805. name: this.name,
  3806. dataValidations: this.dataValidations.model,
  3807. properties: this.properties,
  3808. state: this.state,
  3809. pageSetup: this.pageSetup,
  3810. headerFooter: this.headerFooter,
  3811. rowBreaks: this.rowBreaks,
  3812. views: this.views,
  3813. autoFilter: this.autoFilter,
  3814. media: this._media.map(medium => medium.model),
  3815. sheetProtection: this.sheetProtection,
  3816. tables: Object.values(this.tables).map(table => table.model),
  3817. conditionalFormattings: this.conditionalFormattings
  3818. };
  3819. // =================================================
  3820. // columns
  3821. model.cols = Column.toModel(this.columns);
  3822. // ==========================================================
  3823. // Rows
  3824. const rows = model.rows = [];
  3825. const dimensions = model.dimensions = new Range();
  3826. this._rows.forEach(row => {
  3827. const rowModel = row && row.model;
  3828. if (rowModel) {
  3829. dimensions.expand(rowModel.number, rowModel.min, rowModel.number, rowModel.max);
  3830. rows.push(rowModel);
  3831. }
  3832. });
  3833. // ==========================================================
  3834. // Merges
  3835. model.merges = [];
  3836. _.each(this._merges, merge => {
  3837. model.merges.push(merge.range);
  3838. });
  3839. return model;
  3840. }
  3841. _parseRows(model) {
  3842. this._rows = [];
  3843. model.rows.forEach(rowModel => {
  3844. const row = new Row(this, rowModel.number);
  3845. this._rows[row.number - 1] = row;
  3846. row.model = rowModel;
  3847. });
  3848. }
  3849. _parseMergeCells(model) {
  3850. _.each(model.mergeCells, merge => {
  3851. // Do not merge styles when importing an Excel file
  3852. // since each cell may have different styles intentionally.
  3853. this.mergeCellsWithoutStyle(merge);
  3854. });
  3855. }
  3856. set model(value) {
  3857. this.name = value.name;
  3858. this._columns = Column.fromModel(this, value.cols);
  3859. this._parseRows(value);
  3860. this._parseMergeCells(value);
  3861. this.dataValidations = new DataValidations(value.dataValidations);
  3862. this.properties = value.properties;
  3863. this.pageSetup = value.pageSetup;
  3864. this.headerFooter = value.headerFooter;
  3865. this.views = value.views;
  3866. this.autoFilter = value.autoFilter;
  3867. this._media = value.media.map(medium => new Image(this, medium));
  3868. this.sheetProtection = value.sheetProtection;
  3869. this.tables = value.tables.reduce((tables, table) => {
  3870. const t = new Table();
  3871. t.model = table;
  3872. tables[table.name] = t;
  3873. return tables;
  3874. }, {});
  3875. this.conditionalFormattings = value.conditionalFormattings;
  3876. }
  3877. }
  3878. module.exports = Worksheet;
  3879. },{"../utils/col-cache":19,"../utils/copy-style":20,"../utils/encryptor":21,"../utils/under-dash":26,"./column":4,"./data-validations":5,"./enums":7,"./image":8,"./range":10,"./row":11,"./table":12}],15:[function(require,module,exports){
  3880. "use strict";
  3881. // this bundle is built without polyfill leaving apps the freedom to add their own
  3882. const ExcelJS = {
  3883. Workbook: require('./doc/workbook')
  3884. };
  3885. // Object.assign mono-fill
  3886. const Enums = require('./doc/enums');
  3887. Object.keys(Enums).forEach(key => {
  3888. ExcelJS[key] = Enums[key];
  3889. });
  3890. module.exports = ExcelJS;
  3891. },{"./doc/enums":7,"./doc/workbook":13}],16:[function(require,module,exports){
  3892. "use strict";
  3893. // eslint-disable-next-line node/no-unsupported-features/node-builtins
  3894. const textDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8');
  3895. function bufferToString(chunk) {
  3896. if (typeof chunk === 'string') {
  3897. return chunk;
  3898. }
  3899. if (textDecoder) {
  3900. return textDecoder.decode(chunk);
  3901. }
  3902. return chunk.toString();
  3903. }
  3904. exports.bufferToString = bufferToString;
  3905. },{}],17:[function(require,module,exports){
  3906. "use strict";
  3907. // eslint-disable-next-line node/no-unsupported-features/node-builtins
  3908. const textEncoder = typeof TextEncoder === 'undefined' ? null : new TextEncoder('utf-8');
  3909. const {
  3910. Buffer
  3911. } = require('buffer');
  3912. function stringToBuffer(str) {
  3913. if (typeof str !== 'string') {
  3914. return str;
  3915. }
  3916. if (textEncoder) {
  3917. return Buffer.from(textEncoder.encode(str).buffer);
  3918. }
  3919. return Buffer.from(str);
  3920. }
  3921. exports.stringToBuffer = stringToBuffer;
  3922. },{"buffer":220}],18:[function(require,module,exports){
  3923. "use strict";
  3924. const _ = require('./under-dash');
  3925. const colCache = require('./col-cache');
  3926. class CellMatrix {
  3927. constructor(template) {
  3928. this.template = template;
  3929. this.sheets = {};
  3930. }
  3931. addCell(addressStr) {
  3932. this.addCellEx(colCache.decodeEx(addressStr));
  3933. }
  3934. getCell(addressStr) {
  3935. return this.findCellEx(colCache.decodeEx(addressStr), true);
  3936. }
  3937. findCell(addressStr) {
  3938. return this.findCellEx(colCache.decodeEx(addressStr), false);
  3939. }
  3940. findCellAt(sheetName, rowNumber, colNumber) {
  3941. const sheet = this.sheets[sheetName];
  3942. const row = sheet && sheet[rowNumber];
  3943. return row && row[colNumber];
  3944. }
  3945. addCellEx(address) {
  3946. if (address.top) {
  3947. for (let row = address.top; row <= address.bottom; row++) {
  3948. for (let col = address.left; col <= address.right; col++) {
  3949. this.getCellAt(address.sheetName, row, col);
  3950. }
  3951. }
  3952. } else {
  3953. this.findCellEx(address, true);
  3954. }
  3955. }
  3956. getCellEx(address) {
  3957. return this.findCellEx(address, true);
  3958. }
  3959. findCellEx(address, create) {
  3960. const sheet = this.findSheet(address, create);
  3961. const row = this.findSheetRow(sheet, address, create);
  3962. return this.findRowCell(row, address, create);
  3963. }
  3964. getCellAt(sheetName, rowNumber, colNumber) {
  3965. const sheet = this.sheets[sheetName] || (this.sheets[sheetName] = []);
  3966. const row = sheet[rowNumber] || (sheet[rowNumber] = []);
  3967. const cell = row[colNumber] || (row[colNumber] = {
  3968. sheetName,
  3969. address: colCache.n2l(colNumber) + rowNumber,
  3970. row: rowNumber,
  3971. col: colNumber
  3972. });
  3973. return cell;
  3974. }
  3975. removeCellEx(address) {
  3976. const sheet = this.findSheet(address);
  3977. if (!sheet) {
  3978. return;
  3979. }
  3980. const row = this.findSheetRow(sheet, address);
  3981. if (!row) {
  3982. return;
  3983. }
  3984. delete row[address.col];
  3985. }
  3986. forEachInSheet(sheetName, callback) {
  3987. const sheet = this.sheets[sheetName];
  3988. if (sheet) {
  3989. sheet.forEach((row, rowNumber) => {
  3990. if (row) {
  3991. row.forEach((cell, colNumber) => {
  3992. if (cell) {
  3993. callback(cell, rowNumber, colNumber);
  3994. }
  3995. });
  3996. }
  3997. });
  3998. }
  3999. }
  4000. forEach(callback) {
  4001. _.each(this.sheets, (sheet, sheetName) => {
  4002. this.forEachInSheet(sheetName, callback);
  4003. });
  4004. }
  4005. map(callback) {
  4006. const results = [];
  4007. this.forEach(cell => {
  4008. results.push(callback(cell));
  4009. });
  4010. return results;
  4011. }
  4012. findSheet(address, create) {
  4013. const name = address.sheetName;
  4014. if (this.sheets[name]) {
  4015. return this.sheets[name];
  4016. }
  4017. if (create) {
  4018. return this.sheets[name] = [];
  4019. }
  4020. return undefined;
  4021. }
  4022. findSheetRow(sheet, address, create) {
  4023. const {
  4024. row
  4025. } = address;
  4026. if (sheet && sheet[row]) {
  4027. return sheet[row];
  4028. }
  4029. if (create) {
  4030. return sheet[row] = [];
  4031. }
  4032. return undefined;
  4033. }
  4034. findRowCell(row, address, create) {
  4035. const {
  4036. col
  4037. } = address;
  4038. if (row && row[col]) {
  4039. return row[col];
  4040. }
  4041. if (create) {
  4042. return row[col] = this.template ? Object.assign(address, JSON.parse(JSON.stringify(this.template))) : address;
  4043. }
  4044. return undefined;
  4045. }
  4046. spliceRows(sheetName, start, numDelete, numInsert) {
  4047. const sheet = this.sheets[sheetName];
  4048. if (sheet) {
  4049. const inserts = [];
  4050. for (let i = 0; i < numInsert; i++) {
  4051. inserts.push([]);
  4052. }
  4053. sheet.splice(start, numDelete, ...inserts);
  4054. }
  4055. }
  4056. spliceColumns(sheetName, start, numDelete, numInsert) {
  4057. const sheet = this.sheets[sheetName];
  4058. if (sheet) {
  4059. const inserts = [];
  4060. for (let i = 0; i < numInsert; i++) {
  4061. inserts.push(null);
  4062. }
  4063. _.each(sheet, row => {
  4064. row.splice(start, numDelete, ...inserts);
  4065. });
  4066. }
  4067. }
  4068. }
  4069. module.exports = CellMatrix;
  4070. },{"./col-cache":19,"./under-dash":26}],19:[function(require,module,exports){
  4071. "use strict";
  4072. const addressRegex = /^[A-Z]+\d+$/;
  4073. // =========================================================================
  4074. // Column Letter to Number conversion
  4075. const colCache = {
  4076. _dictionary: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
  4077. _l2nFill: 0,
  4078. _l2n: {},
  4079. _n2l: [],
  4080. _level(n) {
  4081. if (n <= 26) {
  4082. return 1;
  4083. }
  4084. if (n <= 26 * 26) {
  4085. return 2;
  4086. }
  4087. return 3;
  4088. },
  4089. _fill(level) {
  4090. let c;
  4091. let v;
  4092. let l1;
  4093. let l2;
  4094. let l3;
  4095. let n = 1;
  4096. if (level >= 4) {
  4097. throw new Error('Out of bounds. Excel supports columns from 1 to 16384');
  4098. }
  4099. if (this._l2nFill < 1 && level >= 1) {
  4100. while (n <= 26) {
  4101. c = this._dictionary[n - 1];
  4102. this._n2l[n] = c;
  4103. this._l2n[c] = n;
  4104. n++;
  4105. }
  4106. this._l2nFill = 1;
  4107. }
  4108. if (this._l2nFill < 2 && level >= 2) {
  4109. n = 27;
  4110. while (n <= 26 + 26 * 26) {
  4111. v = n - (26 + 1);
  4112. l1 = v % 26;
  4113. l2 = Math.floor(v / 26);
  4114. c = this._dictionary[l2] + this._dictionary[l1];
  4115. this._n2l[n] = c;
  4116. this._l2n[c] = n;
  4117. n++;
  4118. }
  4119. this._l2nFill = 2;
  4120. }
  4121. if (this._l2nFill < 3 && level >= 3) {
  4122. n = 26 + 26 * 26 + 1;
  4123. while (n <= 16384) {
  4124. v = n - (26 * 26 + 26 + 1);
  4125. l1 = v % 26;
  4126. l2 = Math.floor(v / 26) % 26;
  4127. l3 = Math.floor(v / (26 * 26));
  4128. c = this._dictionary[l3] + this._dictionary[l2] + this._dictionary[l1];
  4129. this._n2l[n] = c;
  4130. this._l2n[c] = n;
  4131. n++;
  4132. }
  4133. this._l2nFill = 3;
  4134. }
  4135. },
  4136. l2n(l) {
  4137. if (!this._l2n[l]) {
  4138. this._fill(l.length);
  4139. }
  4140. if (!this._l2n[l]) {
  4141. throw new Error(`Out of bounds. Invalid column letter: ${l}`);
  4142. }
  4143. return this._l2n[l];
  4144. },
  4145. n2l(n) {
  4146. if (n < 1 || n > 16384) {
  4147. throw new Error(`${n} is out of bounds. Excel supports columns from 1 to 16384`);
  4148. }
  4149. if (!this._n2l[n]) {
  4150. this._fill(this._level(n));
  4151. }
  4152. return this._n2l[n];
  4153. },
  4154. // =========================================================================
  4155. // Address processing
  4156. _hash: {},
  4157. // check if value looks like an address
  4158. validateAddress(value) {
  4159. if (!addressRegex.test(value)) {
  4160. throw new Error(`Invalid Address: ${value}`);
  4161. }
  4162. return true;
  4163. },
  4164. // convert address string into structure
  4165. decodeAddress(value) {
  4166. const addr = value.length < 5 && this._hash[value];
  4167. if (addr) {
  4168. return addr;
  4169. }
  4170. let hasCol = false;
  4171. let col = '';
  4172. let colNumber = 0;
  4173. let hasRow = false;
  4174. let row = '';
  4175. let rowNumber = 0;
  4176. for (let i = 0, char; i < value.length; i++) {
  4177. char = value.charCodeAt(i);
  4178. // col should before row
  4179. if (!hasRow && char >= 65 && char <= 90) {
  4180. // 65 = 'A'.charCodeAt(0)
  4181. // 90 = 'Z'.charCodeAt(0)
  4182. hasCol = true;
  4183. col += value[i];
  4184. // colNumber starts from 1
  4185. colNumber = colNumber * 26 + char - 64;
  4186. } else if (char >= 48 && char <= 57) {
  4187. // 48 = '0'.charCodeAt(0)
  4188. // 57 = '9'.charCodeAt(0)
  4189. hasRow = true;
  4190. row += value[i];
  4191. // rowNumber starts from 0
  4192. rowNumber = rowNumber * 10 + char - 48;
  4193. } else if (hasRow && hasCol && char !== 36) {
  4194. // 36 = '$'.charCodeAt(0)
  4195. break;
  4196. }
  4197. }
  4198. if (!hasCol) {
  4199. colNumber = undefined;
  4200. } else if (colNumber > 16384) {
  4201. throw new Error(`Out of bounds. Invalid column letter: ${col}`);
  4202. }
  4203. if (!hasRow) {
  4204. rowNumber = undefined;
  4205. }
  4206. // in case $row$col
  4207. value = col + row;
  4208. const address = {
  4209. address: value,
  4210. col: colNumber,
  4211. row: rowNumber,
  4212. $col$row: `$${col}$${row}`
  4213. };
  4214. // mem fix - cache only the tl 100x100 square
  4215. if (colNumber <= 100 && rowNumber <= 100) {
  4216. this._hash[value] = address;
  4217. this._hash[address.$col$row] = address;
  4218. }
  4219. return address;
  4220. },
  4221. // convert r,c into structure (if only 1 arg, assume r is address string)
  4222. getAddress(r, c) {
  4223. if (c) {
  4224. const address = this.n2l(c) + r;
  4225. return this.decodeAddress(address);
  4226. }
  4227. return this.decodeAddress(r);
  4228. },
  4229. // convert [address], [tl:br] into address structures
  4230. decode(value) {
  4231. const parts = value.split(':');
  4232. if (parts.length === 2) {
  4233. const tl = this.decodeAddress(parts[0]);
  4234. const br = this.decodeAddress(parts[1]);
  4235. const result = {
  4236. top: Math.min(tl.row, br.row),
  4237. left: Math.min(tl.col, br.col),
  4238. bottom: Math.max(tl.row, br.row),
  4239. right: Math.max(tl.col, br.col)
  4240. };
  4241. // reconstruct tl, br and dimensions
  4242. result.tl = this.n2l(result.left) + result.top;
  4243. result.br = this.n2l(result.right) + result.bottom;
  4244. result.dimensions = `${result.tl}:${result.br}`;
  4245. return result;
  4246. }
  4247. return this.decodeAddress(value);
  4248. },
  4249. // convert [sheetName!][$]col[$]row[[$]col[$]row] into address or range structures
  4250. decodeEx(value) {
  4251. const groups = value.match(/(?:(?:(?:'((?:[^']|'')*)')|([^'^ !]*))!)?(.*)/);
  4252. const sheetName = groups[1] || groups[2]; // Qouted and unqouted groups
  4253. const reference = groups[3]; // Remaining address
  4254. const parts = reference.split(':');
  4255. if (parts.length > 1) {
  4256. let tl = this.decodeAddress(parts[0]);
  4257. let br = this.decodeAddress(parts[1]);
  4258. const top = Math.min(tl.row, br.row);
  4259. const left = Math.min(tl.col, br.col);
  4260. const bottom = Math.max(tl.row, br.row);
  4261. const right = Math.max(tl.col, br.col);
  4262. tl = this.n2l(left) + top;
  4263. br = this.n2l(right) + bottom;
  4264. return {
  4265. top,
  4266. left,
  4267. bottom,
  4268. right,
  4269. sheetName,
  4270. tl: {
  4271. address: tl,
  4272. col: left,
  4273. row: top,
  4274. $col$row: `$${this.n2l(left)}$${top}`,
  4275. sheetName
  4276. },
  4277. br: {
  4278. address: br,
  4279. col: right,
  4280. row: bottom,
  4281. $col$row: `$${this.n2l(right)}$${bottom}`,
  4282. sheetName
  4283. },
  4284. dimensions: `${tl}:${br}`
  4285. };
  4286. }
  4287. if (reference.startsWith('#')) {
  4288. return sheetName ? {
  4289. sheetName,
  4290. error: reference
  4291. } : {
  4292. error: reference
  4293. };
  4294. }
  4295. const address = this.decodeAddress(reference);
  4296. return sheetName ? {
  4297. sheetName,
  4298. ...address
  4299. } : address;
  4300. },
  4301. // convert row,col into address string
  4302. encodeAddress(row, col) {
  4303. return colCache.n2l(col) + row;
  4304. },
  4305. // convert row,col into string address or t,l,b,r into range
  4306. encode() {
  4307. switch (arguments.length) {
  4308. case 2:
  4309. return colCache.encodeAddress(arguments[0], arguments[1]);
  4310. case 4:
  4311. return `${colCache.encodeAddress(arguments[0], arguments[1])}:${colCache.encodeAddress(arguments[2], arguments[3])}`;
  4312. default:
  4313. throw new Error('Can only encode with 2 or 4 arguments');
  4314. }
  4315. },
  4316. // return true if address is contained within range
  4317. inRange(range, address) {
  4318. const [left, top,, right, bottom] = range;
  4319. const [col, row] = address;
  4320. return col >= left && col <= right && row >= top && row <= bottom;
  4321. }
  4322. };
  4323. module.exports = colCache;
  4324. },{}],20:[function(require,module,exports){
  4325. "use strict";
  4326. const oneDepthCopy = (obj, nestKeys) => ({
  4327. ...obj,
  4328. ...nestKeys.reduce((memo, key) => {
  4329. if (obj[key]) memo[key] = {
  4330. ...obj[key]
  4331. };
  4332. return memo;
  4333. }, {})
  4334. });
  4335. const setIfExists = function (src, dst, key) {
  4336. let nestKeys = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  4337. if (src[key]) dst[key] = oneDepthCopy(src[key], nestKeys);
  4338. };
  4339. const isEmptyObj = obj => Object.keys(obj).length === 0;
  4340. const copyStyle = style => {
  4341. if (!style) return style;
  4342. if (isEmptyObj(style)) return {};
  4343. const copied = {
  4344. ...style
  4345. };
  4346. setIfExists(style, copied, 'font', ['color']);
  4347. setIfExists(style, copied, 'alignment');
  4348. setIfExists(style, copied, 'protection');
  4349. if (style.border) {
  4350. setIfExists(style, copied, 'border');
  4351. setIfExists(style.border, copied.border, 'top', ['color']);
  4352. setIfExists(style.border, copied.border, 'left', ['color']);
  4353. setIfExists(style.border, copied.border, 'bottom', ['color']);
  4354. setIfExists(style.border, copied.border, 'right', ['color']);
  4355. setIfExists(style.border, copied.border, 'diagonal', ['color']);
  4356. }
  4357. if (style.fill) {
  4358. setIfExists(style, copied, 'fill', ['fgColor', 'bgColor', 'center']);
  4359. if (style.fill.stops) {
  4360. copied.fill.stops = style.fill.stops.map(s => oneDepthCopy(s, ['color']));
  4361. }
  4362. }
  4363. return copied;
  4364. };
  4365. exports.copyStyle = copyStyle;
  4366. },{}],21:[function(require,module,exports){
  4367. (function (Buffer){(function (){
  4368. 'use strict';
  4369. const crypto = require('crypto');
  4370. const Encryptor = {
  4371. /**
  4372. * Calculate a hash of the concatenated buffers with the given algorithm.
  4373. * @param {string} algorithm - The hash algorithm.
  4374. * @returns {Buffer} The hash
  4375. */
  4376. hash(algorithm) {
  4377. const hash = crypto.createHash(algorithm);
  4378. for (var _len = arguments.length, buffers = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4379. buffers[_key - 1] = arguments[_key];
  4380. }
  4381. hash.update(Buffer.concat(buffers));
  4382. return hash.digest();
  4383. },
  4384. /**
  4385. * Convert a password into an encryption key
  4386. * @param {string} password - The password
  4387. * @param {string} hashAlgorithm - The hash algoritm
  4388. * @param {string} saltValue - The salt value
  4389. * @param {number} spinCount - The spin count
  4390. * @param {number} keyBits - The length of the key in bits
  4391. * @param {Buffer} blockKey - The block key
  4392. * @returns {Buffer} The encryption key
  4393. */
  4394. convertPasswordToHash(password, hashAlgorithm, saltValue, spinCount) {
  4395. hashAlgorithm = hashAlgorithm.toLowerCase();
  4396. const hashes = crypto.getHashes();
  4397. if (hashes.indexOf(hashAlgorithm) < 0) {
  4398. throw new Error(`Hash algorithm '${hashAlgorithm}' not supported!`);
  4399. }
  4400. // Password must be in unicode buffer
  4401. const passwordBuffer = Buffer.from(password, 'utf16le');
  4402. // Generate the initial hash
  4403. let key = this.hash(hashAlgorithm, Buffer.from(saltValue, 'base64'), passwordBuffer);
  4404. // Now regenerate until spin count
  4405. for (let i = 0; i < spinCount; i++) {
  4406. const iterator = Buffer.alloc(4);
  4407. // this is the 'special' element of Excel password hashing
  4408. // that stops us from using crypto.pbkdf2()
  4409. iterator.writeUInt32LE(i, 0);
  4410. key = this.hash(hashAlgorithm, key, iterator);
  4411. }
  4412. return key.toString('base64');
  4413. },
  4414. /**
  4415. * Generates cryptographically strong pseudo-random data.
  4416. * @param size The size argument is a number indicating the number of bytes to generate.
  4417. */
  4418. randomBytes(size) {
  4419. return crypto.randomBytes(size);
  4420. }
  4421. };
  4422. module.exports = Encryptor;
  4423. }).call(this)}).call(this,require("buffer").Buffer)
  4424. },{"buffer":220,"crypto":229}],22:[function(require,module,exports){
  4425. "use strict";
  4426. const {
  4427. SaxesParser
  4428. } = require('saxes');
  4429. const {
  4430. PassThrough
  4431. } = require('readable-stream');
  4432. const {
  4433. bufferToString
  4434. } = require('./browser-buffer-decode');
  4435. module.exports = async function* (iterable) {
  4436. // TODO: Remove once node v8 is deprecated
  4437. // Detect and upgrade old streams
  4438. if (iterable.pipe && !iterable[Symbol.asyncIterator]) {
  4439. iterable = iterable.pipe(new PassThrough());
  4440. }
  4441. const saxesParser = new SaxesParser();
  4442. let error;
  4443. saxesParser.on('error', err => {
  4444. error = err;
  4445. });
  4446. let events = [];
  4447. saxesParser.on('opentag', value => events.push({
  4448. eventType: 'opentag',
  4449. value
  4450. }));
  4451. saxesParser.on('text', value => events.push({
  4452. eventType: 'text',
  4453. value
  4454. }));
  4455. saxesParser.on('closetag', value => events.push({
  4456. eventType: 'closetag',
  4457. value
  4458. }));
  4459. for await (const chunk of iterable) {
  4460. saxesParser.write(bufferToString(chunk));
  4461. // saxesParser.write and saxesParser.on() are synchronous,
  4462. // so we can only reach the below line once all events have been emitted
  4463. if (error) throw error;
  4464. // As a performance optimization, we gather all events instead of passing
  4465. // them one by one, which would cause each event to go through the event queue
  4466. yield events;
  4467. events = [];
  4468. }
  4469. };
  4470. },{"./browser-buffer-decode":16,"readable-stream":330,"saxes":334}],23:[function(require,module,exports){
  4471. "use strict";
  4472. const colCache = require('./col-cache');
  4473. // const cellRefRegex = /(([a-z_\-0-9]*)!)?[$]?([a-z]+)[$]?([1-9][0-9]*)/i;
  4474. const replacementCandidateRx = /(([a-z_\-0-9]*)!)?([a-z0-9_$]{2,})([(])?/gi;
  4475. const CRrx = /^([$])?([a-z]+)([$])?([1-9][0-9]*)$/i;
  4476. function slideFormula(formula, fromCell, toCell) {
  4477. const offset = colCache.decode(fromCell);
  4478. const to = colCache.decode(toCell);
  4479. return formula.replace(replacementCandidateRx, (refMatch, sheet, sheetMaybe, addrPart, trailingParen) => {
  4480. if (trailingParen) {
  4481. return refMatch;
  4482. }
  4483. const match = CRrx.exec(addrPart);
  4484. if (match) {
  4485. const colDollar = match[1];
  4486. const colStr = match[2].toUpperCase();
  4487. const rowDollar = match[3];
  4488. const rowStr = match[4];
  4489. if (colStr.length > 3 || colStr.length === 3 && colStr > 'XFD') {
  4490. // > XFD is the highest col number in excel 2007 and beyond, so this is a named range
  4491. return refMatch;
  4492. }
  4493. let col = colCache.l2n(colStr);
  4494. let row = parseInt(rowStr, 10);
  4495. if (!colDollar) {
  4496. col += to.col - offset.col;
  4497. }
  4498. if (!rowDollar) {
  4499. row += to.row - offset.row;
  4500. }
  4501. const res = (sheet || '') + (colDollar || '') + colCache.n2l(col) + (rowDollar || '') + row;
  4502. return res;
  4503. }
  4504. return refMatch;
  4505. });
  4506. }
  4507. module.exports = {
  4508. slideFormula
  4509. };
  4510. },{"./col-cache":19}],24:[function(require,module,exports){
  4511. (function (process,Buffer){(function (){
  4512. "use strict";
  4513. /* eslint-disable max-classes-per-file */
  4514. const Stream = require('readable-stream');
  4515. const utils = require('./utils');
  4516. const StringBuf = require('./string-buf');
  4517. // =============================================================================
  4518. // data chunks - encapsulating incoming data
  4519. class StringChunk {
  4520. constructor(data, encoding) {
  4521. this._data = data;
  4522. this._encoding = encoding;
  4523. }
  4524. get length() {
  4525. return this.toBuffer().length;
  4526. }
  4527. // copy to target buffer
  4528. copy(target, targetOffset, offset, length) {
  4529. return this.toBuffer().copy(target, targetOffset, offset, length);
  4530. }
  4531. toBuffer() {
  4532. if (!this._buffer) {
  4533. this._buffer = Buffer.from(this._data, this._encoding);
  4534. }
  4535. return this._buffer;
  4536. }
  4537. }
  4538. class StringBufChunk {
  4539. constructor(data) {
  4540. this._data = data;
  4541. }
  4542. get length() {
  4543. return this._data.length;
  4544. }
  4545. // copy to target buffer
  4546. copy(target, targetOffset, offset, length) {
  4547. // eslint-disable-next-line no-underscore-dangle
  4548. return this._data._buf.copy(target, targetOffset, offset, length);
  4549. }
  4550. toBuffer() {
  4551. return this._data.toBuffer();
  4552. }
  4553. }
  4554. class BufferChunk {
  4555. constructor(data) {
  4556. this._data = data;
  4557. }
  4558. get length() {
  4559. return this._data.length;
  4560. }
  4561. // copy to target buffer
  4562. copy(target, targetOffset, offset, length) {
  4563. this._data.copy(target, targetOffset, offset, length);
  4564. }
  4565. toBuffer() {
  4566. return this._data;
  4567. }
  4568. }
  4569. // =============================================================================
  4570. // ReadWriteBuf - a single buffer supporting simple read-write
  4571. class ReadWriteBuf {
  4572. constructor(size) {
  4573. this.size = size;
  4574. // the buffer
  4575. this.buffer = Buffer.alloc(size);
  4576. // read index
  4577. this.iRead = 0;
  4578. // write index
  4579. this.iWrite = 0;
  4580. }
  4581. toBuffer() {
  4582. if (this.iRead === 0 && this.iWrite === this.size) {
  4583. return this.buffer;
  4584. }
  4585. const buf = Buffer.alloc(this.iWrite - this.iRead);
  4586. this.buffer.copy(buf, 0, this.iRead, this.iWrite);
  4587. return buf;
  4588. }
  4589. get length() {
  4590. return this.iWrite - this.iRead;
  4591. }
  4592. get eod() {
  4593. return this.iRead === this.iWrite;
  4594. }
  4595. get full() {
  4596. return this.iWrite === this.size;
  4597. }
  4598. read(size) {
  4599. let buf;
  4600. // read size bytes from buffer and return buffer
  4601. if (size === 0) {
  4602. // special case - return null if no data requested
  4603. return null;
  4604. }
  4605. if (size === undefined || size >= this.length) {
  4606. // if no size specified or size is at least what we have then return all of the bytes
  4607. buf = this.toBuffer();
  4608. this.iRead = this.iWrite;
  4609. return buf;
  4610. }
  4611. // otherwise return a chunk
  4612. buf = Buffer.alloc(size);
  4613. this.buffer.copy(buf, 0, this.iRead, size);
  4614. this.iRead += size;
  4615. return buf;
  4616. }
  4617. write(chunk, offset, length) {
  4618. // write as many bytes from data from optional source offset
  4619. // and return number of bytes written
  4620. const size = Math.min(length, this.size - this.iWrite);
  4621. chunk.copy(this.buffer, this.iWrite, offset, offset + size);
  4622. this.iWrite += size;
  4623. return size;
  4624. }
  4625. }
  4626. // =============================================================================
  4627. // StreamBuf - a multi-purpose read-write stream
  4628. // As MemBuf - write as much data as you like. Then call toBuffer() to consolidate
  4629. // As StreamHub - pipe to multiple writables
  4630. // As readable stream - feed data into the writable part and have some other code read from it.
  4631. // Note: Not sure why but StreamBuf does not like JS "class" sugar. It fails the
  4632. // integration tests
  4633. const StreamBuf = function (options) {
  4634. options = options || {};
  4635. this.bufSize = options.bufSize || 1024 * 1024;
  4636. this.buffers = [];
  4637. // batch mode fills a buffer completely before passing the data on
  4638. // to pipes or 'readable' event listeners
  4639. this.batch = options.batch || false;
  4640. this.corked = false;
  4641. // where in the current writable buffer we're up to
  4642. this.inPos = 0;
  4643. // where in the current readable buffer we've read up to
  4644. this.outPos = 0;
  4645. // consuming pipe streams go here
  4646. this.pipes = [];
  4647. // controls emit('data')
  4648. this.paused = false;
  4649. this.encoding = null;
  4650. };
  4651. utils.inherits(StreamBuf, Stream.Duplex, {
  4652. toBuffer() {
  4653. switch (this.buffers.length) {
  4654. case 0:
  4655. return null;
  4656. case 1:
  4657. return this.buffers[0].toBuffer();
  4658. default:
  4659. return Buffer.concat(this.buffers.map(rwBuf => rwBuf.toBuffer()));
  4660. }
  4661. },
  4662. // writable
  4663. // event drain - if write returns false (which it won't), indicates when safe to write again.
  4664. // finish - end() has been called
  4665. // pipe(src) - pipe() has been called on readable
  4666. // unpipe(src) - unpipe() has been called on readable
  4667. // error - duh
  4668. _getWritableBuffer() {
  4669. if (this.buffers.length) {
  4670. const last = this.buffers[this.buffers.length - 1];
  4671. if (!last.full) {
  4672. return last;
  4673. }
  4674. }
  4675. const buf = new ReadWriteBuf(this.bufSize);
  4676. this.buffers.push(buf);
  4677. return buf;
  4678. },
  4679. async _pipe(chunk) {
  4680. const write = function (pipe) {
  4681. return new Promise(resolve => {
  4682. pipe.write(chunk.toBuffer(), () => {
  4683. resolve();
  4684. });
  4685. });
  4686. };
  4687. await Promise.all(this.pipes.map(write));
  4688. },
  4689. _writeToBuffers(chunk) {
  4690. let inPos = 0;
  4691. const inLen = chunk.length;
  4692. while (inPos < inLen) {
  4693. // find writable buffer
  4694. const buffer = this._getWritableBuffer();
  4695. // write some data
  4696. inPos += buffer.write(chunk, inPos, inLen - inPos);
  4697. }
  4698. },
  4699. async write(data, encoding, callback) {
  4700. if (encoding instanceof Function) {
  4701. callback = encoding;
  4702. encoding = 'utf8';
  4703. }
  4704. callback = callback || utils.nop;
  4705. // encapsulate data into a chunk
  4706. let chunk;
  4707. if (data instanceof StringBuf) {
  4708. chunk = new StringBufChunk(data);
  4709. } else if (data instanceof Buffer) {
  4710. chunk = new BufferChunk(data);
  4711. } else if (typeof data === 'string' || data instanceof String || data instanceof ArrayBuffer) {
  4712. chunk = new StringChunk(data, encoding);
  4713. } else {
  4714. throw new Error('Chunk must be one of type String, Buffer or StringBuf.');
  4715. }
  4716. // now, do something with the chunk
  4717. if (this.pipes.length) {
  4718. if (this.batch) {
  4719. this._writeToBuffers(chunk);
  4720. while (!this.corked && this.buffers.length > 1) {
  4721. this._pipe(this.buffers.shift());
  4722. }
  4723. } else if (!this.corked) {
  4724. await this._pipe(chunk);
  4725. callback();
  4726. } else {
  4727. this._writeToBuffers(chunk);
  4728. process.nextTick(callback);
  4729. }
  4730. } else {
  4731. if (!this.paused) {
  4732. this.emit('data', chunk.toBuffer());
  4733. }
  4734. this._writeToBuffers(chunk);
  4735. this.emit('readable');
  4736. }
  4737. return true;
  4738. },
  4739. cork() {
  4740. this.corked = true;
  4741. },
  4742. _flush( /* destination */
  4743. ) {
  4744. // if we have comsumers...
  4745. if (this.pipes.length) {
  4746. // and there's stuff not written
  4747. while (this.buffers.length) {
  4748. this._pipe(this.buffers.shift());
  4749. }
  4750. }
  4751. },
  4752. uncork() {
  4753. this.corked = false;
  4754. this._flush();
  4755. },
  4756. end(chunk, encoding, callback) {
  4757. const writeComplete = error => {
  4758. if (error) {
  4759. callback(error);
  4760. } else {
  4761. this._flush();
  4762. this.pipes.forEach(pipe => {
  4763. pipe.end();
  4764. });
  4765. this.emit('finish');
  4766. }
  4767. };
  4768. if (chunk) {
  4769. this.write(chunk, encoding, writeComplete);
  4770. } else {
  4771. writeComplete();
  4772. }
  4773. },
  4774. // readable
  4775. // event readable - some data is now available
  4776. // event data - switch to flowing mode - feeds chunks to handler
  4777. // event end - no more data
  4778. // event close - optional, indicates upstream close
  4779. // event error - duh
  4780. read(size) {
  4781. let buffers;
  4782. // read min(buffer, size || infinity)
  4783. if (size) {
  4784. buffers = [];
  4785. while (size && this.buffers.length && !this.buffers[0].eod) {
  4786. const first = this.buffers[0];
  4787. const buffer = first.read(size);
  4788. size -= buffer.length;
  4789. buffers.push(buffer);
  4790. if (first.eod && first.full) {
  4791. this.buffers.shift();
  4792. }
  4793. }
  4794. return Buffer.concat(buffers);
  4795. }
  4796. buffers = this.buffers.map(buf => buf.toBuffer()).filter(Boolean);
  4797. this.buffers = [];
  4798. return Buffer.concat(buffers);
  4799. },
  4800. setEncoding(encoding) {
  4801. // causes stream.read or stream.on('data) to return strings of encoding instead of Buffer objects
  4802. this.encoding = encoding;
  4803. },
  4804. pause() {
  4805. this.paused = true;
  4806. },
  4807. resume() {
  4808. this.paused = false;
  4809. },
  4810. isPaused() {
  4811. return !!this.paused;
  4812. },
  4813. pipe(destination) {
  4814. // add destination to pipe list & write current buffer
  4815. this.pipes.push(destination);
  4816. if (!this.paused && this.buffers.length) {
  4817. this.end();
  4818. }
  4819. },
  4820. unpipe(destination) {
  4821. // remove destination from pipe list
  4822. this.pipes = this.pipes.filter(pipe => pipe !== destination);
  4823. },
  4824. unshift( /* chunk */
  4825. ) {
  4826. // some numpty has read some data that's not for them and they want to put it back!
  4827. // Might implement this some day
  4828. throw new Error('Not Implemented');
  4829. },
  4830. wrap( /* stream */
  4831. ) {
  4832. // not implemented
  4833. throw new Error('Not Implemented');
  4834. }
  4835. });
  4836. module.exports = StreamBuf;
  4837. }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
  4838. },{"./string-buf":25,"./utils":27,"_process":306,"buffer":220,"readable-stream":330}],25:[function(require,module,exports){
  4839. (function (Buffer){(function (){
  4840. "use strict";
  4841. // StringBuf - a way to keep string memory operations to a minimum
  4842. // while building the strings for the xml files
  4843. class StringBuf {
  4844. constructor(options) {
  4845. this._buf = Buffer.alloc(options && options.size || 16384);
  4846. this._encoding = options && options.encoding || 'utf8';
  4847. // where in the buffer we are at
  4848. this._inPos = 0;
  4849. // for use by toBuffer()
  4850. this._buffer = undefined;
  4851. }
  4852. get length() {
  4853. return this._inPos;
  4854. }
  4855. get capacity() {
  4856. return this._buf.length;
  4857. }
  4858. get buffer() {
  4859. return this._buf;
  4860. }
  4861. toBuffer() {
  4862. // return the current data as a single enclosing buffer
  4863. if (!this._buffer) {
  4864. this._buffer = Buffer.alloc(this.length);
  4865. this._buf.copy(this._buffer, 0, 0, this.length);
  4866. }
  4867. return this._buffer;
  4868. }
  4869. reset(position) {
  4870. position = position || 0;
  4871. this._buffer = undefined;
  4872. this._inPos = position;
  4873. }
  4874. _grow(min) {
  4875. let size = this._buf.length * 2;
  4876. while (size < min) {
  4877. size *= 2;
  4878. }
  4879. const buf = Buffer.alloc(size);
  4880. this._buf.copy(buf, 0);
  4881. this._buf = buf;
  4882. }
  4883. addText(text) {
  4884. this._buffer = undefined;
  4885. let inPos = this._inPos + this._buf.write(text, this._inPos, this._encoding);
  4886. // if we've hit (or nearing capacity), grow the buf
  4887. while (inPos >= this._buf.length - 4) {
  4888. this._grow(this._inPos + text.length);
  4889. // keep trying to write until we've completely written the text
  4890. inPos = this._inPos + this._buf.write(text, this._inPos, this._encoding);
  4891. }
  4892. this._inPos = inPos;
  4893. }
  4894. addStringBuf(inBuf) {
  4895. if (inBuf.length) {
  4896. this._buffer = undefined;
  4897. if (this.length + inBuf.length > this.capacity) {
  4898. this._grow(this.length + inBuf.length);
  4899. }
  4900. // eslint-disable-next-line no-underscore-dangle
  4901. inBuf._buf.copy(this._buf, this._inPos, 0, inBuf.length);
  4902. this._inPos += inBuf.length;
  4903. }
  4904. }
  4905. }
  4906. module.exports = StringBuf;
  4907. }).call(this)}).call(this,require("buffer").Buffer)
  4908. },{"buffer":220}],26:[function(require,module,exports){
  4909. "use strict";
  4910. const {
  4911. toString
  4912. } = Object.prototype;
  4913. const escapeHtmlRegex = /["&<>]/;
  4914. const _ = {
  4915. each: function each(obj, cb) {
  4916. if (obj) {
  4917. if (Array.isArray(obj)) {
  4918. obj.forEach(cb);
  4919. } else {
  4920. Object.keys(obj).forEach(key => {
  4921. cb(obj[key], key);
  4922. });
  4923. }
  4924. }
  4925. },
  4926. some: function some(obj, cb) {
  4927. if (obj) {
  4928. if (Array.isArray(obj)) {
  4929. return obj.some(cb);
  4930. }
  4931. return Object.keys(obj).some(key => cb(obj[key], key));
  4932. }
  4933. return false;
  4934. },
  4935. every: function every(obj, cb) {
  4936. if (obj) {
  4937. if (Array.isArray(obj)) {
  4938. return obj.every(cb);
  4939. }
  4940. return Object.keys(obj).every(key => cb(obj[key], key));
  4941. }
  4942. return true;
  4943. },
  4944. map: function map(obj, cb) {
  4945. if (obj) {
  4946. if (Array.isArray(obj)) {
  4947. return obj.map(cb);
  4948. }
  4949. return Object.keys(obj).map(key => cb(obj[key], key));
  4950. }
  4951. return [];
  4952. },
  4953. keyBy(a, p) {
  4954. return a.reduce((o, v) => {
  4955. o[v[p]] = v;
  4956. return o;
  4957. }, {});
  4958. },
  4959. isEqual: function isEqual(a, b) {
  4960. const aType = typeof a;
  4961. const bType = typeof b;
  4962. const aArray = Array.isArray(a);
  4963. const bArray = Array.isArray(b);
  4964. let keys;
  4965. if (aType !== bType) {
  4966. return false;
  4967. }
  4968. switch (typeof a) {
  4969. case 'object':
  4970. if (aArray || bArray) {
  4971. if (aArray && bArray) {
  4972. return a.length === b.length && a.every((aValue, index) => {
  4973. const bValue = b[index];
  4974. return _.isEqual(aValue, bValue);
  4975. });
  4976. }
  4977. return false;
  4978. }
  4979. if (a === null || b === null) {
  4980. return a === b;
  4981. }
  4982. // Compare object keys and values
  4983. keys = Object.keys(a);
  4984. if (Object.keys(b).length !== keys.length) {
  4985. return false;
  4986. }
  4987. for (const key of keys) {
  4988. if (!b.hasOwnProperty(key)) {
  4989. return false;
  4990. }
  4991. }
  4992. return _.every(a, (aValue, key) => {
  4993. const bValue = b[key];
  4994. return _.isEqual(aValue, bValue);
  4995. });
  4996. default:
  4997. return a === b;
  4998. }
  4999. },
  5000. escapeHtml(html) {
  5001. const regexResult = escapeHtmlRegex.exec(html);
  5002. if (!regexResult) return html;
  5003. let result = '';
  5004. let escape = '';
  5005. let lastIndex = 0;
  5006. let i = regexResult.index;
  5007. for (; i < html.length; i++) {
  5008. switch (html.charAt(i)) {
  5009. case '"':
  5010. escape = '&quot;';
  5011. break;
  5012. case '&':
  5013. escape = '&amp;';
  5014. break;
  5015. case '\'':
  5016. escape = '&apos;';
  5017. break;
  5018. case '<':
  5019. escape = '&lt;';
  5020. break;
  5021. case '>':
  5022. escape = '&gt;';
  5023. break;
  5024. default:
  5025. continue;
  5026. }
  5027. if (lastIndex !== i) result += html.substring(lastIndex, i);
  5028. lastIndex = i + 1;
  5029. result += escape;
  5030. }
  5031. if (lastIndex !== i) return result + html.substring(lastIndex, i);
  5032. return result;
  5033. },
  5034. strcmp(a, b) {
  5035. if (a < b) return -1;
  5036. if (a > b) return 1;
  5037. return 0;
  5038. },
  5039. isUndefined(val) {
  5040. return toString.call(val) === '[object Undefined]';
  5041. },
  5042. isObject(val) {
  5043. return toString.call(val) === '[object Object]';
  5044. },
  5045. deepMerge() {
  5046. const target = arguments[0] || {};
  5047. const {
  5048. length
  5049. } = arguments;
  5050. // eslint-disable-next-line one-var
  5051. let src, clone, copyIsArray;
  5052. function assignValue(val, key) {
  5053. src = target[key];
  5054. copyIsArray = Array.isArray(val);
  5055. if (_.isObject(val) || copyIsArray) {
  5056. if (copyIsArray) {
  5057. copyIsArray = false;
  5058. clone = src && Array.isArray(src) ? src : [];
  5059. } else {
  5060. clone = src && _.isObject(src) ? src : {};
  5061. }
  5062. target[key] = _.deepMerge(clone, val);
  5063. } else if (!_.isUndefined(val)) {
  5064. target[key] = val;
  5065. }
  5066. }
  5067. for (let i = 0; i < length; i++) {
  5068. _.each(arguments[i], assignValue);
  5069. }
  5070. return target;
  5071. }
  5072. };
  5073. module.exports = _;
  5074. },{}],27:[function(require,module,exports){
  5075. (function (global,setImmediate){(function (){
  5076. "use strict";
  5077. const fs = require('fs');
  5078. // useful stuff
  5079. const inherits = function (cls, superCtor, statics, prototype) {
  5080. // eslint-disable-next-line no-underscore-dangle
  5081. cls.super_ = superCtor;
  5082. if (!prototype) {
  5083. prototype = statics;
  5084. statics = null;
  5085. }
  5086. if (statics) {
  5087. Object.keys(statics).forEach(i => {
  5088. Object.defineProperty(cls, i, Object.getOwnPropertyDescriptor(statics, i));
  5089. });
  5090. }
  5091. const properties = {
  5092. constructor: {
  5093. value: cls,
  5094. enumerable: false,
  5095. writable: false,
  5096. configurable: true
  5097. }
  5098. };
  5099. if (prototype) {
  5100. Object.keys(prototype).forEach(i => {
  5101. properties[i] = Object.getOwnPropertyDescriptor(prototype, i);
  5102. });
  5103. }
  5104. cls.prototype = Object.create(superCtor.prototype, properties);
  5105. };
  5106. // eslint-disable-next-line no-control-regex
  5107. const xmlDecodeRegex = /[<>&'"\x7F\x00-\x08\x0B-\x0C\x0E-\x1F]/;
  5108. const utils = {
  5109. nop() {},
  5110. promiseImmediate(value) {
  5111. return new Promise(resolve => {
  5112. if (global.setImmediate) {
  5113. setImmediate(() => {
  5114. resolve(value);
  5115. });
  5116. } else {
  5117. // poorman's setImmediate - must wait at least 1ms
  5118. setTimeout(() => {
  5119. resolve(value);
  5120. }, 1);
  5121. }
  5122. });
  5123. },
  5124. inherits,
  5125. dateToExcel(d, date1904) {
  5126. return 25569 + d.getTime() / (24 * 3600 * 1000) - (date1904 ? 1462 : 0);
  5127. },
  5128. excelToDate(v, date1904) {
  5129. const millisecondSinceEpoch = Math.round((v - 25569 + (date1904 ? 1462 : 0)) * 24 * 3600 * 1000);
  5130. return new Date(millisecondSinceEpoch);
  5131. },
  5132. parsePath(filepath) {
  5133. const last = filepath.lastIndexOf('/');
  5134. return {
  5135. path: filepath.substring(0, last),
  5136. name: filepath.substring(last + 1)
  5137. };
  5138. },
  5139. getRelsPath(filepath) {
  5140. const path = utils.parsePath(filepath);
  5141. return `${path.path}/_rels/${path.name}.rels`;
  5142. },
  5143. xmlEncode(text) {
  5144. const regexResult = xmlDecodeRegex.exec(text);
  5145. if (!regexResult) return text;
  5146. let result = '';
  5147. let escape = '';
  5148. let lastIndex = 0;
  5149. let i = regexResult.index;
  5150. for (; i < text.length; i++) {
  5151. const charCode = text.charCodeAt(i);
  5152. switch (charCode) {
  5153. case 34:
  5154. // "
  5155. escape = '&quot;';
  5156. break;
  5157. case 38:
  5158. // &
  5159. escape = '&amp;';
  5160. break;
  5161. case 39:
  5162. // '
  5163. escape = '&apos;';
  5164. break;
  5165. case 60:
  5166. // <
  5167. escape = '&lt;';
  5168. break;
  5169. case 62:
  5170. // >
  5171. escape = '&gt;';
  5172. break;
  5173. case 127:
  5174. escape = '';
  5175. break;
  5176. default:
  5177. {
  5178. if (charCode <= 31 && (charCode <= 8 || charCode >= 11 && charCode !== 13)) {
  5179. escape = '';
  5180. break;
  5181. }
  5182. continue;
  5183. }
  5184. }
  5185. if (lastIndex !== i) result += text.substring(lastIndex, i);
  5186. lastIndex = i + 1;
  5187. if (escape) result += escape;
  5188. }
  5189. if (lastIndex !== i) return result + text.substring(lastIndex, i);
  5190. return result;
  5191. },
  5192. xmlDecode(text) {
  5193. return text.replace(/&([a-z]*);/g, c => {
  5194. switch (c) {
  5195. case '&lt;':
  5196. return '<';
  5197. case '&gt;':
  5198. return '>';
  5199. case '&amp;':
  5200. return '&';
  5201. case '&apos;':
  5202. return '\'';
  5203. case '&quot;':
  5204. return '"';
  5205. default:
  5206. return c;
  5207. }
  5208. });
  5209. },
  5210. validInt(value) {
  5211. const i = parseInt(value, 10);
  5212. return !Number.isNaN(i) ? i : 0;
  5213. },
  5214. isDateFmt(fmt) {
  5215. if (!fmt) {
  5216. return false;
  5217. }
  5218. // must remove all chars inside quotes and []
  5219. fmt = fmt.replace(/\[[^\]]*]/g, '');
  5220. fmt = fmt.replace(/"[^"]*"/g, '');
  5221. // then check for date formatting chars
  5222. const result = fmt.match(/[ymdhMsb]+/) !== null;
  5223. return result;
  5224. },
  5225. fs: {
  5226. exists(path) {
  5227. return new Promise(resolve => {
  5228. fs.access(path, fs.constants.F_OK, err => {
  5229. resolve(!err);
  5230. });
  5231. });
  5232. }
  5233. },
  5234. toIsoDateString(dt) {
  5235. return dt.toIsoString().subsstr(0, 10);
  5236. },
  5237. parseBoolean(value) {
  5238. return value === true || value === 'true' || value === 1 || value === '1';
  5239. }
  5240. };
  5241. module.exports = utils;
  5242. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  5243. },{"fs":216,"timers":361}],28:[function(require,module,exports){
  5244. "use strict";
  5245. const _ = require('./under-dash');
  5246. const utils = require('./utils');
  5247. // constants
  5248. const OPEN_ANGLE = '<';
  5249. const CLOSE_ANGLE = '>';
  5250. const OPEN_ANGLE_SLASH = '</';
  5251. const CLOSE_SLASH_ANGLE = '/>';
  5252. function pushAttribute(xml, name, value) {
  5253. xml.push(` ${name}="${utils.xmlEncode(value.toString())}"`);
  5254. }
  5255. function pushAttributes(xml, attributes) {
  5256. if (attributes) {
  5257. const tmp = [];
  5258. _.each(attributes, (value, name) => {
  5259. if (value !== undefined) {
  5260. pushAttribute(tmp, name, value);
  5261. }
  5262. });
  5263. xml.push(tmp.join(""));
  5264. }
  5265. }
  5266. class XmlStream {
  5267. constructor() {
  5268. this._xml = [];
  5269. this._stack = [];
  5270. this._rollbacks = [];
  5271. }
  5272. get tos() {
  5273. return this._stack.length ? this._stack[this._stack.length - 1] : undefined;
  5274. }
  5275. get cursor() {
  5276. // handy way to track whether anything has been added
  5277. return this._xml.length;
  5278. }
  5279. openXml(docAttributes) {
  5280. const xml = this._xml;
  5281. // <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  5282. xml.push('<?xml');
  5283. pushAttributes(xml, docAttributes);
  5284. xml.push('?>\n');
  5285. }
  5286. openNode(name, attributes) {
  5287. const parent = this.tos;
  5288. const xml = this._xml;
  5289. if (parent && this.open) {
  5290. xml.push(CLOSE_ANGLE);
  5291. }
  5292. this._stack.push(name);
  5293. // start streaming node
  5294. xml.push(OPEN_ANGLE);
  5295. xml.push(name);
  5296. pushAttributes(xml, attributes);
  5297. this.leaf = true;
  5298. this.open = true;
  5299. }
  5300. addAttribute(name, value) {
  5301. if (!this.open) {
  5302. throw new Error('Cannot write attributes to node if it is not open');
  5303. }
  5304. if (value !== undefined) {
  5305. pushAttribute(this._xml, name, value);
  5306. }
  5307. }
  5308. addAttributes(attrs) {
  5309. if (!this.open) {
  5310. throw new Error('Cannot write attributes to node if it is not open');
  5311. }
  5312. pushAttributes(this._xml, attrs);
  5313. }
  5314. writeText(text) {
  5315. const xml = this._xml;
  5316. if (this.open) {
  5317. xml.push(CLOSE_ANGLE);
  5318. this.open = false;
  5319. }
  5320. this.leaf = false;
  5321. xml.push(utils.xmlEncode(text.toString()));
  5322. }
  5323. writeXml(xml) {
  5324. if (this.open) {
  5325. this._xml.push(CLOSE_ANGLE);
  5326. this.open = false;
  5327. }
  5328. this.leaf = false;
  5329. this._xml.push(xml);
  5330. }
  5331. closeNode() {
  5332. const node = this._stack.pop();
  5333. const xml = this._xml;
  5334. if (this.leaf) {
  5335. xml.push(CLOSE_SLASH_ANGLE);
  5336. } else {
  5337. xml.push(OPEN_ANGLE_SLASH);
  5338. xml.push(node);
  5339. xml.push(CLOSE_ANGLE);
  5340. }
  5341. this.open = false;
  5342. this.leaf = false;
  5343. }
  5344. leafNode(name, attributes, text) {
  5345. this.openNode(name, attributes);
  5346. if (text !== undefined) {
  5347. // zeros need to be written
  5348. this.writeText(text);
  5349. }
  5350. this.closeNode();
  5351. }
  5352. closeAll() {
  5353. while (this._stack.length) {
  5354. this.closeNode();
  5355. }
  5356. }
  5357. addRollback() {
  5358. this._rollbacks.push({
  5359. xml: this._xml.length,
  5360. stack: this._stack.length,
  5361. leaf: this.leaf,
  5362. open: this.open
  5363. });
  5364. return this.cursor;
  5365. }
  5366. commit() {
  5367. this._rollbacks.pop();
  5368. }
  5369. rollback() {
  5370. const r = this._rollbacks.pop();
  5371. if (this._xml.length > r.xml) {
  5372. this._xml.splice(r.xml, this._xml.length - r.xml);
  5373. }
  5374. if (this._stack.length > r.stack) {
  5375. this._stack.splice(r.stack, this._stack.length - r.stack);
  5376. }
  5377. this.leaf = r.leaf;
  5378. this.open = r.open;
  5379. }
  5380. get xml() {
  5381. this.closeAll();
  5382. return this._xml.join('');
  5383. }
  5384. }
  5385. XmlStream.StdDocAttributes = {
  5386. version: '1.0',
  5387. encoding: 'UTF-8',
  5388. standalone: 'yes'
  5389. };
  5390. module.exports = XmlStream;
  5391. },{"./under-dash":26,"./utils":27}],29:[function(require,module,exports){
  5392. (function (process){(function (){
  5393. "use strict";
  5394. const events = require('events');
  5395. const JSZip = require('jszip');
  5396. const StreamBuf = require('./stream-buf');
  5397. const {
  5398. stringToBuffer
  5399. } = require('./browser-buffer-encode');
  5400. // =============================================================================
  5401. // The ZipWriter class
  5402. // Packs streamed data into an output zip stream
  5403. class ZipWriter extends events.EventEmitter {
  5404. constructor(options) {
  5405. super();
  5406. this.options = Object.assign({
  5407. type: 'nodebuffer',
  5408. compression: 'DEFLATE'
  5409. }, options);
  5410. this.zip = new JSZip();
  5411. this.stream = new StreamBuf();
  5412. }
  5413. append(data, options) {
  5414. if (options.hasOwnProperty('base64') && options.base64) {
  5415. this.zip.file(options.name, data, {
  5416. base64: true
  5417. });
  5418. } else {
  5419. // https://www.npmjs.com/package/process
  5420. if (process.browser && typeof data === 'string') {
  5421. // use TextEncoder in browser
  5422. data = stringToBuffer(data);
  5423. }
  5424. this.zip.file(options.name, data);
  5425. }
  5426. }
  5427. async finalize() {
  5428. const content = await this.zip.generateAsync(this.options);
  5429. this.stream.end(content);
  5430. this.emit('finish');
  5431. }
  5432. // ==========================================================================
  5433. // Stream.Readable interface
  5434. read(size) {
  5435. return this.stream.read(size);
  5436. }
  5437. setEncoding(encoding) {
  5438. return this.stream.setEncoding(encoding);
  5439. }
  5440. pause() {
  5441. return this.stream.pause();
  5442. }
  5443. resume() {
  5444. return this.stream.resume();
  5445. }
  5446. isPaused() {
  5447. return this.stream.isPaused();
  5448. }
  5449. pipe(destination, options) {
  5450. return this.stream.pipe(destination, options);
  5451. }
  5452. unpipe(destination) {
  5453. return this.stream.unpipe(destination);
  5454. }
  5455. unshift(chunk) {
  5456. return this.stream.unshift(chunk);
  5457. }
  5458. wrap(stream) {
  5459. return this.stream.wrap(stream);
  5460. }
  5461. }
  5462. // =============================================================================
  5463. module.exports = {
  5464. ZipWriter
  5465. };
  5466. }).call(this)}).call(this,require('_process'))
  5467. },{"./browser-buffer-encode":17,"./stream-buf":24,"_process":306,"events":261,"jszip":280}],30:[function(require,module,exports){
  5468. "use strict";
  5469. module.exports = {
  5470. 0: {
  5471. f: 'General'
  5472. },
  5473. 1: {
  5474. f: '0'
  5475. },
  5476. 2: {
  5477. f: '0.00'
  5478. },
  5479. 3: {
  5480. f: '#,##0'
  5481. },
  5482. 4: {
  5483. f: '#,##0.00'
  5484. },
  5485. 9: {
  5486. f: '0%'
  5487. },
  5488. 10: {
  5489. f: '0.00%'
  5490. },
  5491. 11: {
  5492. f: '0.00E+00'
  5493. },
  5494. 12: {
  5495. f: '# ?/?'
  5496. },
  5497. 13: {
  5498. f: '# ??/??'
  5499. },
  5500. 14: {
  5501. f: 'mm-dd-yy'
  5502. },
  5503. 15: {
  5504. f: 'd-mmm-yy'
  5505. },
  5506. 16: {
  5507. f: 'd-mmm'
  5508. },
  5509. 17: {
  5510. f: 'mmm-yy'
  5511. },
  5512. 18: {
  5513. f: 'h:mm AM/PM'
  5514. },
  5515. 19: {
  5516. f: 'h:mm:ss AM/PM'
  5517. },
  5518. 20: {
  5519. f: 'h:mm'
  5520. },
  5521. 21: {
  5522. f: 'h:mm:ss'
  5523. },
  5524. 22: {
  5525. f: 'm/d/yy "h":mm'
  5526. },
  5527. 27: {
  5528. 'zh-tw': '[$-404]e/m/d',
  5529. 'zh-cn': 'yyyy"年"m"月"',
  5530. 'ja-jp': '[$-411]ge.m.d',
  5531. 'ko-kr': 'yyyy"年" mm"月" dd"日"'
  5532. },
  5533. 28: {
  5534. 'zh-tw': '[$-404]e"年"m"月"d"日"',
  5535. 'zh-cn': 'm"月"d"日"',
  5536. 'ja-jp': '[$-411]ggge"年"m"月"d"日"',
  5537. 'ko-kr': 'mm-dd'
  5538. },
  5539. 29: {
  5540. 'zh-tw': '[$-404]e"年"m"月"d"日"',
  5541. 'zh-cn': 'm"月"d"日"',
  5542. 'ja-jp': '[$-411]ggge"年"m"月"d"日"',
  5543. 'ko-kr': 'mm-dd'
  5544. },
  5545. 30: {
  5546. 'zh-tw': 'm/d/yy ',
  5547. 'zh-cn': 'm-d-yy',
  5548. 'ja-jp': 'm/d/yy',
  5549. 'ko-kr': 'mm-dd-yy'
  5550. },
  5551. 31: {
  5552. 'zh-tw': 'yyyy"年"m"月"d"日"',
  5553. 'zh-cn': 'yyyy"年"m"月"d"日"',
  5554. 'ja-jp': 'yyyy"年"m"月"d"日"',
  5555. 'ko-kr': 'yyyy"년" mm"월" dd"일"'
  5556. },
  5557. 32: {
  5558. 'zh-tw': 'hh"時"mm"分"',
  5559. 'zh-cn': 'h"时"mm"分"',
  5560. 'ja-jp': 'h"時"mm"分"',
  5561. 'ko-kr': 'h"시" mm"분"'
  5562. },
  5563. 33: {
  5564. 'zh-tw': 'hh"時"mm"分"ss"秒"',
  5565. 'zh-cn': 'h"时"mm"分"ss"秒"',
  5566. 'ja-jp': 'h"時"mm"分"ss"秒"',
  5567. 'ko-kr': 'h"시" mm"분" ss"초"'
  5568. },
  5569. 34: {
  5570. 'zh-tw': '上午/下午 hh"時"mm"分"',
  5571. 'zh-cn': '上午/下午 h"时"mm"分"',
  5572. 'ja-jp': 'yyyy"年"m"月"',
  5573. 'ko-kr': 'yyyy-mm-dd'
  5574. },
  5575. 35: {
  5576. 'zh-tw': '上午/下午 hh"時"mm"分"ss"秒"',
  5577. 'zh-cn': '上午/下午 h"时"mm"分"ss"秒"',
  5578. 'ja-jp': 'm"月"d"日"',
  5579. 'ko-kr': 'yyyy-mm-dd'
  5580. },
  5581. 36: {
  5582. 'zh-tw': '[$-404]e/m/d',
  5583. 'zh-cn': 'yyyy"年"m"月"',
  5584. 'ja-jp': '[$-411]ge.m.d',
  5585. 'ko-kr': 'yyyy"年" mm"月" dd"日"'
  5586. },
  5587. 37: {
  5588. f: '#,##0 ;(#,##0)'
  5589. },
  5590. 38: {
  5591. f: '#,##0 ;[Red](#,##0)'
  5592. },
  5593. 39: {
  5594. f: '#,##0.00 ;(#,##0.00)'
  5595. },
  5596. 40: {
  5597. f: '#,##0.00 ;[Red](#,##0.00)'
  5598. },
  5599. 45: {
  5600. f: 'mm:ss'
  5601. },
  5602. 46: {
  5603. f: '[h]:mm:ss'
  5604. },
  5605. 47: {
  5606. f: 'mmss.0'
  5607. },
  5608. 48: {
  5609. f: '##0.0E+0'
  5610. },
  5611. 49: {
  5612. f: '@'
  5613. },
  5614. 50: {
  5615. 'zh-tw': '[$-404]e/m/d',
  5616. 'zh-cn': 'yyyy"年"m"月"',
  5617. 'ja-jp': '[$-411]ge.m.d',
  5618. 'ko-kr': 'yyyy"年" mm"月" dd"日"'
  5619. },
  5620. 51: {
  5621. 'zh-tw': '[$-404]e"年"m"月"d"日"',
  5622. 'zh-cn': 'm"月"d"日"',
  5623. 'ja-jp': '[$-411]ggge"年"m"月"d"日"',
  5624. 'ko-kr': 'mm-dd'
  5625. },
  5626. 52: {
  5627. 'zh-tw': '上午/下午 hh"時"mm"分"',
  5628. 'zh-cn': 'yyyy"年"m"月"',
  5629. 'ja-jp': 'yyyy"年"m"月"',
  5630. 'ko-kr': 'yyyy-mm-dd'
  5631. },
  5632. 53: {
  5633. 'zh-tw': '上午/下午 hh"時"mm"分"ss"秒"',
  5634. 'zh-cn': 'm"月"d"日"',
  5635. 'ja-jp': 'm"月"d"日"',
  5636. 'ko-kr': 'yyyy-mm-dd'
  5637. },
  5638. 54: {
  5639. 'zh-tw': '[$-404]e"年"m"月"d"日"',
  5640. 'zh-cn': 'm"月"d"日"',
  5641. 'ja-jp': '[$-411]ggge"年"m"月"d"日"',
  5642. 'ko-kr': 'mm-dd'
  5643. },
  5644. 55: {
  5645. 'zh-tw': '上午/下午 hh"時"mm"分"',
  5646. 'zh-cn': '上午/下午 h"时"mm"分"',
  5647. 'ja-jp': 'yyyy"年"m"月"',
  5648. 'ko-kr': 'yyyy-mm-dd'
  5649. },
  5650. 56: {
  5651. 'zh-tw': '上午/下午 hh"時"mm"分"ss"秒"',
  5652. 'zh-cn': '上午/下午 h"时"mm"分"ss"秒"',
  5653. 'ja-jp': 'm"月"d"日"',
  5654. 'ko-kr': 'yyyy-mm-dd'
  5655. },
  5656. 57: {
  5657. 'zh-tw': '[$-404]e/m/d',
  5658. 'zh-cn': 'yyyy"年"m"月"',
  5659. 'ja-jp': '[$-411]ge.m.d',
  5660. 'ko-kr': 'yyyy"年" mm"月" dd"日"'
  5661. },
  5662. 58: {
  5663. 'zh-tw': '[$-404]e"年"m"月"d"日"',
  5664. 'zh-cn': 'm"月"d"日"',
  5665. 'ja-jp': '[$-411]ggge"年"m"月"d"日"',
  5666. 'ko-kr': 'mm-dd'
  5667. },
  5668. 59: {
  5669. 'th-th': 't0'
  5670. },
  5671. 60: {
  5672. 'th-th': 't0.00'
  5673. },
  5674. 61: {
  5675. 'th-th': 't#,##0'
  5676. },
  5677. 62: {
  5678. 'th-th': 't#,##0.00'
  5679. },
  5680. 67: {
  5681. 'th-th': 't0%'
  5682. },
  5683. 68: {
  5684. 'th-th': 't0.00%'
  5685. },
  5686. 69: {
  5687. 'th-th': 't# ?/?'
  5688. },
  5689. 70: {
  5690. 'th-th': 't# ??/??'
  5691. },
  5692. 81: {
  5693. 'th-th': 'd/m/bb'
  5694. }
  5695. };
  5696. },{}],31:[function(require,module,exports){
  5697. 'use strict';
  5698. module.exports = {
  5699. OfficeDocument: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
  5700. Worksheet: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',
  5701. CalcChain: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/calcChain',
  5702. SharedStrings: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',
  5703. Styles: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
  5704. Theme: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
  5705. Hyperlink: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
  5706. Image: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
  5707. CoreProperties: 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
  5708. ExtenderProperties: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
  5709. Comments: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments',
  5710. VmlDrawing: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
  5711. Table: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/table'
  5712. };
  5713. },{}],32:[function(require,module,exports){
  5714. "use strict";
  5715. const parseSax = require('../../utils/parse-sax');
  5716. const XmlStream = require('../../utils/xml-stream');
  5717. /* 'virtual' methods used as a form of documentation */
  5718. /* eslint-disable class-methods-use-this */
  5719. // Base class for Xforms
  5720. class BaseXform {
  5721. // constructor(/* model, name */) {}
  5722. // ============================================================
  5723. // Virtual Interface
  5724. prepare( /* model, options */
  5725. ) {
  5726. // optional preparation (mutation) of model so it is ready for write
  5727. }
  5728. render( /* xmlStream, model */
  5729. ) {
  5730. // convert model to xml
  5731. }
  5732. parseOpen(node) {
  5733. // XML node opened
  5734. }
  5735. parseText(text) {
  5736. // chunk of text encountered for current node
  5737. }
  5738. parseClose(name) {
  5739. // XML node closed
  5740. }
  5741. reconcile(model, options) {
  5742. // optional post-parse step (opposite to prepare)
  5743. }
  5744. // ============================================================
  5745. reset() {
  5746. // to make sure parses don't bleed to next iteration
  5747. this.model = null;
  5748. // if we have a map - reset them too
  5749. if (this.map) {
  5750. Object.values(this.map).forEach(xform => {
  5751. if (xform instanceof BaseXform) {
  5752. xform.reset();
  5753. } else if (xform.xform) {
  5754. xform.xform.reset();
  5755. }
  5756. });
  5757. }
  5758. }
  5759. mergeModel(obj) {
  5760. // set obj's props to this.model
  5761. this.model = Object.assign(this.model || {}, obj);
  5762. }
  5763. async parse(saxParser) {
  5764. for await (const events of saxParser) {
  5765. for (const {
  5766. eventType,
  5767. value
  5768. } of events) {
  5769. if (eventType === 'opentag') {
  5770. this.parseOpen(value);
  5771. } else if (eventType === 'text') {
  5772. this.parseText(value);
  5773. } else if (eventType === 'closetag') {
  5774. if (!this.parseClose(value.name)) {
  5775. return this.model;
  5776. }
  5777. }
  5778. }
  5779. }
  5780. return this.model;
  5781. }
  5782. async parseStream(stream) {
  5783. return this.parse(parseSax(stream));
  5784. }
  5785. get xml() {
  5786. // convenience function to get the xml of this.model
  5787. // useful for manager types that are built during the prepare phase
  5788. return this.toXml(this.model);
  5789. }
  5790. toXml(model) {
  5791. const xmlStream = new XmlStream();
  5792. this.render(xmlStream, model);
  5793. return xmlStream.xml;
  5794. }
  5795. // ============================================================
  5796. // Useful Utilities
  5797. static toAttribute(value, dflt) {
  5798. let always = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  5799. if (value === undefined) {
  5800. if (always) {
  5801. return dflt;
  5802. }
  5803. } else if (always || value !== dflt) {
  5804. return value.toString();
  5805. }
  5806. return undefined;
  5807. }
  5808. static toStringAttribute(value, dflt) {
  5809. let always = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  5810. return BaseXform.toAttribute(value, dflt, always);
  5811. }
  5812. static toStringValue(attr, dflt) {
  5813. return attr === undefined ? dflt : attr;
  5814. }
  5815. static toBoolAttribute(value, dflt) {
  5816. let always = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  5817. if (value === undefined) {
  5818. if (always) {
  5819. return dflt;
  5820. }
  5821. } else if (always || value !== dflt) {
  5822. return value ? '1' : '0';
  5823. }
  5824. return undefined;
  5825. }
  5826. static toBoolValue(attr, dflt) {
  5827. return attr === undefined ? dflt : attr === '1';
  5828. }
  5829. static toIntAttribute(value, dflt) {
  5830. let always = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  5831. return BaseXform.toAttribute(value, dflt, always);
  5832. }
  5833. static toIntValue(attr, dflt) {
  5834. return attr === undefined ? dflt : parseInt(attr, 10);
  5835. }
  5836. static toFloatAttribute(value, dflt) {
  5837. let always = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  5838. return BaseXform.toAttribute(value, dflt, always);
  5839. }
  5840. static toFloatValue(attr, dflt) {
  5841. return attr === undefined ? dflt : parseFloat(attr);
  5842. }
  5843. }
  5844. module.exports = BaseXform;
  5845. },{"../../utils/parse-sax":22,"../../utils/xml-stream":28}],33:[function(require,module,exports){
  5846. "use strict";
  5847. const BaseXform = require('../base-xform');
  5848. const colCache = require('../../../utils/col-cache');
  5849. class DefinedNamesXform extends BaseXform {
  5850. render(xmlStream, model) {
  5851. // <definedNames>
  5852. // <definedName name="name">name.ranges.join(',')</definedName>
  5853. // <definedName name="_xlnm.Print_Area" localSheetId="0">name.ranges.join(',')</definedName>
  5854. // </definedNames>
  5855. xmlStream.openNode('definedName', {
  5856. name: model.name,
  5857. localSheetId: model.localSheetId
  5858. });
  5859. xmlStream.writeText(model.ranges.join(','));
  5860. xmlStream.closeNode();
  5861. }
  5862. parseOpen(node) {
  5863. switch (node.name) {
  5864. case 'definedName':
  5865. this._parsedName = node.attributes.name;
  5866. this._parsedLocalSheetId = node.attributes.localSheetId;
  5867. this._parsedText = [];
  5868. return true;
  5869. default:
  5870. return false;
  5871. }
  5872. }
  5873. parseText(text) {
  5874. this._parsedText.push(text);
  5875. }
  5876. parseClose() {
  5877. this.model = {
  5878. name: this._parsedName,
  5879. ranges: extractRanges(this._parsedText.join(''))
  5880. };
  5881. if (this._parsedLocalSheetId !== undefined) {
  5882. this.model.localSheetId = parseInt(this._parsedLocalSheetId, 10);
  5883. }
  5884. return false;
  5885. }
  5886. }
  5887. function isValidRange(range) {
  5888. try {
  5889. colCache.decodeEx(range);
  5890. return true;
  5891. } catch (err) {
  5892. return false;
  5893. }
  5894. }
  5895. function extractRanges(parsedText) {
  5896. const ranges = [];
  5897. let quotesOpened = false;
  5898. let last = '';
  5899. parsedText.split(',').forEach(item => {
  5900. if (!item) {
  5901. return;
  5902. }
  5903. const quotes = (item.match(/'/g) || []).length;
  5904. if (!quotes) {
  5905. if (quotesOpened) {
  5906. last += `${item},`;
  5907. } else if (isValidRange(item)) {
  5908. ranges.push(item);
  5909. }
  5910. return;
  5911. }
  5912. const quotesEven = quotes % 2 === 0;
  5913. if (!quotesOpened && quotesEven && isValidRange(item)) {
  5914. ranges.push(item);
  5915. } else if (quotesOpened && !quotesEven) {
  5916. quotesOpened = false;
  5917. if (isValidRange(last + item)) {
  5918. ranges.push(last + item);
  5919. }
  5920. last = '';
  5921. } else {
  5922. quotesOpened = true;
  5923. last += `${item},`;
  5924. }
  5925. });
  5926. return ranges;
  5927. }
  5928. module.exports = DefinedNamesXform;
  5929. },{"../../../utils/col-cache":19,"../base-xform":32}],34:[function(require,module,exports){
  5930. "use strict";
  5931. const utils = require('../../../utils/utils');
  5932. const BaseXform = require('../base-xform');
  5933. class WorksheetXform extends BaseXform {
  5934. render(xmlStream, model) {
  5935. xmlStream.leafNode('sheet', {
  5936. sheetId: model.id,
  5937. name: model.name,
  5938. state: model.state,
  5939. 'r:id': model.rId
  5940. });
  5941. }
  5942. parseOpen(node) {
  5943. if (node.name === 'sheet') {
  5944. this.model = {
  5945. name: utils.xmlDecode(node.attributes.name),
  5946. id: parseInt(node.attributes.sheetId, 10),
  5947. state: node.attributes.state,
  5948. rId: node.attributes['r:id']
  5949. };
  5950. return true;
  5951. }
  5952. return false;
  5953. }
  5954. parseText() {}
  5955. parseClose() {
  5956. return false;
  5957. }
  5958. }
  5959. module.exports = WorksheetXform;
  5960. },{"../../../utils/utils":27,"../base-xform":32}],35:[function(require,module,exports){
  5961. "use strict";
  5962. const BaseXform = require('../base-xform');
  5963. class WorkbookCalcPropertiesXform extends BaseXform {
  5964. render(xmlStream, model) {
  5965. xmlStream.leafNode('calcPr', {
  5966. calcId: 171027,
  5967. fullCalcOnLoad: model.fullCalcOnLoad ? 1 : undefined
  5968. });
  5969. }
  5970. parseOpen(node) {
  5971. if (node.name === 'calcPr') {
  5972. this.model = {};
  5973. return true;
  5974. }
  5975. return false;
  5976. }
  5977. parseText() {}
  5978. parseClose() {
  5979. return false;
  5980. }
  5981. }
  5982. module.exports = WorkbookCalcPropertiesXform;
  5983. },{"../base-xform":32}],36:[function(require,module,exports){
  5984. "use strict";
  5985. const BaseXform = require('../base-xform');
  5986. class WorksheetPropertiesXform extends BaseXform {
  5987. render(xmlStream, model) {
  5988. xmlStream.leafNode('workbookPr', {
  5989. date1904: model.date1904 ? 1 : undefined,
  5990. defaultThemeVersion: 164011,
  5991. filterPrivacy: 1
  5992. });
  5993. }
  5994. parseOpen(node) {
  5995. if (node.name === 'workbookPr') {
  5996. this.model = {
  5997. date1904: node.attributes.date1904 === '1'
  5998. };
  5999. return true;
  6000. }
  6001. return false;
  6002. }
  6003. parseText() {}
  6004. parseClose() {
  6005. return false;
  6006. }
  6007. }
  6008. module.exports = WorksheetPropertiesXform;
  6009. },{"../base-xform":32}],37:[function(require,module,exports){
  6010. "use strict";
  6011. const BaseXform = require('../base-xform');
  6012. class WorkbookViewXform extends BaseXform {
  6013. render(xmlStream, model) {
  6014. const attributes = {
  6015. xWindow: model.x || 0,
  6016. yWindow: model.y || 0,
  6017. windowWidth: model.width || 12000,
  6018. windowHeight: model.height || 24000,
  6019. firstSheet: model.firstSheet,
  6020. activeTab: model.activeTab
  6021. };
  6022. if (model.visibility && model.visibility !== 'visible') {
  6023. attributes.visibility = model.visibility;
  6024. }
  6025. xmlStream.leafNode('workbookView', attributes);
  6026. }
  6027. parseOpen(node) {
  6028. if (node.name === 'workbookView') {
  6029. const model = this.model = {};
  6030. const addS = function (name, value, dflt) {
  6031. const s = value !== undefined ? model[name] = value : dflt;
  6032. if (s !== undefined) {
  6033. model[name] = s;
  6034. }
  6035. };
  6036. const addN = function (name, value, dflt) {
  6037. const n = value !== undefined ? model[name] = parseInt(value, 10) : dflt;
  6038. if (n !== undefined) {
  6039. model[name] = n;
  6040. }
  6041. };
  6042. addN('x', node.attributes.xWindow, 0);
  6043. addN('y', node.attributes.yWindow, 0);
  6044. addN('width', node.attributes.windowWidth, 25000);
  6045. addN('height', node.attributes.windowHeight, 10000);
  6046. addS('visibility', node.attributes.visibility, 'visible');
  6047. addN('activeTab', node.attributes.activeTab, undefined);
  6048. addN('firstSheet', node.attributes.firstSheet, undefined);
  6049. return true;
  6050. }
  6051. return false;
  6052. }
  6053. parseText() {}
  6054. parseClose() {
  6055. return false;
  6056. }
  6057. }
  6058. module.exports = WorkbookViewXform;
  6059. },{"../base-xform":32}],38:[function(require,module,exports){
  6060. "use strict";
  6061. const _ = require('../../../utils/under-dash');
  6062. const colCache = require('../../../utils/col-cache');
  6063. const XmlStream = require('../../../utils/xml-stream');
  6064. const BaseXform = require('../base-xform');
  6065. const StaticXform = require('../static-xform');
  6066. const ListXform = require('../list-xform');
  6067. const DefinedNameXform = require('./defined-name-xform');
  6068. const SheetXform = require('./sheet-xform');
  6069. const WorkbookViewXform = require('./workbook-view-xform');
  6070. const WorkbookPropertiesXform = require('./workbook-properties-xform');
  6071. const WorkbookCalcPropertiesXform = require('./workbook-calc-properties-xform');
  6072. class WorkbookXform extends BaseXform {
  6073. constructor() {
  6074. super();
  6075. this.map = {
  6076. fileVersion: WorkbookXform.STATIC_XFORMS.fileVersion,
  6077. workbookPr: new WorkbookPropertiesXform(),
  6078. bookViews: new ListXform({
  6079. tag: 'bookViews',
  6080. count: false,
  6081. childXform: new WorkbookViewXform()
  6082. }),
  6083. sheets: new ListXform({
  6084. tag: 'sheets',
  6085. count: false,
  6086. childXform: new SheetXform()
  6087. }),
  6088. definedNames: new ListXform({
  6089. tag: 'definedNames',
  6090. count: false,
  6091. childXform: new DefinedNameXform()
  6092. }),
  6093. calcPr: new WorkbookCalcPropertiesXform()
  6094. };
  6095. }
  6096. prepare(model) {
  6097. model.sheets = model.worksheets;
  6098. // collate all the print areas from all of the sheets and add them to the defined names
  6099. const printAreas = [];
  6100. let index = 0; // sheets is sparse array - calc index manually
  6101. model.sheets.forEach(sheet => {
  6102. if (sheet.pageSetup && sheet.pageSetup.printArea) {
  6103. sheet.pageSetup.printArea.split('&&').forEach(printArea => {
  6104. const printAreaComponents = printArea.split(':');
  6105. const definedName = {
  6106. name: '_xlnm.Print_Area',
  6107. ranges: [`'${sheet.name}'!$${printAreaComponents[0]}:$${printAreaComponents[1]}`],
  6108. localSheetId: index
  6109. };
  6110. printAreas.push(definedName);
  6111. });
  6112. }
  6113. if (sheet.pageSetup && (sheet.pageSetup.printTitlesRow || sheet.pageSetup.printTitlesColumn)) {
  6114. const ranges = [];
  6115. if (sheet.pageSetup.printTitlesColumn) {
  6116. const titlesColumns = sheet.pageSetup.printTitlesColumn.split(':');
  6117. ranges.push(`'${sheet.name}'!$${titlesColumns[0]}:$${titlesColumns[1]}`);
  6118. }
  6119. if (sheet.pageSetup.printTitlesRow) {
  6120. const titlesRows = sheet.pageSetup.printTitlesRow.split(':');
  6121. ranges.push(`'${sheet.name}'!$${titlesRows[0]}:$${titlesRows[1]}`);
  6122. }
  6123. const definedName = {
  6124. name: '_xlnm.Print_Titles',
  6125. ranges,
  6126. localSheetId: index
  6127. };
  6128. printAreas.push(definedName);
  6129. }
  6130. index++;
  6131. });
  6132. if (printAreas.length) {
  6133. model.definedNames = model.definedNames.concat(printAreas);
  6134. }
  6135. (model.media || []).forEach((medium, i) => {
  6136. // assign name
  6137. medium.name = medium.type + (i + 1);
  6138. });
  6139. }
  6140. render(xmlStream, model) {
  6141. xmlStream.openXml(XmlStream.StdDocAttributes);
  6142. xmlStream.openNode('workbook', WorkbookXform.WORKBOOK_ATTRIBUTES);
  6143. this.map.fileVersion.render(xmlStream);
  6144. this.map.workbookPr.render(xmlStream, model.properties);
  6145. this.map.bookViews.render(xmlStream, model.views);
  6146. this.map.sheets.render(xmlStream, model.sheets);
  6147. this.map.definedNames.render(xmlStream, model.definedNames);
  6148. this.map.calcPr.render(xmlStream, model.calcProperties);
  6149. xmlStream.closeNode();
  6150. }
  6151. parseOpen(node) {
  6152. if (this.parser) {
  6153. this.parser.parseOpen(node);
  6154. return true;
  6155. }
  6156. switch (node.name) {
  6157. case 'workbook':
  6158. return true;
  6159. default:
  6160. this.parser = this.map[node.name];
  6161. if (this.parser) {
  6162. this.parser.parseOpen(node);
  6163. }
  6164. return true;
  6165. }
  6166. }
  6167. parseText(text) {
  6168. if (this.parser) {
  6169. this.parser.parseText(text);
  6170. }
  6171. }
  6172. parseClose(name) {
  6173. if (this.parser) {
  6174. if (!this.parser.parseClose(name)) {
  6175. this.parser = undefined;
  6176. }
  6177. return true;
  6178. }
  6179. switch (name) {
  6180. case 'workbook':
  6181. this.model = {
  6182. sheets: this.map.sheets.model,
  6183. properties: this.map.workbookPr.model || {},
  6184. views: this.map.bookViews.model,
  6185. calcProperties: {}
  6186. };
  6187. if (this.map.definedNames.model) {
  6188. this.model.definedNames = this.map.definedNames.model;
  6189. }
  6190. return false;
  6191. default:
  6192. // not quite sure how we get here!
  6193. return true;
  6194. }
  6195. }
  6196. reconcile(model) {
  6197. const rels = (model.workbookRels || []).reduce((map, rel) => {
  6198. map[rel.Id] = rel;
  6199. return map;
  6200. }, {});
  6201. // reconcile sheet ids, rIds and names
  6202. const worksheets = [];
  6203. let worksheet;
  6204. let index = 0;
  6205. (model.sheets || []).forEach(sheet => {
  6206. const rel = rels[sheet.rId];
  6207. if (!rel) {
  6208. return;
  6209. }
  6210. // if rel.Target start with `[space]/xl/` or `/xl/` , then it will be replaced with `''` and spliced behind `xl/`,
  6211. // otherwise it will be spliced directly behind `xl/`. i.g.
  6212. worksheet = model.worksheetHash[`xl/${rel.Target.replace(/^(\s|\/xl\/)+/, '')}`];
  6213. // If there are "chartsheets" in the file, rel.Target will
  6214. // come out as chartsheets/sheet1.xml or similar here, and
  6215. // that won't be in model.worksheetHash.
  6216. // As we don't have the infrastructure to support chartsheets,
  6217. // we will ignore them for now:
  6218. if (worksheet) {
  6219. worksheet.name = sheet.name;
  6220. worksheet.id = sheet.id;
  6221. worksheet.state = sheet.state;
  6222. worksheets[index++] = worksheet;
  6223. }
  6224. });
  6225. // reconcile print areas
  6226. const definedNames = [];
  6227. _.each(model.definedNames, definedName => {
  6228. if (definedName.name === '_xlnm.Print_Area') {
  6229. worksheet = worksheets[definedName.localSheetId];
  6230. if (worksheet) {
  6231. if (!worksheet.pageSetup) {
  6232. worksheet.pageSetup = {};
  6233. }
  6234. const range = colCache.decodeEx(definedName.ranges[0]);
  6235. worksheet.pageSetup.printArea = worksheet.pageSetup.printArea ? `${worksheet.pageSetup.printArea}&&${range.dimensions}` : range.dimensions;
  6236. }
  6237. } else if (definedName.name === '_xlnm.Print_Titles') {
  6238. worksheet = worksheets[definedName.localSheetId];
  6239. if (worksheet) {
  6240. if (!worksheet.pageSetup) {
  6241. worksheet.pageSetup = {};
  6242. }
  6243. const rangeString = definedName.ranges.join(',');
  6244. const dollarRegex = /\$/g;
  6245. const rowRangeRegex = /\$\d+:\$\d+/;
  6246. const rowRangeMatches = rangeString.match(rowRangeRegex);
  6247. if (rowRangeMatches && rowRangeMatches.length) {
  6248. const range = rowRangeMatches[0];
  6249. worksheet.pageSetup.printTitlesRow = range.replace(dollarRegex, '');
  6250. }
  6251. const columnRangeRegex = /\$[A-Z]+:\$[A-Z]+/;
  6252. const columnRangeMatches = rangeString.match(columnRangeRegex);
  6253. if (columnRangeMatches && columnRangeMatches.length) {
  6254. const range = columnRangeMatches[0];
  6255. worksheet.pageSetup.printTitlesColumn = range.replace(dollarRegex, '');
  6256. }
  6257. }
  6258. } else {
  6259. definedNames.push(definedName);
  6260. }
  6261. });
  6262. model.definedNames = definedNames;
  6263. // used by sheets to build their image models
  6264. model.media.forEach((media, i) => {
  6265. media.index = i;
  6266. });
  6267. }
  6268. }
  6269. WorkbookXform.WORKBOOK_ATTRIBUTES = {
  6270. xmlns: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  6271. 'xmlns:r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  6272. 'xmlns:mc': 'http://schemas.openxmlformats.org/markup-compatibility/2006',
  6273. 'mc:Ignorable': 'x15',
  6274. 'xmlns:x15': 'http://schemas.microsoft.com/office/spreadsheetml/2010/11/main'
  6275. };
  6276. WorkbookXform.STATIC_XFORMS = {
  6277. fileVersion: new StaticXform({
  6278. tag: 'fileVersion',
  6279. $: {
  6280. appName: 'xl',
  6281. lastEdited: 5,
  6282. lowestEdited: 5,
  6283. rupBuild: 9303
  6284. }
  6285. })
  6286. };
  6287. module.exports = WorkbookXform;
  6288. },{"../../../utils/col-cache":19,"../../../utils/under-dash":26,"../../../utils/xml-stream":28,"../base-xform":32,"../list-xform":71,"../static-xform":120,"./defined-name-xform":33,"./sheet-xform":34,"./workbook-calc-properties-xform":35,"./workbook-properties-xform":36,"./workbook-view-xform":37}],39:[function(require,module,exports){
  6289. "use strict";
  6290. const RichTextXform = require('../strings/rich-text-xform');
  6291. const utils = require('../../../utils/utils');
  6292. const BaseXform = require('../base-xform');
  6293. /**
  6294. <comment ref="B1" authorId="0">
  6295. <text>
  6296. <r>
  6297. <rPr>
  6298. <b/>
  6299. <sz val="9"/>
  6300. <rFont val="宋体"/>
  6301. <charset val="134"/>
  6302. </rPr>
  6303. <t>51422:</t>
  6304. </r>
  6305. <r>
  6306. <rPr>
  6307. <sz val="9"/>
  6308. <rFont val="宋体"/>
  6309. <charset val="134"/>
  6310. </rPr>
  6311. <t xml:space="preserve">&#10;test</t>
  6312. </r>
  6313. </text>
  6314. </comment>
  6315. */
  6316. const CommentXform = module.exports = function (model) {
  6317. this.model = model;
  6318. };
  6319. utils.inherits(CommentXform, BaseXform, {
  6320. get tag() {
  6321. return 'r';
  6322. },
  6323. get richTextXform() {
  6324. if (!this._richTextXform) {
  6325. this._richTextXform = new RichTextXform();
  6326. }
  6327. return this._richTextXform;
  6328. },
  6329. render(xmlStream, model) {
  6330. model = model || this.model;
  6331. xmlStream.openNode('comment', {
  6332. ref: model.ref,
  6333. authorId: 0
  6334. });
  6335. xmlStream.openNode('text');
  6336. if (model && model.note && model.note.texts) {
  6337. model.note.texts.forEach(text => {
  6338. this.richTextXform.render(xmlStream, text);
  6339. });
  6340. }
  6341. xmlStream.closeNode();
  6342. xmlStream.closeNode();
  6343. },
  6344. parseOpen(node) {
  6345. if (this.parser) {
  6346. this.parser.parseOpen(node);
  6347. return true;
  6348. }
  6349. switch (node.name) {
  6350. case 'comment':
  6351. this.model = {
  6352. type: 'note',
  6353. note: {
  6354. texts: []
  6355. },
  6356. ...node.attributes
  6357. };
  6358. return true;
  6359. case 'r':
  6360. this.parser = this.richTextXform;
  6361. this.parser.parseOpen(node);
  6362. return true;
  6363. default:
  6364. return false;
  6365. }
  6366. },
  6367. parseText(text) {
  6368. if (this.parser) {
  6369. this.parser.parseText(text);
  6370. }
  6371. },
  6372. parseClose(name) {
  6373. switch (name) {
  6374. case 'comment':
  6375. return false;
  6376. case 'r':
  6377. this.model.note.texts.push(this.parser.model);
  6378. this.parser = undefined;
  6379. return true;
  6380. default:
  6381. if (this.parser) {
  6382. this.parser.parseClose(name);
  6383. }
  6384. return true;
  6385. }
  6386. }
  6387. });
  6388. },{"../../../utils/utils":27,"../base-xform":32,"../strings/rich-text-xform":122}],40:[function(require,module,exports){
  6389. "use strict";
  6390. const XmlStream = require('../../../utils/xml-stream');
  6391. const utils = require('../../../utils/utils');
  6392. const BaseXform = require('../base-xform');
  6393. const CommentXform = require('./comment-xform');
  6394. const CommentsXform = module.exports = function () {
  6395. this.map = {
  6396. comment: new CommentXform()
  6397. };
  6398. };
  6399. utils.inherits(CommentsXform, BaseXform, {
  6400. COMMENTS_ATTRIBUTES: {
  6401. xmlns: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'
  6402. }
  6403. }, {
  6404. render(xmlStream, model) {
  6405. model = model || this.model;
  6406. xmlStream.openXml(XmlStream.StdDocAttributes);
  6407. xmlStream.openNode('comments', CommentsXform.COMMENTS_ATTRIBUTES);
  6408. // authors
  6409. // TODO: support authors properly
  6410. xmlStream.openNode('authors');
  6411. xmlStream.leafNode('author', null, 'Author');
  6412. xmlStream.closeNode();
  6413. // comments
  6414. xmlStream.openNode('commentList');
  6415. model.comments.forEach(comment => {
  6416. this.map.comment.render(xmlStream, comment);
  6417. });
  6418. xmlStream.closeNode();
  6419. xmlStream.closeNode();
  6420. },
  6421. parseOpen(node) {
  6422. if (this.parser) {
  6423. this.parser.parseOpen(node);
  6424. return true;
  6425. }
  6426. switch (node.name) {
  6427. case 'commentList':
  6428. this.model = {
  6429. comments: []
  6430. };
  6431. return true;
  6432. case 'comment':
  6433. this.parser = this.map.comment;
  6434. this.parser.parseOpen(node);
  6435. return true;
  6436. default:
  6437. return false;
  6438. }
  6439. },
  6440. parseText(text) {
  6441. if (this.parser) {
  6442. this.parser.parseText(text);
  6443. }
  6444. },
  6445. parseClose(name) {
  6446. switch (name) {
  6447. case 'commentList':
  6448. return false;
  6449. case 'comment':
  6450. this.model.comments.push(this.parser.model);
  6451. this.parser = undefined;
  6452. return true;
  6453. default:
  6454. if (this.parser) {
  6455. this.parser.parseClose(name);
  6456. }
  6457. return true;
  6458. }
  6459. }
  6460. });
  6461. },{"../../../utils/utils":27,"../../../utils/xml-stream":28,"../base-xform":32,"./comment-xform":39}],41:[function(require,module,exports){
  6462. "use strict";
  6463. const BaseXform = require('../../base-xform');
  6464. class VmlPositionXform extends BaseXform {
  6465. constructor(model) {
  6466. super();
  6467. this._model = model;
  6468. }
  6469. get tag() {
  6470. return this._model && this._model.tag;
  6471. }
  6472. render(xmlStream, model, type) {
  6473. if (model === type[2]) {
  6474. xmlStream.leafNode(this.tag);
  6475. } else if (this.tag === 'x:SizeWithCells' && model === type[1]) {
  6476. xmlStream.leafNode(this.tag);
  6477. }
  6478. }
  6479. parseOpen(node) {
  6480. switch (node.name) {
  6481. case this.tag:
  6482. this.model = {};
  6483. this.model[this.tag] = true;
  6484. return true;
  6485. default:
  6486. return false;
  6487. }
  6488. }
  6489. parseText() {}
  6490. parseClose() {
  6491. return false;
  6492. }
  6493. }
  6494. module.exports = VmlPositionXform;
  6495. },{"../../base-xform":32}],42:[function(require,module,exports){
  6496. "use strict";
  6497. const BaseXform = require('../../base-xform');
  6498. class VmlProtectionXform extends BaseXform {
  6499. constructor(model) {
  6500. super();
  6501. this._model = model;
  6502. }
  6503. get tag() {
  6504. return this._model && this._model.tag;
  6505. }
  6506. render(xmlStream, model) {
  6507. xmlStream.leafNode(this.tag, null, model);
  6508. }
  6509. parseOpen(node) {
  6510. switch (node.name) {
  6511. case this.tag:
  6512. this.text = '';
  6513. return true;
  6514. default:
  6515. return false;
  6516. }
  6517. }
  6518. parseText(text) {
  6519. this.text = text;
  6520. }
  6521. parseClose() {
  6522. return false;
  6523. }
  6524. }
  6525. module.exports = VmlProtectionXform;
  6526. },{"../../base-xform":32}],43:[function(require,module,exports){
  6527. "use strict";
  6528. const BaseXform = require('../base-xform');
  6529. // render the triangle in the cell for the comment
  6530. class VmlAnchorXform extends BaseXform {
  6531. get tag() {
  6532. return 'x:Anchor';
  6533. }
  6534. getAnchorRect(anchor) {
  6535. const l = Math.floor(anchor.left);
  6536. const lf = Math.floor((anchor.left - l) * 68);
  6537. const t = Math.floor(anchor.top);
  6538. const tf = Math.floor((anchor.top - t) * 18);
  6539. const r = Math.floor(anchor.right);
  6540. const rf = Math.floor((anchor.right - r) * 68);
  6541. const b = Math.floor(anchor.bottom);
  6542. const bf = Math.floor((anchor.bottom - b) * 18);
  6543. return [l, lf, t, tf, r, rf, b, bf];
  6544. }
  6545. getDefaultRect(ref) {
  6546. const l = ref.col;
  6547. const lf = 6;
  6548. const t = Math.max(ref.row - 2, 0);
  6549. const tf = 14;
  6550. const r = l + 2;
  6551. const rf = 2;
  6552. const b = t + 4;
  6553. const bf = 16;
  6554. return [l, lf, t, tf, r, rf, b, bf];
  6555. }
  6556. render(xmlStream, model) {
  6557. const rect = model.anchor ? this.getAnchorRect(model.anchor) : this.getDefaultRect(model.refAddress);
  6558. xmlStream.leafNode('x:Anchor', null, rect.join(', '));
  6559. }
  6560. parseOpen(node) {
  6561. switch (node.name) {
  6562. case this.tag:
  6563. this.text = '';
  6564. return true;
  6565. default:
  6566. return false;
  6567. }
  6568. }
  6569. parseText(text) {
  6570. this.text = text;
  6571. }
  6572. parseClose() {
  6573. return false;
  6574. }
  6575. }
  6576. module.exports = VmlAnchorXform;
  6577. },{"../base-xform":32}],44:[function(require,module,exports){
  6578. "use strict";
  6579. const BaseXform = require('../base-xform');
  6580. const VmlAnchorXform = require('./vml-anchor-xform');
  6581. const VmlProtectionXform = require('./style/vml-protection-xform');
  6582. const VmlPositionXform = require('./style/vml-position-xform');
  6583. const POSITION_TYPE = ['twoCells', 'oneCells', 'absolute'];
  6584. class VmlClientDataXform extends BaseXform {
  6585. constructor() {
  6586. super();
  6587. this.map = {
  6588. 'x:Anchor': new VmlAnchorXform(),
  6589. 'x:Locked': new VmlProtectionXform({
  6590. tag: 'x:Locked'
  6591. }),
  6592. 'x:LockText': new VmlProtectionXform({
  6593. tag: 'x:LockText'
  6594. }),
  6595. 'x:SizeWithCells': new VmlPositionXform({
  6596. tag: 'x:SizeWithCells'
  6597. }),
  6598. 'x:MoveWithCells': new VmlPositionXform({
  6599. tag: 'x:MoveWithCells'
  6600. })
  6601. };
  6602. }
  6603. get tag() {
  6604. return 'x:ClientData';
  6605. }
  6606. render(xmlStream, model) {
  6607. const {
  6608. protection,
  6609. editAs
  6610. } = model.note;
  6611. xmlStream.openNode(this.tag, {
  6612. ObjectType: 'Note'
  6613. });
  6614. this.map['x:MoveWithCells'].render(xmlStream, editAs, POSITION_TYPE);
  6615. this.map['x:SizeWithCells'].render(xmlStream, editAs, POSITION_TYPE);
  6616. this.map['x:Anchor'].render(xmlStream, model);
  6617. this.map['x:Locked'].render(xmlStream, protection.locked);
  6618. xmlStream.leafNode('x:AutoFill', null, 'False');
  6619. this.map['x:LockText'].render(xmlStream, protection.lockText);
  6620. xmlStream.leafNode('x:Row', null, model.refAddress.row - 1);
  6621. xmlStream.leafNode('x:Column', null, model.refAddress.col - 1);
  6622. xmlStream.closeNode();
  6623. }
  6624. parseOpen(node) {
  6625. switch (node.name) {
  6626. case this.tag:
  6627. this.reset();
  6628. this.model = {
  6629. anchor: [],
  6630. protection: {},
  6631. editAs: ''
  6632. };
  6633. break;
  6634. default:
  6635. this.parser = this.map[node.name];
  6636. if (this.parser) {
  6637. this.parser.parseOpen(node);
  6638. }
  6639. break;
  6640. }
  6641. return true;
  6642. }
  6643. parseText(text) {
  6644. if (this.parser) {
  6645. this.parser.parseText(text);
  6646. }
  6647. }
  6648. parseClose(name) {
  6649. if (this.parser) {
  6650. if (!this.parser.parseClose(name)) {
  6651. this.parser = undefined;
  6652. }
  6653. return true;
  6654. }
  6655. switch (name) {
  6656. case this.tag:
  6657. this.normalizeModel();
  6658. return false;
  6659. default:
  6660. return true;
  6661. }
  6662. }
  6663. normalizeModel() {
  6664. const position = Object.assign({}, this.map['x:MoveWithCells'].model, this.map['x:SizeWithCells'].model);
  6665. const len = Object.keys(position).length;
  6666. this.model.editAs = POSITION_TYPE[len];
  6667. this.model.anchor = this.map['x:Anchor'].text;
  6668. this.model.protection.locked = this.map['x:Locked'].text;
  6669. this.model.protection.lockText = this.map['x:LockText'].text;
  6670. }
  6671. }
  6672. module.exports = VmlClientDataXform;
  6673. },{"../base-xform":32,"./style/vml-position-xform":41,"./style/vml-protection-xform":42,"./vml-anchor-xform":43}],45:[function(require,module,exports){
  6674. "use strict";
  6675. const XmlStream = require('../../../utils/xml-stream');
  6676. const BaseXform = require('../base-xform');
  6677. const VmlShapeXform = require('./vml-shape-xform');
  6678. // This class is (currently) single purposed to insert the triangle
  6679. // drawing icons on commented cells
  6680. class VmlNotesXform extends BaseXform {
  6681. constructor() {
  6682. super();
  6683. this.map = {
  6684. 'v:shape': new VmlShapeXform()
  6685. };
  6686. }
  6687. get tag() {
  6688. return 'xml';
  6689. }
  6690. render(xmlStream, model) {
  6691. xmlStream.openXml(XmlStream.StdDocAttributes);
  6692. xmlStream.openNode(this.tag, VmlNotesXform.DRAWING_ATTRIBUTES);
  6693. xmlStream.openNode('o:shapelayout', {
  6694. 'v:ext': 'edit'
  6695. });
  6696. xmlStream.leafNode('o:idmap', {
  6697. 'v:ext': 'edit',
  6698. data: 1
  6699. });
  6700. xmlStream.closeNode();
  6701. xmlStream.openNode('v:shapetype', {
  6702. id: '_x0000_t202',
  6703. coordsize: '21600,21600',
  6704. 'o:spt': 202,
  6705. path: 'm,l,21600r21600,l21600,xe'
  6706. });
  6707. xmlStream.leafNode('v:stroke', {
  6708. joinstyle: 'miter'
  6709. });
  6710. xmlStream.leafNode('v:path', {
  6711. gradientshapeok: 't',
  6712. 'o:connecttype': 'rect'
  6713. });
  6714. xmlStream.closeNode();
  6715. model.comments.forEach((item, index) => {
  6716. this.map['v:shape'].render(xmlStream, item, index);
  6717. });
  6718. xmlStream.closeNode();
  6719. }
  6720. parseOpen(node) {
  6721. if (this.parser) {
  6722. this.parser.parseOpen(node);
  6723. return true;
  6724. }
  6725. switch (node.name) {
  6726. case this.tag:
  6727. this.reset();
  6728. this.model = {
  6729. comments: []
  6730. };
  6731. break;
  6732. default:
  6733. this.parser = this.map[node.name];
  6734. if (this.parser) {
  6735. this.parser.parseOpen(node);
  6736. }
  6737. break;
  6738. }
  6739. return true;
  6740. }
  6741. parseText(text) {
  6742. if (this.parser) {
  6743. this.parser.parseText(text);
  6744. }
  6745. }
  6746. parseClose(name) {
  6747. if (this.parser) {
  6748. if (!this.parser.parseClose(name)) {
  6749. this.model.comments.push(this.parser.model);
  6750. this.parser = undefined;
  6751. }
  6752. return true;
  6753. }
  6754. switch (name) {
  6755. case this.tag:
  6756. return false;
  6757. default:
  6758. // could be some unrecognised tags
  6759. return true;
  6760. }
  6761. }
  6762. reconcile(model, options) {
  6763. model.anchors.forEach(anchor => {
  6764. if (anchor.br) {
  6765. this.map['xdr:twoCellAnchor'].reconcile(anchor, options);
  6766. } else {
  6767. this.map['xdr:oneCellAnchor'].reconcile(anchor, options);
  6768. }
  6769. });
  6770. }
  6771. }
  6772. VmlNotesXform.DRAWING_ATTRIBUTES = {
  6773. 'xmlns:v': 'urn:schemas-microsoft-com:vml',
  6774. 'xmlns:o': 'urn:schemas-microsoft-com:office:office',
  6775. 'xmlns:x': 'urn:schemas-microsoft-com:office:excel'
  6776. };
  6777. module.exports = VmlNotesXform;
  6778. },{"../../../utils/xml-stream":28,"../base-xform":32,"./vml-shape-xform":46}],46:[function(require,module,exports){
  6779. "use strict";
  6780. const BaseXform = require('../base-xform');
  6781. const VmlTextboxXform = require('./vml-textbox-xform');
  6782. const VmlClientDataXform = require('./vml-client-data-xform');
  6783. class VmlShapeXform extends BaseXform {
  6784. constructor() {
  6785. super();
  6786. this.map = {
  6787. 'v:textbox': new VmlTextboxXform(),
  6788. 'x:ClientData': new VmlClientDataXform()
  6789. };
  6790. }
  6791. get tag() {
  6792. return 'v:shape';
  6793. }
  6794. render(xmlStream, model, index) {
  6795. xmlStream.openNode('v:shape', VmlShapeXform.V_SHAPE_ATTRIBUTES(model, index));
  6796. xmlStream.leafNode('v:fill', {
  6797. color2: 'infoBackground [80]'
  6798. });
  6799. xmlStream.leafNode('v:shadow', {
  6800. color: 'none [81]',
  6801. obscured: 't'
  6802. });
  6803. xmlStream.leafNode('v:path', {
  6804. 'o:connecttype': 'none'
  6805. });
  6806. this.map['v:textbox'].render(xmlStream, model);
  6807. this.map['x:ClientData'].render(xmlStream, model);
  6808. xmlStream.closeNode();
  6809. }
  6810. parseOpen(node) {
  6811. if (this.parser) {
  6812. this.parser.parseOpen(node);
  6813. return true;
  6814. }
  6815. switch (node.name) {
  6816. case this.tag:
  6817. this.reset();
  6818. this.model = {
  6819. margins: {
  6820. insetmode: node.attributes['o:insetmode']
  6821. },
  6822. anchor: '',
  6823. editAs: '',
  6824. protection: {}
  6825. };
  6826. break;
  6827. default:
  6828. this.parser = this.map[node.name];
  6829. if (this.parser) {
  6830. this.parser.parseOpen(node);
  6831. }
  6832. break;
  6833. }
  6834. return true;
  6835. }
  6836. parseText(text) {
  6837. if (this.parser) {
  6838. this.parser.parseText(text);
  6839. }
  6840. }
  6841. parseClose(name) {
  6842. if (this.parser) {
  6843. if (!this.parser.parseClose(name)) {
  6844. this.parser = undefined;
  6845. }
  6846. return true;
  6847. }
  6848. switch (name) {
  6849. case this.tag:
  6850. this.model.margins.inset = this.map['v:textbox'].model && this.map['v:textbox'].model.inset;
  6851. this.model.protection = this.map['x:ClientData'].model && this.map['x:ClientData'].model.protection;
  6852. this.model.anchor = this.map['x:ClientData'].model && this.map['x:ClientData'].model.anchor;
  6853. this.model.editAs = this.map['x:ClientData'].model && this.map['x:ClientData'].model.editAs;
  6854. return false;
  6855. default:
  6856. return true;
  6857. }
  6858. }
  6859. }
  6860. VmlShapeXform.V_SHAPE_ATTRIBUTES = (model, index) => ({
  6861. id: `_x0000_s${1025 + index}`,
  6862. type: '#_x0000_t202',
  6863. style: 'position:absolute; margin-left:105.3pt;margin-top:10.5pt;width:97.8pt;height:59.1pt;z-index:1;visibility:hidden',
  6864. fillcolor: 'infoBackground [80]',
  6865. strokecolor: 'none [81]',
  6866. 'o:insetmode': model.note.margins && model.note.margins.insetmode
  6867. });
  6868. module.exports = VmlShapeXform;
  6869. },{"../base-xform":32,"./vml-client-data-xform":44,"./vml-textbox-xform":47}],47:[function(require,module,exports){
  6870. "use strict";
  6871. const BaseXform = require('../base-xform');
  6872. class VmlTextboxXform extends BaseXform {
  6873. get tag() {
  6874. return 'v:textbox';
  6875. }
  6876. conversionUnit(value, multiple, unit) {
  6877. return `${parseFloat(value) * multiple.toFixed(2)}${unit}`;
  6878. }
  6879. reverseConversionUnit(inset) {
  6880. return (inset || '').split(',').map(margin => {
  6881. return Number(parseFloat(this.conversionUnit(parseFloat(margin), 0.1, '')).toFixed(2));
  6882. });
  6883. }
  6884. render(xmlStream, model) {
  6885. const attributes = {
  6886. style: 'mso-direction-alt:auto'
  6887. };
  6888. if (model && model.note) {
  6889. let {
  6890. inset
  6891. } = model.note && model.note.margins;
  6892. if (Array.isArray(inset)) {
  6893. inset = inset.map(margin => {
  6894. return this.conversionUnit(margin, 10, 'mm');
  6895. }).join(',');
  6896. }
  6897. if (inset) {
  6898. attributes.inset = inset;
  6899. }
  6900. }
  6901. xmlStream.openNode('v:textbox', attributes);
  6902. xmlStream.leafNode('div', {
  6903. style: 'text-align:left'
  6904. });
  6905. xmlStream.closeNode();
  6906. }
  6907. parseOpen(node) {
  6908. switch (node.name) {
  6909. case this.tag:
  6910. this.model = {
  6911. inset: this.reverseConversionUnit(node.attributes.inset)
  6912. };
  6913. return true;
  6914. default:
  6915. return true;
  6916. }
  6917. }
  6918. parseText() {}
  6919. parseClose(name) {
  6920. switch (name) {
  6921. case this.tag:
  6922. return false;
  6923. default:
  6924. return true;
  6925. }
  6926. }
  6927. }
  6928. module.exports = VmlTextboxXform;
  6929. },{"../base-xform":32}],48:[function(require,module,exports){
  6930. "use strict";
  6931. const BaseXform = require('./base-xform');
  6932. /* 'virtual' methods used as a form of documentation */
  6933. /* eslint-disable class-methods-use-this */
  6934. // base class for xforms that are composed of other xforms
  6935. // offers some default implementations
  6936. class CompositeXform extends BaseXform {
  6937. createNewModel(node) {
  6938. return {};
  6939. }
  6940. parseOpen(node) {
  6941. // Typical pattern for composite xform
  6942. this.parser = this.parser || this.map[node.name];
  6943. if (this.parser) {
  6944. this.parser.parseOpen(node);
  6945. return true;
  6946. }
  6947. if (node.name === this.tag) {
  6948. this.model = this.createNewModel(node);
  6949. return true;
  6950. }
  6951. return false;
  6952. }
  6953. parseText(text) {
  6954. // Default implementation. Send text to child parser
  6955. if (this.parser) {
  6956. this.parser.parseText(text);
  6957. }
  6958. }
  6959. onParserClose(name, parser) {
  6960. // parseClose has seen a child parser close
  6961. // now need to incorporate into this.model somehow
  6962. this.model[name] = parser.model;
  6963. }
  6964. parseClose(name) {
  6965. // Default implementation
  6966. if (this.parser) {
  6967. if (!this.parser.parseClose(name)) {
  6968. this.onParserClose(name, this.parser);
  6969. this.parser = undefined;
  6970. }
  6971. return true;
  6972. }
  6973. return name !== this.tag;
  6974. }
  6975. }
  6976. module.exports = CompositeXform;
  6977. },{"./base-xform":32}],49:[function(require,module,exports){
  6978. "use strict";
  6979. const BaseXform = require('../base-xform');
  6980. class AppHeadingPairsXform extends BaseXform {
  6981. render(xmlStream, model) {
  6982. xmlStream.openNode('HeadingPairs');
  6983. xmlStream.openNode('vt:vector', {
  6984. size: 2,
  6985. baseType: 'variant'
  6986. });
  6987. xmlStream.openNode('vt:variant');
  6988. xmlStream.leafNode('vt:lpstr', undefined, 'Worksheets');
  6989. xmlStream.closeNode();
  6990. xmlStream.openNode('vt:variant');
  6991. xmlStream.leafNode('vt:i4', undefined, model.length);
  6992. xmlStream.closeNode();
  6993. xmlStream.closeNode();
  6994. xmlStream.closeNode();
  6995. }
  6996. parseOpen(node) {
  6997. // no parsing
  6998. return node.name === 'HeadingPairs';
  6999. }
  7000. parseText() {}
  7001. parseClose(name) {
  7002. return name !== 'HeadingPairs';
  7003. }
  7004. }
  7005. module.exports = AppHeadingPairsXform;
  7006. },{"../base-xform":32}],50:[function(require,module,exports){
  7007. "use strict";
  7008. const BaseXform = require('../base-xform');
  7009. class AppTitlesOfPartsXform extends BaseXform {
  7010. render(xmlStream, model) {
  7011. xmlStream.openNode('TitlesOfParts');
  7012. xmlStream.openNode('vt:vector', {
  7013. size: model.length,
  7014. baseType: 'lpstr'
  7015. });
  7016. model.forEach(sheet => {
  7017. xmlStream.leafNode('vt:lpstr', undefined, sheet.name);
  7018. });
  7019. xmlStream.closeNode();
  7020. xmlStream.closeNode();
  7021. }
  7022. parseOpen(node) {
  7023. // no parsing
  7024. return node.name === 'TitlesOfParts';
  7025. }
  7026. parseText() {}
  7027. parseClose(name) {
  7028. return name !== 'TitlesOfParts';
  7029. }
  7030. }
  7031. module.exports = AppTitlesOfPartsXform;
  7032. },{"../base-xform":32}],51:[function(require,module,exports){
  7033. "use strict";
  7034. const XmlStream = require('../../../utils/xml-stream');
  7035. const BaseXform = require('../base-xform');
  7036. const StringXform = require('../simple/string-xform');
  7037. const AppHeadingPairsXform = require('./app-heading-pairs-xform');
  7038. const AppTitleOfPartsXform = require('./app-titles-of-parts-xform');
  7039. class AppXform extends BaseXform {
  7040. constructor() {
  7041. super();
  7042. this.map = {
  7043. Company: new StringXform({
  7044. tag: 'Company'
  7045. }),
  7046. Manager: new StringXform({
  7047. tag: 'Manager'
  7048. }),
  7049. HeadingPairs: new AppHeadingPairsXform(),
  7050. TitleOfParts: new AppTitleOfPartsXform()
  7051. };
  7052. }
  7053. render(xmlStream, model) {
  7054. xmlStream.openXml(XmlStream.StdDocAttributes);
  7055. xmlStream.openNode('Properties', AppXform.PROPERTY_ATTRIBUTES);
  7056. xmlStream.leafNode('Application', undefined, 'Microsoft Excel');
  7057. xmlStream.leafNode('DocSecurity', undefined, '0');
  7058. xmlStream.leafNode('ScaleCrop', undefined, 'false');
  7059. this.map.HeadingPairs.render(xmlStream, model.worksheets);
  7060. this.map.TitleOfParts.render(xmlStream, model.worksheets);
  7061. this.map.Company.render(xmlStream, model.company || '');
  7062. this.map.Manager.render(xmlStream, model.manager);
  7063. xmlStream.leafNode('LinksUpToDate', undefined, 'false');
  7064. xmlStream.leafNode('SharedDoc', undefined, 'false');
  7065. xmlStream.leafNode('HyperlinksChanged', undefined, 'false');
  7066. xmlStream.leafNode('AppVersion', undefined, '16.0300');
  7067. xmlStream.closeNode();
  7068. }
  7069. parseOpen(node) {
  7070. if (this.parser) {
  7071. this.parser.parseOpen(node);
  7072. return true;
  7073. }
  7074. switch (node.name) {
  7075. case 'Properties':
  7076. return true;
  7077. default:
  7078. this.parser = this.map[node.name];
  7079. if (this.parser) {
  7080. this.parser.parseOpen(node);
  7081. return true;
  7082. }
  7083. // there's a lot we don't bother to parse
  7084. return false;
  7085. }
  7086. }
  7087. parseText(text) {
  7088. if (this.parser) {
  7089. this.parser.parseText(text);
  7090. }
  7091. }
  7092. parseClose(name) {
  7093. if (this.parser) {
  7094. if (!this.parser.parseClose(name)) {
  7095. this.parser = undefined;
  7096. }
  7097. return true;
  7098. }
  7099. switch (name) {
  7100. case 'Properties':
  7101. this.model = {
  7102. worksheets: this.map.TitleOfParts.model,
  7103. company: this.map.Company.model,
  7104. manager: this.map.Manager.model
  7105. };
  7106. return false;
  7107. default:
  7108. return true;
  7109. }
  7110. }
  7111. }
  7112. AppXform.DateFormat = function (dt) {
  7113. return dt.toISOString().replace(/[.]\d{3,6}/, '');
  7114. };
  7115. AppXform.DateAttrs = {
  7116. 'xsi:type': 'dcterms:W3CDTF'
  7117. };
  7118. AppXform.PROPERTY_ATTRIBUTES = {
  7119. xmlns: 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties',
  7120. 'xmlns:vt': 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'
  7121. };
  7122. module.exports = AppXform;
  7123. },{"../../../utils/xml-stream":28,"../base-xform":32,"../simple/string-xform":119,"./app-heading-pairs-xform":49,"./app-titles-of-parts-xform":50}],52:[function(require,module,exports){
  7124. "use strict";
  7125. const XmlStream = require('../../../utils/xml-stream');
  7126. const BaseXform = require('../base-xform');
  7127. // used for rendering the [Content_Types].xml file
  7128. // not used for parsing
  7129. class ContentTypesXform extends BaseXform {
  7130. render(xmlStream, model) {
  7131. xmlStream.openXml(XmlStream.StdDocAttributes);
  7132. xmlStream.openNode('Types', ContentTypesXform.PROPERTY_ATTRIBUTES);
  7133. const mediaHash = {};
  7134. (model.media || []).forEach(medium => {
  7135. if (medium.type === 'image') {
  7136. const imageType = medium.extension;
  7137. if (!mediaHash[imageType]) {
  7138. mediaHash[imageType] = true;
  7139. xmlStream.leafNode('Default', {
  7140. Extension: imageType,
  7141. ContentType: `image/${imageType}`
  7142. });
  7143. }
  7144. }
  7145. });
  7146. xmlStream.leafNode('Default', {
  7147. Extension: 'rels',
  7148. ContentType: 'application/vnd.openxmlformats-package.relationships+xml'
  7149. });
  7150. xmlStream.leafNode('Default', {
  7151. Extension: 'xml',
  7152. ContentType: 'application/xml'
  7153. });
  7154. xmlStream.leafNode('Override', {
  7155. PartName: '/xl/workbook.xml',
  7156. ContentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'
  7157. });
  7158. model.worksheets.forEach(worksheet => {
  7159. const name = `/xl/worksheets/sheet${worksheet.id}.xml`;
  7160. xmlStream.leafNode('Override', {
  7161. PartName: name,
  7162. ContentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'
  7163. });
  7164. });
  7165. xmlStream.leafNode('Override', {
  7166. PartName: '/xl/theme/theme1.xml',
  7167. ContentType: 'application/vnd.openxmlformats-officedocument.theme+xml'
  7168. });
  7169. xmlStream.leafNode('Override', {
  7170. PartName: '/xl/styles.xml',
  7171. ContentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'
  7172. });
  7173. const hasSharedStrings = model.sharedStrings && model.sharedStrings.count;
  7174. if (hasSharedStrings) {
  7175. xmlStream.leafNode('Override', {
  7176. PartName: '/xl/sharedStrings.xml',
  7177. ContentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'
  7178. });
  7179. }
  7180. if (model.tables) {
  7181. model.tables.forEach(table => {
  7182. xmlStream.leafNode('Override', {
  7183. PartName: `/xl/tables/${table.target}`,
  7184. ContentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml'
  7185. });
  7186. });
  7187. }
  7188. if (model.drawings) {
  7189. model.drawings.forEach(drawing => {
  7190. xmlStream.leafNode('Override', {
  7191. PartName: `/xl/drawings/${drawing.name}.xml`,
  7192. ContentType: 'application/vnd.openxmlformats-officedocument.drawing+xml'
  7193. });
  7194. });
  7195. }
  7196. if (model.commentRefs) {
  7197. xmlStream.leafNode('Default', {
  7198. Extension: 'vml',
  7199. ContentType: 'application/vnd.openxmlformats-officedocument.vmlDrawing'
  7200. });
  7201. model.commentRefs.forEach(_ref => {
  7202. let {
  7203. commentName
  7204. } = _ref;
  7205. xmlStream.leafNode('Override', {
  7206. PartName: `/xl/${commentName}.xml`,
  7207. ContentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml'
  7208. });
  7209. });
  7210. }
  7211. xmlStream.leafNode('Override', {
  7212. PartName: '/docProps/core.xml',
  7213. ContentType: 'application/vnd.openxmlformats-package.core-properties+xml'
  7214. });
  7215. xmlStream.leafNode('Override', {
  7216. PartName: '/docProps/app.xml',
  7217. ContentType: 'application/vnd.openxmlformats-officedocument.extended-properties+xml'
  7218. });
  7219. xmlStream.closeNode();
  7220. }
  7221. parseOpen() {
  7222. return false;
  7223. }
  7224. parseText() {}
  7225. parseClose() {
  7226. return false;
  7227. }
  7228. }
  7229. ContentTypesXform.PROPERTY_ATTRIBUTES = {
  7230. xmlns: 'http://schemas.openxmlformats.org/package/2006/content-types'
  7231. };
  7232. module.exports = ContentTypesXform;
  7233. },{"../../../utils/xml-stream":28,"../base-xform":32}],53:[function(require,module,exports){
  7234. "use strict";
  7235. const XmlStream = require('../../../utils/xml-stream');
  7236. const BaseXform = require('../base-xform');
  7237. const DateXform = require('../simple/date-xform');
  7238. const StringXform = require('../simple/string-xform');
  7239. const IntegerXform = require('../simple/integer-xform');
  7240. class CoreXform extends BaseXform {
  7241. constructor() {
  7242. super();
  7243. this.map = {
  7244. 'dc:creator': new StringXform({
  7245. tag: 'dc:creator'
  7246. }),
  7247. 'dc:title': new StringXform({
  7248. tag: 'dc:title'
  7249. }),
  7250. 'dc:subject': new StringXform({
  7251. tag: 'dc:subject'
  7252. }),
  7253. 'dc:description': new StringXform({
  7254. tag: 'dc:description'
  7255. }),
  7256. 'dc:identifier': new StringXform({
  7257. tag: 'dc:identifier'
  7258. }),
  7259. 'dc:language': new StringXform({
  7260. tag: 'dc:language'
  7261. }),
  7262. 'cp:keywords': new StringXform({
  7263. tag: 'cp:keywords'
  7264. }),
  7265. 'cp:category': new StringXform({
  7266. tag: 'cp:category'
  7267. }),
  7268. 'cp:lastModifiedBy': new StringXform({
  7269. tag: 'cp:lastModifiedBy'
  7270. }),
  7271. 'cp:lastPrinted': new DateXform({
  7272. tag: 'cp:lastPrinted',
  7273. format: CoreXform.DateFormat
  7274. }),
  7275. 'cp:revision': new IntegerXform({
  7276. tag: 'cp:revision'
  7277. }),
  7278. 'cp:version': new StringXform({
  7279. tag: 'cp:version'
  7280. }),
  7281. 'cp:contentStatus': new StringXform({
  7282. tag: 'cp:contentStatus'
  7283. }),
  7284. 'cp:contentType': new StringXform({
  7285. tag: 'cp:contentType'
  7286. }),
  7287. 'dcterms:created': new DateXform({
  7288. tag: 'dcterms:created',
  7289. attrs: CoreXform.DateAttrs,
  7290. format: CoreXform.DateFormat
  7291. }),
  7292. 'dcterms:modified': new DateXform({
  7293. tag: 'dcterms:modified',
  7294. attrs: CoreXform.DateAttrs,
  7295. format: CoreXform.DateFormat
  7296. })
  7297. };
  7298. }
  7299. render(xmlStream, model) {
  7300. xmlStream.openXml(XmlStream.StdDocAttributes);
  7301. xmlStream.openNode('cp:coreProperties', CoreXform.CORE_PROPERTY_ATTRIBUTES);
  7302. this.map['dc:creator'].render(xmlStream, model.creator);
  7303. this.map['dc:title'].render(xmlStream, model.title);
  7304. this.map['dc:subject'].render(xmlStream, model.subject);
  7305. this.map['dc:description'].render(xmlStream, model.description);
  7306. this.map['dc:identifier'].render(xmlStream, model.identifier);
  7307. this.map['dc:language'].render(xmlStream, model.language);
  7308. this.map['cp:keywords'].render(xmlStream, model.keywords);
  7309. this.map['cp:category'].render(xmlStream, model.category);
  7310. this.map['cp:lastModifiedBy'].render(xmlStream, model.lastModifiedBy);
  7311. this.map['cp:lastPrinted'].render(xmlStream, model.lastPrinted);
  7312. this.map['cp:revision'].render(xmlStream, model.revision);
  7313. this.map['cp:version'].render(xmlStream, model.version);
  7314. this.map['cp:contentStatus'].render(xmlStream, model.contentStatus);
  7315. this.map['cp:contentType'].render(xmlStream, model.contentType);
  7316. this.map['dcterms:created'].render(xmlStream, model.created);
  7317. this.map['dcterms:modified'].render(xmlStream, model.modified);
  7318. xmlStream.closeNode();
  7319. }
  7320. parseOpen(node) {
  7321. if (this.parser) {
  7322. this.parser.parseOpen(node);
  7323. return true;
  7324. }
  7325. switch (node.name) {
  7326. case 'cp:coreProperties':
  7327. case 'coreProperties':
  7328. return true;
  7329. default:
  7330. this.parser = this.map[node.name];
  7331. if (this.parser) {
  7332. this.parser.parseOpen(node);
  7333. return true;
  7334. }
  7335. throw new Error(`Unexpected xml node in parseOpen: ${JSON.stringify(node)}`);
  7336. }
  7337. }
  7338. parseText(text) {
  7339. if (this.parser) {
  7340. this.parser.parseText(text);
  7341. }
  7342. }
  7343. parseClose(name) {
  7344. if (this.parser) {
  7345. if (!this.parser.parseClose(name)) {
  7346. this.parser = undefined;
  7347. }
  7348. return true;
  7349. }
  7350. switch (name) {
  7351. case 'cp:coreProperties':
  7352. case 'coreProperties':
  7353. this.model = {
  7354. creator: this.map['dc:creator'].model,
  7355. title: this.map['dc:title'].model,
  7356. subject: this.map['dc:subject'].model,
  7357. description: this.map['dc:description'].model,
  7358. identifier: this.map['dc:identifier'].model,
  7359. language: this.map['dc:language'].model,
  7360. keywords: this.map['cp:keywords'].model,
  7361. category: this.map['cp:category'].model,
  7362. lastModifiedBy: this.map['cp:lastModifiedBy'].model,
  7363. lastPrinted: this.map['cp:lastPrinted'].model,
  7364. revision: this.map['cp:revision'].model,
  7365. contentStatus: this.map['cp:contentStatus'].model,
  7366. contentType: this.map['cp:contentType'].model,
  7367. created: this.map['dcterms:created'].model,
  7368. modified: this.map['dcterms:modified'].model
  7369. };
  7370. return false;
  7371. default:
  7372. throw new Error(`Unexpected xml node in parseClose: ${name}`);
  7373. }
  7374. }
  7375. }
  7376. CoreXform.DateFormat = function (dt) {
  7377. return dt.toISOString().replace(/[.]\d{3}/, '');
  7378. };
  7379. CoreXform.DateAttrs = {
  7380. 'xsi:type': 'dcterms:W3CDTF'
  7381. };
  7382. CoreXform.CORE_PROPERTY_ATTRIBUTES = {
  7383. 'xmlns:cp': 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties',
  7384. 'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
  7385. 'xmlns:dcterms': 'http://purl.org/dc/terms/',
  7386. 'xmlns:dcmitype': 'http://purl.org/dc/dcmitype/',
  7387. 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance'
  7388. };
  7389. module.exports = CoreXform;
  7390. },{"../../../utils/xml-stream":28,"../base-xform":32,"../simple/date-xform":117,"../simple/integer-xform":118,"../simple/string-xform":119}],54:[function(require,module,exports){
  7391. "use strict";
  7392. const BaseXform = require('../base-xform');
  7393. class RelationshipXform extends BaseXform {
  7394. render(xmlStream, model) {
  7395. xmlStream.leafNode('Relationship', model);
  7396. }
  7397. parseOpen(node) {
  7398. switch (node.name) {
  7399. case 'Relationship':
  7400. this.model = node.attributes;
  7401. return true;
  7402. default:
  7403. return false;
  7404. }
  7405. }
  7406. parseText() {}
  7407. parseClose() {
  7408. return false;
  7409. }
  7410. }
  7411. module.exports = RelationshipXform;
  7412. },{"../base-xform":32}],55:[function(require,module,exports){
  7413. "use strict";
  7414. const XmlStream = require('../../../utils/xml-stream');
  7415. const BaseXform = require('../base-xform');
  7416. const RelationshipXform = require('./relationship-xform');
  7417. class RelationshipsXform extends BaseXform {
  7418. constructor() {
  7419. super();
  7420. this.map = {
  7421. Relationship: new RelationshipXform()
  7422. };
  7423. }
  7424. render(xmlStream, model) {
  7425. model = model || this._values;
  7426. xmlStream.openXml(XmlStream.StdDocAttributes);
  7427. xmlStream.openNode('Relationships', RelationshipsXform.RELATIONSHIPS_ATTRIBUTES);
  7428. model.forEach(relationship => {
  7429. this.map.Relationship.render(xmlStream, relationship);
  7430. });
  7431. xmlStream.closeNode();
  7432. }
  7433. parseOpen(node) {
  7434. if (this.parser) {
  7435. this.parser.parseOpen(node);
  7436. return true;
  7437. }
  7438. switch (node.name) {
  7439. case 'Relationships':
  7440. this.model = [];
  7441. return true;
  7442. default:
  7443. this.parser = this.map[node.name];
  7444. if (this.parser) {
  7445. this.parser.parseOpen(node);
  7446. return true;
  7447. }
  7448. throw new Error(`Unexpected xml node in parseOpen: ${JSON.stringify(node)}`);
  7449. }
  7450. }
  7451. parseText(text) {
  7452. if (this.parser) {
  7453. this.parser.parseText(text);
  7454. }
  7455. }
  7456. parseClose(name) {
  7457. if (this.parser) {
  7458. if (!this.parser.parseClose(name)) {
  7459. this.model.push(this.parser.model);
  7460. this.parser = undefined;
  7461. }
  7462. return true;
  7463. }
  7464. switch (name) {
  7465. case 'Relationships':
  7466. return false;
  7467. default:
  7468. throw new Error(`Unexpected xml node in parseClose: ${name}`);
  7469. }
  7470. }
  7471. }
  7472. RelationshipsXform.RELATIONSHIPS_ATTRIBUTES = {
  7473. xmlns: 'http://schemas.openxmlformats.org/package/2006/relationships'
  7474. };
  7475. module.exports = RelationshipsXform;
  7476. },{"../../../utils/xml-stream":28,"../base-xform":32,"./relationship-xform":54}],56:[function(require,module,exports){
  7477. "use strict";
  7478. const BaseXform = require('../base-xform');
  7479. class BaseCellAnchorXform extends BaseXform {
  7480. parseOpen(node) {
  7481. if (this.parser) {
  7482. this.parser.parseOpen(node);
  7483. return true;
  7484. }
  7485. switch (node.name) {
  7486. case this.tag:
  7487. this.reset();
  7488. this.model = {
  7489. range: {
  7490. editAs: node.attributes.editAs || 'oneCell'
  7491. }
  7492. };
  7493. break;
  7494. default:
  7495. this.parser = this.map[node.name];
  7496. if (this.parser) {
  7497. this.parser.parseOpen(node);
  7498. }
  7499. break;
  7500. }
  7501. return true;
  7502. }
  7503. parseText(text) {
  7504. if (this.parser) {
  7505. this.parser.parseText(text);
  7506. }
  7507. }
  7508. reconcilePicture(model, options) {
  7509. if (model && model.rId) {
  7510. const rel = options.rels[model.rId];
  7511. const match = rel.Target.match(/.*\/media\/(.+[.][a-zA-Z]{3,4})/);
  7512. if (match) {
  7513. const name = match[1];
  7514. const mediaId = options.mediaIndex[name];
  7515. return options.media[mediaId];
  7516. }
  7517. }
  7518. return undefined;
  7519. }
  7520. }
  7521. module.exports = BaseCellAnchorXform;
  7522. },{"../base-xform":32}],57:[function(require,module,exports){
  7523. "use strict";
  7524. const BaseXform = require('../base-xform');
  7525. const BlipXform = require('./blip-xform');
  7526. class BlipFillXform extends BaseXform {
  7527. constructor() {
  7528. super();
  7529. this.map = {
  7530. 'a:blip': new BlipXform()
  7531. };
  7532. }
  7533. get tag() {
  7534. return 'xdr:blipFill';
  7535. }
  7536. render(xmlStream, model) {
  7537. xmlStream.openNode(this.tag);
  7538. this.map['a:blip'].render(xmlStream, model);
  7539. // TODO: options for this + parsing
  7540. xmlStream.openNode('a:stretch');
  7541. xmlStream.leafNode('a:fillRect');
  7542. xmlStream.closeNode();
  7543. xmlStream.closeNode();
  7544. }
  7545. parseOpen(node) {
  7546. if (this.parser) {
  7547. this.parser.parseOpen(node);
  7548. return true;
  7549. }
  7550. switch (node.name) {
  7551. case this.tag:
  7552. this.reset();
  7553. break;
  7554. default:
  7555. this.parser = this.map[node.name];
  7556. if (this.parser) {
  7557. this.parser.parseOpen(node);
  7558. }
  7559. break;
  7560. }
  7561. return true;
  7562. }
  7563. parseText() {}
  7564. parseClose(name) {
  7565. if (this.parser) {
  7566. if (!this.parser.parseClose(name)) {
  7567. this.parser = undefined;
  7568. }
  7569. return true;
  7570. }
  7571. switch (name) {
  7572. case this.tag:
  7573. this.model = this.map['a:blip'].model;
  7574. return false;
  7575. default:
  7576. return true;
  7577. }
  7578. }
  7579. }
  7580. module.exports = BlipFillXform;
  7581. },{"../base-xform":32,"./blip-xform":58}],58:[function(require,module,exports){
  7582. "use strict";
  7583. const BaseXform = require('../base-xform');
  7584. class BlipXform extends BaseXform {
  7585. get tag() {
  7586. return 'a:blip';
  7587. }
  7588. render(xmlStream, model) {
  7589. xmlStream.leafNode(this.tag, {
  7590. 'xmlns:r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  7591. 'r:embed': model.rId,
  7592. cstate: 'print'
  7593. });
  7594. // TODO: handle children (e.g. a:extLst=>a:ext=>a14:useLocalDpi
  7595. }
  7596. parseOpen(node) {
  7597. switch (node.name) {
  7598. case this.tag:
  7599. this.model = {
  7600. rId: node.attributes['r:embed']
  7601. };
  7602. return true;
  7603. default:
  7604. return true;
  7605. }
  7606. }
  7607. parseText() {}
  7608. parseClose(name) {
  7609. switch (name) {
  7610. case this.tag:
  7611. return false;
  7612. default:
  7613. // unprocessed internal nodes
  7614. return true;
  7615. }
  7616. }
  7617. }
  7618. module.exports = BlipXform;
  7619. },{"../base-xform":32}],59:[function(require,module,exports){
  7620. "use strict";
  7621. const BaseXform = require('../base-xform');
  7622. class CNvPicPrXform extends BaseXform {
  7623. get tag() {
  7624. return 'xdr:cNvPicPr';
  7625. }
  7626. render(xmlStream) {
  7627. xmlStream.openNode(this.tag);
  7628. xmlStream.leafNode('a:picLocks', {
  7629. noChangeAspect: '1'
  7630. });
  7631. xmlStream.closeNode();
  7632. }
  7633. parseOpen(node) {
  7634. switch (node.name) {
  7635. case this.tag:
  7636. return true;
  7637. default:
  7638. return true;
  7639. }
  7640. }
  7641. parseText() {}
  7642. parseClose(name) {
  7643. switch (name) {
  7644. case this.tag:
  7645. return false;
  7646. default:
  7647. // unprocessed internal nodes
  7648. return true;
  7649. }
  7650. }
  7651. }
  7652. module.exports = CNvPicPrXform;
  7653. },{"../base-xform":32}],60:[function(require,module,exports){
  7654. "use strict";
  7655. const BaseXform = require('../base-xform');
  7656. const HlickClickXform = require('./hlink-click-xform');
  7657. const ExtLstXform = require('./ext-lst-xform');
  7658. class CNvPrXform extends BaseXform {
  7659. constructor() {
  7660. super();
  7661. this.map = {
  7662. 'a:hlinkClick': new HlickClickXform(),
  7663. 'a:extLst': new ExtLstXform()
  7664. };
  7665. }
  7666. get tag() {
  7667. return 'xdr:cNvPr';
  7668. }
  7669. render(xmlStream, model) {
  7670. xmlStream.openNode(this.tag, {
  7671. id: model.index,
  7672. name: `Picture ${model.index}`
  7673. });
  7674. this.map['a:hlinkClick'].render(xmlStream, model);
  7675. this.map['a:extLst'].render(xmlStream, model);
  7676. xmlStream.closeNode();
  7677. }
  7678. parseOpen(node) {
  7679. if (this.parser) {
  7680. this.parser.parseOpen(node);
  7681. return true;
  7682. }
  7683. switch (node.name) {
  7684. case this.tag:
  7685. this.reset();
  7686. break;
  7687. default:
  7688. this.parser = this.map[node.name];
  7689. if (this.parser) {
  7690. this.parser.parseOpen(node);
  7691. }
  7692. break;
  7693. }
  7694. return true;
  7695. }
  7696. parseText() {}
  7697. parseClose(name) {
  7698. if (this.parser) {
  7699. if (!this.parser.parseClose(name)) {
  7700. this.parser = undefined;
  7701. }
  7702. return true;
  7703. }
  7704. switch (name) {
  7705. case this.tag:
  7706. this.model = this.map['a:hlinkClick'].model;
  7707. return false;
  7708. default:
  7709. return true;
  7710. }
  7711. }
  7712. }
  7713. module.exports = CNvPrXform;
  7714. },{"../base-xform":32,"./ext-lst-xform":63,"./hlink-click-xform":65}],61:[function(require,module,exports){
  7715. "use strict";
  7716. const BaseXform = require('../base-xform');
  7717. const IntegerXform = require('../simple/integer-xform');
  7718. class CellPositionXform extends BaseXform {
  7719. constructor(options) {
  7720. super();
  7721. this.tag = options.tag;
  7722. this.map = {
  7723. 'xdr:col': new IntegerXform({
  7724. tag: 'xdr:col',
  7725. zero: true
  7726. }),
  7727. 'xdr:colOff': new IntegerXform({
  7728. tag: 'xdr:colOff',
  7729. zero: true
  7730. }),
  7731. 'xdr:row': new IntegerXform({
  7732. tag: 'xdr:row',
  7733. zero: true
  7734. }),
  7735. 'xdr:rowOff': new IntegerXform({
  7736. tag: 'xdr:rowOff',
  7737. zero: true
  7738. })
  7739. };
  7740. }
  7741. render(xmlStream, model) {
  7742. xmlStream.openNode(this.tag);
  7743. this.map['xdr:col'].render(xmlStream, model.nativeCol);
  7744. this.map['xdr:colOff'].render(xmlStream, model.nativeColOff);
  7745. this.map['xdr:row'].render(xmlStream, model.nativeRow);
  7746. this.map['xdr:rowOff'].render(xmlStream, model.nativeRowOff);
  7747. xmlStream.closeNode();
  7748. }
  7749. parseOpen(node) {
  7750. if (this.parser) {
  7751. this.parser.parseOpen(node);
  7752. return true;
  7753. }
  7754. switch (node.name) {
  7755. case this.tag:
  7756. this.reset();
  7757. break;
  7758. default:
  7759. this.parser = this.map[node.name];
  7760. if (this.parser) {
  7761. this.parser.parseOpen(node);
  7762. }
  7763. break;
  7764. }
  7765. return true;
  7766. }
  7767. parseText(text) {
  7768. if (this.parser) {
  7769. this.parser.parseText(text);
  7770. }
  7771. }
  7772. parseClose(name) {
  7773. if (this.parser) {
  7774. if (!this.parser.parseClose(name)) {
  7775. this.parser = undefined;
  7776. }
  7777. return true;
  7778. }
  7779. switch (name) {
  7780. case this.tag:
  7781. this.model = {
  7782. nativeCol: this.map['xdr:col'].model,
  7783. nativeColOff: this.map['xdr:colOff'].model,
  7784. nativeRow: this.map['xdr:row'].model,
  7785. nativeRowOff: this.map['xdr:rowOff'].model
  7786. };
  7787. return false;
  7788. default:
  7789. // not quite sure how we get here!
  7790. return true;
  7791. }
  7792. }
  7793. }
  7794. module.exports = CellPositionXform;
  7795. },{"../base-xform":32,"../simple/integer-xform":118}],62:[function(require,module,exports){
  7796. "use strict";
  7797. const colCache = require('../../../utils/col-cache');
  7798. const XmlStream = require('../../../utils/xml-stream');
  7799. const BaseXform = require('../base-xform');
  7800. const TwoCellAnchorXform = require('./two-cell-anchor-xform');
  7801. const OneCellAnchorXform = require('./one-cell-anchor-xform');
  7802. function getAnchorType(model) {
  7803. const range = typeof model.range === 'string' ? colCache.decode(model.range) : model.range;
  7804. return range.br ? 'xdr:twoCellAnchor' : 'xdr:oneCellAnchor';
  7805. }
  7806. class DrawingXform extends BaseXform {
  7807. constructor() {
  7808. super();
  7809. this.map = {
  7810. 'xdr:twoCellAnchor': new TwoCellAnchorXform(),
  7811. 'xdr:oneCellAnchor': new OneCellAnchorXform()
  7812. };
  7813. }
  7814. prepare(model) {
  7815. model.anchors.forEach((item, index) => {
  7816. item.anchorType = getAnchorType(item);
  7817. const anchor = this.map[item.anchorType];
  7818. anchor.prepare(item, {
  7819. index
  7820. });
  7821. });
  7822. }
  7823. get tag() {
  7824. return 'xdr:wsDr';
  7825. }
  7826. render(xmlStream, model) {
  7827. xmlStream.openXml(XmlStream.StdDocAttributes);
  7828. xmlStream.openNode(this.tag, DrawingXform.DRAWING_ATTRIBUTES);
  7829. model.anchors.forEach(item => {
  7830. const anchor = this.map[item.anchorType];
  7831. anchor.render(xmlStream, item);
  7832. });
  7833. xmlStream.closeNode();
  7834. }
  7835. parseOpen(node) {
  7836. if (this.parser) {
  7837. this.parser.parseOpen(node);
  7838. return true;
  7839. }
  7840. switch (node.name) {
  7841. case this.tag:
  7842. this.reset();
  7843. this.model = {
  7844. anchors: []
  7845. };
  7846. break;
  7847. default:
  7848. this.parser = this.map[node.name];
  7849. if (this.parser) {
  7850. this.parser.parseOpen(node);
  7851. }
  7852. break;
  7853. }
  7854. return true;
  7855. }
  7856. parseText(text) {
  7857. if (this.parser) {
  7858. this.parser.parseText(text);
  7859. }
  7860. }
  7861. parseClose(name) {
  7862. if (this.parser) {
  7863. if (!this.parser.parseClose(name)) {
  7864. this.model.anchors.push(this.parser.model);
  7865. this.parser = undefined;
  7866. }
  7867. return true;
  7868. }
  7869. switch (name) {
  7870. case this.tag:
  7871. return false;
  7872. default:
  7873. // could be some unrecognised tags
  7874. return true;
  7875. }
  7876. }
  7877. reconcile(model, options) {
  7878. model.anchors.forEach(anchor => {
  7879. if (anchor.br) {
  7880. this.map['xdr:twoCellAnchor'].reconcile(anchor, options);
  7881. } else {
  7882. this.map['xdr:oneCellAnchor'].reconcile(anchor, options);
  7883. }
  7884. });
  7885. }
  7886. }
  7887. DrawingXform.DRAWING_ATTRIBUTES = {
  7888. 'xmlns:xdr': 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing',
  7889. 'xmlns:a': 'http://schemas.openxmlformats.org/drawingml/2006/main'
  7890. };
  7891. module.exports = DrawingXform;
  7892. },{"../../../utils/col-cache":19,"../../../utils/xml-stream":28,"../base-xform":32,"./one-cell-anchor-xform":67,"./two-cell-anchor-xform":70}],63:[function(require,module,exports){
  7893. "use strict";
  7894. const BaseXform = require('../base-xform');
  7895. class ExtLstXform extends BaseXform {
  7896. get tag() {
  7897. return 'a:extLst';
  7898. }
  7899. render(xmlStream) {
  7900. xmlStream.openNode(this.tag);
  7901. xmlStream.openNode('a:ext', {
  7902. uri: '{FF2B5EF4-FFF2-40B4-BE49-F238E27FC236}'
  7903. });
  7904. xmlStream.leafNode('a16:creationId', {
  7905. 'xmlns:a16': 'http://schemas.microsoft.com/office/drawing/2014/main',
  7906. id: '{00000000-0008-0000-0000-000002000000}'
  7907. });
  7908. xmlStream.closeNode();
  7909. xmlStream.closeNode();
  7910. }
  7911. parseOpen(node) {
  7912. switch (node.name) {
  7913. case this.tag:
  7914. return true;
  7915. default:
  7916. return true;
  7917. }
  7918. }
  7919. parseText() {}
  7920. parseClose(name) {
  7921. switch (name) {
  7922. case this.tag:
  7923. return false;
  7924. default:
  7925. // unprocessed internal nodes
  7926. return true;
  7927. }
  7928. }
  7929. }
  7930. module.exports = ExtLstXform;
  7931. },{"../base-xform":32}],64:[function(require,module,exports){
  7932. "use strict";
  7933. const BaseXform = require('../base-xform');
  7934. /** https://en.wikipedia.org/wiki/Office_Open_XML_file_formats#DrawingML */
  7935. const EMU_PER_PIXEL_AT_96_DPI = 9525;
  7936. class ExtXform extends BaseXform {
  7937. constructor(options) {
  7938. super();
  7939. this.tag = options.tag;
  7940. this.map = {};
  7941. }
  7942. render(xmlStream, model) {
  7943. xmlStream.openNode(this.tag);
  7944. const width = Math.floor(model.width * EMU_PER_PIXEL_AT_96_DPI);
  7945. const height = Math.floor(model.height * EMU_PER_PIXEL_AT_96_DPI);
  7946. xmlStream.addAttribute('cx', width);
  7947. xmlStream.addAttribute('cy', height);
  7948. xmlStream.closeNode();
  7949. }
  7950. parseOpen(node) {
  7951. if (node.name === this.tag) {
  7952. this.model = {
  7953. width: parseInt(node.attributes.cx || '0', 10) / EMU_PER_PIXEL_AT_96_DPI,
  7954. height: parseInt(node.attributes.cy || '0', 10) / EMU_PER_PIXEL_AT_96_DPI
  7955. };
  7956. return true;
  7957. }
  7958. return false;
  7959. }
  7960. parseText( /* text */) {}
  7961. parseClose( /* name */
  7962. ) {
  7963. return false;
  7964. }
  7965. }
  7966. module.exports = ExtXform;
  7967. },{"../base-xform":32}],65:[function(require,module,exports){
  7968. "use strict";
  7969. const BaseXform = require('../base-xform');
  7970. class HLinkClickXform extends BaseXform {
  7971. get tag() {
  7972. return 'a:hlinkClick';
  7973. }
  7974. render(xmlStream, model) {
  7975. if (!(model.hyperlinks && model.hyperlinks.rId)) {
  7976. return;
  7977. }
  7978. xmlStream.leafNode(this.tag, {
  7979. 'xmlns:r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  7980. 'r:id': model.hyperlinks.rId,
  7981. tooltip: model.hyperlinks.tooltip
  7982. });
  7983. }
  7984. parseOpen(node) {
  7985. switch (node.name) {
  7986. case this.tag:
  7987. this.model = {
  7988. hyperlinks: {
  7989. rId: node.attributes['r:id'],
  7990. tooltip: node.attributes.tooltip
  7991. }
  7992. };
  7993. return true;
  7994. default:
  7995. return true;
  7996. }
  7997. }
  7998. parseText() {}
  7999. parseClose() {
  8000. return false;
  8001. }
  8002. }
  8003. module.exports = HLinkClickXform;
  8004. },{"../base-xform":32}],66:[function(require,module,exports){
  8005. "use strict";
  8006. const BaseXform = require('../base-xform');
  8007. const CNvPrXform = require('./c-nv-pr-xform');
  8008. const CNvPicPrXform = require('./c-nv-pic-pr-xform');
  8009. class NvPicPrXform extends BaseXform {
  8010. constructor() {
  8011. super();
  8012. this.map = {
  8013. 'xdr:cNvPr': new CNvPrXform(),
  8014. 'xdr:cNvPicPr': new CNvPicPrXform()
  8015. };
  8016. }
  8017. get tag() {
  8018. return 'xdr:nvPicPr';
  8019. }
  8020. render(xmlStream, model) {
  8021. xmlStream.openNode(this.tag);
  8022. this.map['xdr:cNvPr'].render(xmlStream, model);
  8023. this.map['xdr:cNvPicPr'].render(xmlStream, model);
  8024. xmlStream.closeNode();
  8025. }
  8026. parseOpen(node) {
  8027. if (this.parser) {
  8028. this.parser.parseOpen(node);
  8029. return true;
  8030. }
  8031. switch (node.name) {
  8032. case this.tag:
  8033. this.reset();
  8034. break;
  8035. default:
  8036. this.parser = this.map[node.name];
  8037. if (this.parser) {
  8038. this.parser.parseOpen(node);
  8039. }
  8040. break;
  8041. }
  8042. return true;
  8043. }
  8044. parseText() {}
  8045. parseClose(name) {
  8046. if (this.parser) {
  8047. if (!this.parser.parseClose(name)) {
  8048. this.parser = undefined;
  8049. }
  8050. return true;
  8051. }
  8052. switch (name) {
  8053. case this.tag:
  8054. this.model = this.map['xdr:cNvPr'].model;
  8055. return false;
  8056. default:
  8057. return true;
  8058. }
  8059. }
  8060. }
  8061. module.exports = NvPicPrXform;
  8062. },{"../base-xform":32,"./c-nv-pic-pr-xform":59,"./c-nv-pr-xform":60}],67:[function(require,module,exports){
  8063. "use strict";
  8064. const BaseCellAnchorXform = require('./base-cell-anchor-xform');
  8065. const StaticXform = require('../static-xform');
  8066. const CellPositionXform = require('./cell-position-xform');
  8067. const ExtXform = require('./ext-xform');
  8068. const PicXform = require('./pic-xform');
  8069. class OneCellAnchorXform extends BaseCellAnchorXform {
  8070. constructor() {
  8071. super();
  8072. this.map = {
  8073. 'xdr:from': new CellPositionXform({
  8074. tag: 'xdr:from'
  8075. }),
  8076. 'xdr:ext': new ExtXform({
  8077. tag: 'xdr:ext'
  8078. }),
  8079. 'xdr:pic': new PicXform(),
  8080. 'xdr:clientData': new StaticXform({
  8081. tag: 'xdr:clientData'
  8082. })
  8083. };
  8084. }
  8085. get tag() {
  8086. return 'xdr:oneCellAnchor';
  8087. }
  8088. prepare(model, options) {
  8089. this.map['xdr:pic'].prepare(model.picture, options);
  8090. }
  8091. render(xmlStream, model) {
  8092. xmlStream.openNode(this.tag, {
  8093. editAs: model.range.editAs || 'oneCell'
  8094. });
  8095. this.map['xdr:from'].render(xmlStream, model.range.tl);
  8096. this.map['xdr:ext'].render(xmlStream, model.range.ext);
  8097. this.map['xdr:pic'].render(xmlStream, model.picture);
  8098. this.map['xdr:clientData'].render(xmlStream, {});
  8099. xmlStream.closeNode();
  8100. }
  8101. parseClose(name) {
  8102. if (this.parser) {
  8103. if (!this.parser.parseClose(name)) {
  8104. this.parser = undefined;
  8105. }
  8106. return true;
  8107. }
  8108. switch (name) {
  8109. case this.tag:
  8110. this.model.range.tl = this.map['xdr:from'].model;
  8111. this.model.range.ext = this.map['xdr:ext'].model;
  8112. this.model.picture = this.map['xdr:pic'].model;
  8113. return false;
  8114. default:
  8115. // could be some unrecognised tags
  8116. return true;
  8117. }
  8118. }
  8119. reconcile(model, options) {
  8120. model.medium = this.reconcilePicture(model.picture, options);
  8121. }
  8122. }
  8123. module.exports = OneCellAnchorXform;
  8124. },{"../static-xform":120,"./base-cell-anchor-xform":56,"./cell-position-xform":61,"./ext-xform":64,"./pic-xform":68}],68:[function(require,module,exports){
  8125. "use strict";
  8126. const BaseXform = require('../base-xform');
  8127. const StaticXform = require('../static-xform');
  8128. const BlipFillXform = require('./blip-fill-xform');
  8129. const NvPicPrXform = require('./nv-pic-pr-xform');
  8130. const spPrJSON = require('./sp-pr');
  8131. class PicXform extends BaseXform {
  8132. constructor() {
  8133. super();
  8134. this.map = {
  8135. 'xdr:nvPicPr': new NvPicPrXform(),
  8136. 'xdr:blipFill': new BlipFillXform(),
  8137. 'xdr:spPr': new StaticXform(spPrJSON)
  8138. };
  8139. }
  8140. get tag() {
  8141. return 'xdr:pic';
  8142. }
  8143. prepare(model, options) {
  8144. model.index = options.index + 1;
  8145. }
  8146. render(xmlStream, model) {
  8147. xmlStream.openNode(this.tag);
  8148. this.map['xdr:nvPicPr'].render(xmlStream, model);
  8149. this.map['xdr:blipFill'].render(xmlStream, model);
  8150. this.map['xdr:spPr'].render(xmlStream, model);
  8151. xmlStream.closeNode();
  8152. }
  8153. parseOpen(node) {
  8154. if (this.parser) {
  8155. this.parser.parseOpen(node);
  8156. return true;
  8157. }
  8158. switch (node.name) {
  8159. case this.tag:
  8160. this.reset();
  8161. break;
  8162. default:
  8163. this.parser = this.map[node.name];
  8164. if (this.parser) {
  8165. this.parser.parseOpen(node);
  8166. }
  8167. break;
  8168. }
  8169. return true;
  8170. }
  8171. parseText() {}
  8172. parseClose(name) {
  8173. if (this.parser) {
  8174. if (!this.parser.parseClose(name)) {
  8175. this.mergeModel(this.parser.model);
  8176. this.parser = undefined;
  8177. }
  8178. return true;
  8179. }
  8180. switch (name) {
  8181. case this.tag:
  8182. return false;
  8183. default:
  8184. // not quite sure how we get here!
  8185. return true;
  8186. }
  8187. }
  8188. }
  8189. module.exports = PicXform;
  8190. },{"../base-xform":32,"../static-xform":120,"./blip-fill-xform":57,"./nv-pic-pr-xform":66,"./sp-pr":69}],69:[function(require,module,exports){
  8191. "use strict";
  8192. module.exports = {
  8193. tag: 'xdr:spPr',
  8194. c: [{
  8195. tag: 'a:xfrm',
  8196. c: [{
  8197. tag: 'a:off',
  8198. $: {
  8199. x: '0',
  8200. y: '0'
  8201. }
  8202. }, {
  8203. tag: 'a:ext',
  8204. $: {
  8205. cx: '0',
  8206. cy: '0'
  8207. }
  8208. }]
  8209. }, {
  8210. tag: 'a:prstGeom',
  8211. $: {
  8212. prst: 'rect'
  8213. },
  8214. c: [{
  8215. tag: 'a:avLst'
  8216. }]
  8217. }]
  8218. };
  8219. },{}],70:[function(require,module,exports){
  8220. "use strict";
  8221. const BaseCellAnchorXform = require('./base-cell-anchor-xform');
  8222. const StaticXform = require('../static-xform');
  8223. const CellPositionXform = require('./cell-position-xform');
  8224. const PicXform = require('./pic-xform');
  8225. class TwoCellAnchorXform extends BaseCellAnchorXform {
  8226. constructor() {
  8227. super();
  8228. this.map = {
  8229. 'xdr:from': new CellPositionXform({
  8230. tag: 'xdr:from'
  8231. }),
  8232. 'xdr:to': new CellPositionXform({
  8233. tag: 'xdr:to'
  8234. }),
  8235. 'xdr:pic': new PicXform(),
  8236. 'xdr:clientData': new StaticXform({
  8237. tag: 'xdr:clientData'
  8238. })
  8239. };
  8240. }
  8241. get tag() {
  8242. return 'xdr:twoCellAnchor';
  8243. }
  8244. prepare(model, options) {
  8245. this.map['xdr:pic'].prepare(model.picture, options);
  8246. }
  8247. render(xmlStream, model) {
  8248. xmlStream.openNode(this.tag, {
  8249. editAs: model.range.editAs || 'oneCell'
  8250. });
  8251. this.map['xdr:from'].render(xmlStream, model.range.tl);
  8252. this.map['xdr:to'].render(xmlStream, model.range.br);
  8253. this.map['xdr:pic'].render(xmlStream, model.picture);
  8254. this.map['xdr:clientData'].render(xmlStream, {});
  8255. xmlStream.closeNode();
  8256. }
  8257. parseClose(name) {
  8258. if (this.parser) {
  8259. if (!this.parser.parseClose(name)) {
  8260. this.parser = undefined;
  8261. }
  8262. return true;
  8263. }
  8264. switch (name) {
  8265. case this.tag:
  8266. this.model.range.tl = this.map['xdr:from'].model;
  8267. this.model.range.br = this.map['xdr:to'].model;
  8268. this.model.picture = this.map['xdr:pic'].model;
  8269. return false;
  8270. default:
  8271. // could be some unrecognised tags
  8272. return true;
  8273. }
  8274. }
  8275. reconcile(model, options) {
  8276. model.medium = this.reconcilePicture(model.picture, options);
  8277. }
  8278. }
  8279. module.exports = TwoCellAnchorXform;
  8280. },{"../static-xform":120,"./base-cell-anchor-xform":56,"./cell-position-xform":61,"./pic-xform":68}],71:[function(require,module,exports){
  8281. "use strict";
  8282. const BaseXform = require('./base-xform');
  8283. class ListXform extends BaseXform {
  8284. constructor(options) {
  8285. super();
  8286. this.tag = options.tag;
  8287. this.always = !!options.always;
  8288. this.count = options.count;
  8289. this.empty = options.empty;
  8290. this.$count = options.$count || 'count';
  8291. this.$ = options.$;
  8292. this.childXform = options.childXform;
  8293. this.maxItems = options.maxItems;
  8294. }
  8295. prepare(model, options) {
  8296. const {
  8297. childXform
  8298. } = this;
  8299. if (model) {
  8300. model.forEach((childModel, index) => {
  8301. options.index = index;
  8302. childXform.prepare(childModel, options);
  8303. });
  8304. }
  8305. }
  8306. render(xmlStream, model) {
  8307. if (this.always || model && model.length) {
  8308. xmlStream.openNode(this.tag, this.$);
  8309. if (this.count) {
  8310. xmlStream.addAttribute(this.$count, model && model.length || 0);
  8311. }
  8312. const {
  8313. childXform
  8314. } = this;
  8315. (model || []).forEach((childModel, index) => {
  8316. childXform.render(xmlStream, childModel, index);
  8317. });
  8318. xmlStream.closeNode();
  8319. } else if (this.empty) {
  8320. xmlStream.leafNode(this.tag);
  8321. }
  8322. }
  8323. parseOpen(node) {
  8324. if (this.parser) {
  8325. this.parser.parseOpen(node);
  8326. return true;
  8327. }
  8328. switch (node.name) {
  8329. case this.tag:
  8330. this.model = [];
  8331. return true;
  8332. default:
  8333. if (this.childXform.parseOpen(node)) {
  8334. this.parser = this.childXform;
  8335. return true;
  8336. }
  8337. return false;
  8338. }
  8339. }
  8340. parseText(text) {
  8341. if (this.parser) {
  8342. this.parser.parseText(text);
  8343. }
  8344. }
  8345. parseClose(name) {
  8346. if (this.parser) {
  8347. if (!this.parser.parseClose(name)) {
  8348. this.model.push(this.parser.model);
  8349. this.parser = undefined;
  8350. if (this.maxItems && this.model.length > this.maxItems) {
  8351. throw new Error(`Max ${this.childXform.tag} count (${this.maxItems}) exceeded`);
  8352. }
  8353. }
  8354. return true;
  8355. }
  8356. return false;
  8357. }
  8358. reconcile(model, options) {
  8359. if (model) {
  8360. const {
  8361. childXform
  8362. } = this;
  8363. model.forEach(childModel => {
  8364. childXform.reconcile(childModel, options);
  8365. });
  8366. }
  8367. }
  8368. }
  8369. module.exports = ListXform;
  8370. },{"./base-xform":32}],72:[function(require,module,exports){
  8371. "use strict";
  8372. const colCache = require('../../../utils/col-cache');
  8373. const BaseXform = require('../base-xform');
  8374. class AutoFilterXform extends BaseXform {
  8375. get tag() {
  8376. return 'autoFilter';
  8377. }
  8378. render(xmlStream, model) {
  8379. if (model) {
  8380. if (typeof model === 'string') {
  8381. // assume range
  8382. xmlStream.leafNode('autoFilter', {
  8383. ref: model
  8384. });
  8385. } else {
  8386. const getAddress = function (addr) {
  8387. if (typeof addr === 'string') {
  8388. return addr;
  8389. }
  8390. return colCache.getAddress(addr.row, addr.column).address;
  8391. };
  8392. const firstAddress = getAddress(model.from);
  8393. const secondAddress = getAddress(model.to);
  8394. if (firstAddress && secondAddress) {
  8395. xmlStream.leafNode('autoFilter', {
  8396. ref: `${firstAddress}:${secondAddress}`
  8397. });
  8398. }
  8399. }
  8400. }
  8401. }
  8402. parseOpen(node) {
  8403. if (node.name === 'autoFilter') {
  8404. this.model = node.attributes.ref;
  8405. }
  8406. }
  8407. }
  8408. module.exports = AutoFilterXform;
  8409. },{"../../../utils/col-cache":19,"../base-xform":32}],73:[function(require,module,exports){
  8410. "use strict";
  8411. const utils = require('../../../utils/utils');
  8412. const BaseXform = require('../base-xform');
  8413. const Range = require('../../../doc/range');
  8414. const Enums = require('../../../doc/enums');
  8415. const RichTextXform = require('../strings/rich-text-xform');
  8416. function getValueType(v) {
  8417. if (v === null || v === undefined) {
  8418. return Enums.ValueType.Null;
  8419. }
  8420. if (v instanceof String || typeof v === 'string') {
  8421. return Enums.ValueType.String;
  8422. }
  8423. if (typeof v === 'number') {
  8424. return Enums.ValueType.Number;
  8425. }
  8426. if (typeof v === 'boolean') {
  8427. return Enums.ValueType.Boolean;
  8428. }
  8429. if (v instanceof Date) {
  8430. return Enums.ValueType.Date;
  8431. }
  8432. if (v.text && v.hyperlink) {
  8433. return Enums.ValueType.Hyperlink;
  8434. }
  8435. if (v.formula) {
  8436. return Enums.ValueType.Formula;
  8437. }
  8438. if (v.error) {
  8439. return Enums.ValueType.Error;
  8440. }
  8441. throw new Error('I could not understand type of value');
  8442. }
  8443. function getEffectiveCellType(cell) {
  8444. switch (cell.type) {
  8445. case Enums.ValueType.Formula:
  8446. return getValueType(cell.result);
  8447. default:
  8448. return cell.type;
  8449. }
  8450. }
  8451. class CellXform extends BaseXform {
  8452. constructor() {
  8453. super();
  8454. this.richTextXForm = new RichTextXform();
  8455. }
  8456. get tag() {
  8457. return 'c';
  8458. }
  8459. prepare(model, options) {
  8460. const styleId = options.styles.addStyleModel(model.style || {}, getEffectiveCellType(model));
  8461. if (styleId) {
  8462. model.styleId = styleId;
  8463. }
  8464. if (model.comment) {
  8465. options.comments.push({
  8466. ...model.comment,
  8467. ref: model.address
  8468. });
  8469. }
  8470. switch (model.type) {
  8471. case Enums.ValueType.String:
  8472. case Enums.ValueType.RichText:
  8473. if (options.sharedStrings) {
  8474. model.ssId = options.sharedStrings.add(model.value);
  8475. }
  8476. break;
  8477. case Enums.ValueType.Date:
  8478. if (options.date1904) {
  8479. model.date1904 = true;
  8480. }
  8481. break;
  8482. case Enums.ValueType.Hyperlink:
  8483. if (options.sharedStrings && model.text !== undefined && model.text !== null) {
  8484. model.ssId = options.sharedStrings.add(model.text);
  8485. }
  8486. options.hyperlinks.push({
  8487. address: model.address,
  8488. target: model.hyperlink,
  8489. tooltip: model.tooltip
  8490. });
  8491. break;
  8492. case Enums.ValueType.Merge:
  8493. options.merges.add(model);
  8494. break;
  8495. case Enums.ValueType.Formula:
  8496. if (options.date1904) {
  8497. // in case valueType is date
  8498. model.date1904 = true;
  8499. }
  8500. if (model.shareType === 'shared') {
  8501. model.si = options.siFormulae++;
  8502. }
  8503. if (model.formula) {
  8504. options.formulae[model.address] = model;
  8505. } else if (model.sharedFormula) {
  8506. const master = options.formulae[model.sharedFormula];
  8507. if (!master) {
  8508. throw new Error(`Shared Formula master must exist above and or left of clone for cell ${model.address}`);
  8509. }
  8510. if (master.si === undefined) {
  8511. master.shareType = 'shared';
  8512. master.si = options.siFormulae++;
  8513. master.range = new Range(master.address, model.address);
  8514. } else if (master.range) {
  8515. master.range.expandToAddress(model.address);
  8516. }
  8517. model.si = master.si;
  8518. }
  8519. break;
  8520. default:
  8521. break;
  8522. }
  8523. }
  8524. renderFormula(xmlStream, model) {
  8525. let attrs = null;
  8526. switch (model.shareType) {
  8527. case 'shared':
  8528. attrs = {
  8529. t: 'shared',
  8530. ref: model.ref || model.range.range,
  8531. si: model.si
  8532. };
  8533. break;
  8534. case 'array':
  8535. attrs = {
  8536. t: 'array',
  8537. ref: model.ref
  8538. };
  8539. break;
  8540. default:
  8541. if (model.si !== undefined) {
  8542. attrs = {
  8543. t: 'shared',
  8544. si: model.si
  8545. };
  8546. }
  8547. break;
  8548. }
  8549. switch (getValueType(model.result)) {
  8550. case Enums.ValueType.Null:
  8551. // ?
  8552. xmlStream.leafNode('f', attrs, model.formula);
  8553. break;
  8554. case Enums.ValueType.String:
  8555. // oddly, formula results don't ever use shared strings
  8556. xmlStream.addAttribute('t', 'str');
  8557. xmlStream.leafNode('f', attrs, model.formula);
  8558. xmlStream.leafNode('v', null, model.result);
  8559. break;
  8560. case Enums.ValueType.Number:
  8561. xmlStream.leafNode('f', attrs, model.formula);
  8562. xmlStream.leafNode('v', null, model.result);
  8563. break;
  8564. case Enums.ValueType.Boolean:
  8565. xmlStream.addAttribute('t', 'b');
  8566. xmlStream.leafNode('f', attrs, model.formula);
  8567. xmlStream.leafNode('v', null, model.result ? 1 : 0);
  8568. break;
  8569. case Enums.ValueType.Error:
  8570. xmlStream.addAttribute('t', 'e');
  8571. xmlStream.leafNode('f', attrs, model.formula);
  8572. xmlStream.leafNode('v', null, model.result.error);
  8573. break;
  8574. case Enums.ValueType.Date:
  8575. xmlStream.leafNode('f', attrs, model.formula);
  8576. xmlStream.leafNode('v', null, utils.dateToExcel(model.result, model.date1904));
  8577. break;
  8578. // case Enums.ValueType.Hyperlink: // ??
  8579. // case Enums.ValueType.Formula:
  8580. default:
  8581. throw new Error('I could not understand type of value');
  8582. }
  8583. }
  8584. render(xmlStream, model) {
  8585. if (model.type === Enums.ValueType.Null && !model.styleId) {
  8586. // if null and no style, exit
  8587. return;
  8588. }
  8589. xmlStream.openNode('c');
  8590. xmlStream.addAttribute('r', model.address);
  8591. if (model.styleId) {
  8592. xmlStream.addAttribute('s', model.styleId);
  8593. }
  8594. switch (model.type) {
  8595. case Enums.ValueType.Null:
  8596. break;
  8597. case Enums.ValueType.Number:
  8598. xmlStream.leafNode('v', null, model.value);
  8599. break;
  8600. case Enums.ValueType.Boolean:
  8601. xmlStream.addAttribute('t', 'b');
  8602. xmlStream.leafNode('v', null, model.value ? '1' : '0');
  8603. break;
  8604. case Enums.ValueType.Error:
  8605. xmlStream.addAttribute('t', 'e');
  8606. xmlStream.leafNode('v', null, model.value.error);
  8607. break;
  8608. case Enums.ValueType.String:
  8609. case Enums.ValueType.RichText:
  8610. if (model.ssId !== undefined) {
  8611. xmlStream.addAttribute('t', 's');
  8612. xmlStream.leafNode('v', null, model.ssId);
  8613. } else if (model.value && model.value.richText) {
  8614. xmlStream.addAttribute('t', 'inlineStr');
  8615. xmlStream.openNode('is');
  8616. model.value.richText.forEach(text => {
  8617. this.richTextXForm.render(xmlStream, text);
  8618. });
  8619. xmlStream.closeNode('is');
  8620. } else {
  8621. xmlStream.addAttribute('t', 'str');
  8622. xmlStream.leafNode('v', null, model.value);
  8623. }
  8624. break;
  8625. case Enums.ValueType.Date:
  8626. xmlStream.leafNode('v', null, utils.dateToExcel(model.value, model.date1904));
  8627. break;
  8628. case Enums.ValueType.Hyperlink:
  8629. if (model.ssId !== undefined) {
  8630. xmlStream.addAttribute('t', 's');
  8631. xmlStream.leafNode('v', null, model.ssId);
  8632. } else {
  8633. xmlStream.addAttribute('t', 'str');
  8634. xmlStream.leafNode('v', null, model.text);
  8635. }
  8636. break;
  8637. case Enums.ValueType.Formula:
  8638. this.renderFormula(xmlStream, model);
  8639. break;
  8640. case Enums.ValueType.Merge:
  8641. // nothing to add
  8642. break;
  8643. default:
  8644. break;
  8645. }
  8646. xmlStream.closeNode(); // </c>
  8647. }
  8648. parseOpen(node) {
  8649. if (this.parser) {
  8650. this.parser.parseOpen(node);
  8651. return true;
  8652. }
  8653. switch (node.name) {
  8654. case 'c':
  8655. // const address = colCache.decodeAddress(node.attributes.r);
  8656. this.model = {
  8657. address: node.attributes.r
  8658. };
  8659. this.t = node.attributes.t;
  8660. if (node.attributes.s) {
  8661. this.model.styleId = parseInt(node.attributes.s, 10);
  8662. }
  8663. return true;
  8664. case 'f':
  8665. this.currentNode = 'f';
  8666. this.model.si = node.attributes.si;
  8667. this.model.shareType = node.attributes.t;
  8668. this.model.ref = node.attributes.ref;
  8669. return true;
  8670. case 'v':
  8671. this.currentNode = 'v';
  8672. return true;
  8673. case 't':
  8674. this.currentNode = 't';
  8675. return true;
  8676. case 'r':
  8677. this.parser = this.richTextXForm;
  8678. this.parser.parseOpen(node);
  8679. return true;
  8680. default:
  8681. return false;
  8682. }
  8683. }
  8684. parseText(text) {
  8685. if (this.parser) {
  8686. this.parser.parseText(text);
  8687. return;
  8688. }
  8689. switch (this.currentNode) {
  8690. case 'f':
  8691. this.model.formula = this.model.formula ? this.model.formula + text : text;
  8692. break;
  8693. case 'v':
  8694. case 't':
  8695. if (this.model.value && this.model.value.richText) {
  8696. this.model.value.richText.text = this.model.value.richText.text ? this.model.value.richText.text + text : text;
  8697. } else {
  8698. this.model.value = this.model.value ? this.model.value + text : text;
  8699. }
  8700. break;
  8701. default:
  8702. break;
  8703. }
  8704. }
  8705. parseClose(name) {
  8706. switch (name) {
  8707. case 'c':
  8708. {
  8709. const {
  8710. model
  8711. } = this;
  8712. // first guess on cell type
  8713. if (model.formula || model.shareType) {
  8714. model.type = Enums.ValueType.Formula;
  8715. if (model.value) {
  8716. if (this.t === 'str') {
  8717. model.result = utils.xmlDecode(model.value);
  8718. } else if (this.t === 'b') {
  8719. model.result = parseInt(model.value, 10) !== 0;
  8720. } else if (this.t === 'e') {
  8721. model.result = {
  8722. error: model.value
  8723. };
  8724. } else {
  8725. model.result = parseFloat(model.value);
  8726. }
  8727. model.value = undefined;
  8728. }
  8729. } else if (model.value !== undefined) {
  8730. switch (this.t) {
  8731. case 's':
  8732. model.type = Enums.ValueType.String;
  8733. model.value = parseInt(model.value, 10);
  8734. break;
  8735. case 'str':
  8736. model.type = Enums.ValueType.String;
  8737. model.value = utils.xmlDecode(model.value);
  8738. break;
  8739. case 'inlineStr':
  8740. model.type = Enums.ValueType.String;
  8741. break;
  8742. case 'b':
  8743. model.type = Enums.ValueType.Boolean;
  8744. model.value = parseInt(model.value, 10) !== 0;
  8745. break;
  8746. case 'e':
  8747. model.type = Enums.ValueType.Error;
  8748. model.value = {
  8749. error: model.value
  8750. };
  8751. break;
  8752. default:
  8753. model.type = Enums.ValueType.Number;
  8754. model.value = parseFloat(model.value);
  8755. break;
  8756. }
  8757. } else if (model.styleId) {
  8758. model.type = Enums.ValueType.Null;
  8759. } else {
  8760. model.type = Enums.ValueType.Merge;
  8761. }
  8762. return false;
  8763. }
  8764. case 'f':
  8765. case 'v':
  8766. case 'is':
  8767. this.currentNode = undefined;
  8768. return true;
  8769. case 't':
  8770. if (this.parser) {
  8771. this.parser.parseClose(name);
  8772. return true;
  8773. }
  8774. this.currentNode = undefined;
  8775. return true;
  8776. case 'r':
  8777. this.model.value = this.model.value || {};
  8778. this.model.value.richText = this.model.value.richText || [];
  8779. this.model.value.richText.push(this.parser.model);
  8780. this.parser = undefined;
  8781. this.currentNode = undefined;
  8782. return true;
  8783. default:
  8784. if (this.parser) {
  8785. this.parser.parseClose(name);
  8786. return true;
  8787. }
  8788. return false;
  8789. }
  8790. }
  8791. reconcile(model, options) {
  8792. const style = model.styleId && options.styles && options.styles.getStyleModel(model.styleId);
  8793. if (style) {
  8794. model.style = style;
  8795. }
  8796. if (model.styleId !== undefined) {
  8797. model.styleId = undefined;
  8798. }
  8799. switch (model.type) {
  8800. case Enums.ValueType.String:
  8801. if (typeof model.value === 'number') {
  8802. if (options.sharedStrings) {
  8803. model.value = options.sharedStrings.getString(model.value);
  8804. }
  8805. }
  8806. if (model.value.richText) {
  8807. model.type = Enums.ValueType.RichText;
  8808. }
  8809. break;
  8810. case Enums.ValueType.Number:
  8811. if (style && utils.isDateFmt(style.numFmt)) {
  8812. model.type = Enums.ValueType.Date;
  8813. model.value = utils.excelToDate(model.value, options.date1904);
  8814. }
  8815. break;
  8816. case Enums.ValueType.Formula:
  8817. if (model.result !== undefined && style && utils.isDateFmt(style.numFmt)) {
  8818. model.result = utils.excelToDate(model.result, options.date1904);
  8819. }
  8820. if (model.shareType === 'shared') {
  8821. if (model.ref) {
  8822. // master
  8823. options.formulae[model.si] = model.address;
  8824. } else {
  8825. // slave
  8826. model.sharedFormula = options.formulae[model.si];
  8827. delete model.shareType;
  8828. }
  8829. delete model.si;
  8830. }
  8831. break;
  8832. default:
  8833. break;
  8834. }
  8835. // look for hyperlink
  8836. const hyperlink = options.hyperlinkMap[model.address];
  8837. if (hyperlink) {
  8838. if (model.type === Enums.ValueType.Formula) {
  8839. model.text = model.result;
  8840. model.result = undefined;
  8841. } else {
  8842. model.text = model.value;
  8843. model.value = undefined;
  8844. }
  8845. model.type = Enums.ValueType.Hyperlink;
  8846. model.hyperlink = hyperlink;
  8847. }
  8848. const comment = options.commentsMap && options.commentsMap[model.address];
  8849. if (comment) {
  8850. model.comment = comment;
  8851. }
  8852. }
  8853. }
  8854. module.exports = CellXform;
  8855. },{"../../../doc/enums":7,"../../../doc/range":10,"../../../utils/utils":27,"../base-xform":32,"../strings/rich-text-xform":122}],74:[function(require,module,exports){
  8856. "use strict";
  8857. const BaseXform = require('../../base-xform');
  8858. class CfIconExtXform extends BaseXform {
  8859. get tag() {
  8860. return 'x14:cfIcon';
  8861. }
  8862. render(xmlStream, model) {
  8863. xmlStream.leafNode(this.tag, {
  8864. iconSet: model.iconSet,
  8865. iconId: model.iconId
  8866. });
  8867. }
  8868. parseOpen(_ref) {
  8869. let {
  8870. attributes
  8871. } = _ref;
  8872. this.model = {
  8873. iconSet: attributes.iconSet,
  8874. iconId: BaseXform.toIntValue(attributes.iconId)
  8875. };
  8876. }
  8877. parseClose(name) {
  8878. return name !== this.tag;
  8879. }
  8880. }
  8881. module.exports = CfIconExtXform;
  8882. },{"../../base-xform":32}],75:[function(require,module,exports){
  8883. "use strict";
  8884. const {
  8885. v4: uuidv4
  8886. } = require('uuid');
  8887. const BaseXform = require('../../base-xform');
  8888. const CompositeXform = require('../../composite-xform');
  8889. const DatabarExtXform = require('./databar-ext-xform');
  8890. const IconSetExtXform = require('./icon-set-ext-xform');
  8891. const extIcons = {
  8892. '3Triangles': true,
  8893. '3Stars': true,
  8894. '5Boxes': true
  8895. };
  8896. class CfRuleExtXform extends CompositeXform {
  8897. constructor() {
  8898. super();
  8899. this.map = {
  8900. 'x14:dataBar': this.databarXform = new DatabarExtXform(),
  8901. 'x14:iconSet': this.iconSetXform = new IconSetExtXform()
  8902. };
  8903. }
  8904. get tag() {
  8905. return 'x14:cfRule';
  8906. }
  8907. static isExt(rule) {
  8908. // is this rule primitive?
  8909. if (rule.type === 'dataBar') {
  8910. return DatabarExtXform.isExt(rule);
  8911. }
  8912. if (rule.type === 'iconSet') {
  8913. if (rule.custom || extIcons[rule.iconSet]) {
  8914. return true;
  8915. }
  8916. }
  8917. return false;
  8918. }
  8919. prepare(model) {
  8920. if (CfRuleExtXform.isExt(model)) {
  8921. model.x14Id = `{${uuidv4()}}`.toUpperCase();
  8922. }
  8923. }
  8924. render(xmlStream, model) {
  8925. if (!CfRuleExtXform.isExt(model)) {
  8926. return;
  8927. }
  8928. switch (model.type) {
  8929. case 'dataBar':
  8930. this.renderDataBar(xmlStream, model);
  8931. break;
  8932. case 'iconSet':
  8933. this.renderIconSet(xmlStream, model);
  8934. break;
  8935. }
  8936. }
  8937. renderDataBar(xmlStream, model) {
  8938. xmlStream.openNode(this.tag, {
  8939. type: 'dataBar',
  8940. id: model.x14Id
  8941. });
  8942. this.databarXform.render(xmlStream, model);
  8943. xmlStream.closeNode();
  8944. }
  8945. renderIconSet(xmlStream, model) {
  8946. xmlStream.openNode(this.tag, {
  8947. type: 'iconSet',
  8948. priority: model.priority,
  8949. id: model.x14Id || `{${uuidv4()}}`
  8950. });
  8951. this.iconSetXform.render(xmlStream, model);
  8952. xmlStream.closeNode();
  8953. }
  8954. createNewModel(_ref) {
  8955. let {
  8956. attributes
  8957. } = _ref;
  8958. return {
  8959. type: attributes.type,
  8960. x14Id: attributes.id,
  8961. priority: BaseXform.toIntValue(attributes.priority)
  8962. };
  8963. }
  8964. onParserClose(name, parser) {
  8965. Object.assign(this.model, parser.model);
  8966. }
  8967. }
  8968. module.exports = CfRuleExtXform;
  8969. },{"../../base-xform":32,"../../composite-xform":48,"./databar-ext-xform":79,"./icon-set-ext-xform":81,"uuid":366}],76:[function(require,module,exports){
  8970. "use strict";
  8971. const CompositeXform = require('../../composite-xform');
  8972. const FExtXform = require('./f-ext-xform');
  8973. class CfvoExtXform extends CompositeXform {
  8974. constructor() {
  8975. super();
  8976. this.map = {
  8977. 'xm:f': this.fExtXform = new FExtXform()
  8978. };
  8979. }
  8980. get tag() {
  8981. return 'x14:cfvo';
  8982. }
  8983. render(xmlStream, model) {
  8984. xmlStream.openNode(this.tag, {
  8985. type: model.type
  8986. });
  8987. if (model.value !== undefined) {
  8988. this.fExtXform.render(xmlStream, model.value);
  8989. }
  8990. xmlStream.closeNode();
  8991. }
  8992. createNewModel(node) {
  8993. return {
  8994. type: node.attributes.type
  8995. };
  8996. }
  8997. onParserClose(name, parser) {
  8998. switch (name) {
  8999. case 'xm:f':
  9000. this.model.value = parser.model ? parseFloat(parser.model) : 0;
  9001. break;
  9002. }
  9003. }
  9004. }
  9005. module.exports = CfvoExtXform;
  9006. },{"../../composite-xform":48,"./f-ext-xform":80}],77:[function(require,module,exports){
  9007. "use strict";
  9008. const CompositeXform = require('../../composite-xform');
  9009. const SqRefExtXform = require('./sqref-ext-xform');
  9010. const CfRuleExtXform = require('./cf-rule-ext-xform');
  9011. class ConditionalFormattingExtXform extends CompositeXform {
  9012. constructor() {
  9013. super();
  9014. this.map = {
  9015. 'xm:sqref': this.sqRef = new SqRefExtXform(),
  9016. 'x14:cfRule': this.cfRule = new CfRuleExtXform()
  9017. };
  9018. }
  9019. get tag() {
  9020. return 'x14:conditionalFormatting';
  9021. }
  9022. prepare(model, options) {
  9023. model.rules.forEach(rule => {
  9024. this.cfRule.prepare(rule, options);
  9025. });
  9026. }
  9027. render(xmlStream, model) {
  9028. if (!model.rules.some(CfRuleExtXform.isExt)) {
  9029. return;
  9030. }
  9031. xmlStream.openNode(this.tag, {
  9032. 'xmlns:xm': 'http://schemas.microsoft.com/office/excel/2006/main'
  9033. });
  9034. model.rules.filter(CfRuleExtXform.isExt).forEach(rule => this.cfRule.render(xmlStream, rule));
  9035. // for some odd reason, Excel needs the <xm:sqref> node to be after the rules
  9036. this.sqRef.render(xmlStream, model.ref);
  9037. xmlStream.closeNode();
  9038. }
  9039. createNewModel() {
  9040. return {
  9041. rules: []
  9042. };
  9043. }
  9044. onParserClose(name, parser) {
  9045. switch (name) {
  9046. case 'xm:sqref':
  9047. this.model.ref = parser.model;
  9048. break;
  9049. case 'x14:cfRule':
  9050. this.model.rules.push(parser.model);
  9051. break;
  9052. }
  9053. }
  9054. }
  9055. module.exports = ConditionalFormattingExtXform;
  9056. },{"../../composite-xform":48,"./cf-rule-ext-xform":75,"./sqref-ext-xform":82}],78:[function(require,module,exports){
  9057. "use strict";
  9058. const CompositeXform = require('../../composite-xform');
  9059. const CfRuleExtXform = require('./cf-rule-ext-xform');
  9060. const ConditionalFormattingExtXform = require('./conditional-formatting-ext-xform');
  9061. class ConditionalFormattingsExtXform extends CompositeXform {
  9062. constructor() {
  9063. super();
  9064. this.map = {
  9065. 'x14:conditionalFormatting': this.cfXform = new ConditionalFormattingExtXform()
  9066. };
  9067. }
  9068. get tag() {
  9069. return 'x14:conditionalFormattings';
  9070. }
  9071. hasContent(model) {
  9072. if (model.hasExtContent === undefined) {
  9073. model.hasExtContent = model.some(cf => cf.rules.some(CfRuleExtXform.isExt));
  9074. }
  9075. return model.hasExtContent;
  9076. }
  9077. prepare(model, options) {
  9078. model.forEach(cf => {
  9079. this.cfXform.prepare(cf, options);
  9080. });
  9081. }
  9082. render(xmlStream, model) {
  9083. if (this.hasContent(model)) {
  9084. xmlStream.openNode(this.tag);
  9085. model.forEach(cf => this.cfXform.render(xmlStream, cf));
  9086. xmlStream.closeNode();
  9087. }
  9088. }
  9089. createNewModel() {
  9090. return [];
  9091. }
  9092. onParserClose(name, parser) {
  9093. // model is array of conditional formatting objects
  9094. this.model.push(parser.model);
  9095. }
  9096. }
  9097. module.exports = ConditionalFormattingsExtXform;
  9098. },{"../../composite-xform":48,"./cf-rule-ext-xform":75,"./conditional-formatting-ext-xform":77}],79:[function(require,module,exports){
  9099. "use strict";
  9100. const BaseXform = require('../../base-xform');
  9101. const CompositeXform = require('../../composite-xform');
  9102. const ColorXform = require('../../style/color-xform');
  9103. const CfvoExtXform = require('./cfvo-ext-xform');
  9104. class DatabarExtXform extends CompositeXform {
  9105. constructor() {
  9106. super();
  9107. this.map = {
  9108. 'x14:cfvo': this.cfvoXform = new CfvoExtXform(),
  9109. 'x14:borderColor': this.borderColorXform = new ColorXform('x14:borderColor'),
  9110. 'x14:negativeBorderColor': this.negativeBorderColorXform = new ColorXform('x14:negativeBorderColor'),
  9111. 'x14:negativeFillColor': this.negativeFillColorXform = new ColorXform('x14:negativeFillColor'),
  9112. 'x14:axisColor': this.axisColorXform = new ColorXform('x14:axisColor')
  9113. };
  9114. }
  9115. static isExt(rule) {
  9116. // not all databars need ext
  9117. // TODO: refine this
  9118. return !rule.gradient;
  9119. }
  9120. get tag() {
  9121. return 'x14:dataBar';
  9122. }
  9123. render(xmlStream, model) {
  9124. xmlStream.openNode(this.tag, {
  9125. minLength: BaseXform.toIntAttribute(model.minLength, 0, true),
  9126. maxLength: BaseXform.toIntAttribute(model.maxLength, 100, true),
  9127. border: BaseXform.toBoolAttribute(model.border, false),
  9128. gradient: BaseXform.toBoolAttribute(model.gradient, true),
  9129. negativeBarColorSameAsPositive: BaseXform.toBoolAttribute(model.negativeBarColorSameAsPositive, true),
  9130. negativeBarBorderColorSameAsPositive: BaseXform.toBoolAttribute(model.negativeBarBorderColorSameAsPositive, true),
  9131. axisPosition: BaseXform.toAttribute(model.axisPosition, 'auto'),
  9132. direction: BaseXform.toAttribute(model.direction, 'leftToRight')
  9133. });
  9134. model.cfvo.forEach(cfvo => {
  9135. this.cfvoXform.render(xmlStream, cfvo);
  9136. });
  9137. this.borderColorXform.render(xmlStream, model.borderColor);
  9138. this.negativeBorderColorXform.render(xmlStream, model.negativeBorderColor);
  9139. this.negativeFillColorXform.render(xmlStream, model.negativeFillColor);
  9140. this.axisColorXform.render(xmlStream, model.axisColor);
  9141. xmlStream.closeNode();
  9142. }
  9143. createNewModel(_ref) {
  9144. let {
  9145. attributes
  9146. } = _ref;
  9147. return {
  9148. cfvo: [],
  9149. minLength: BaseXform.toIntValue(attributes.minLength, 0),
  9150. maxLength: BaseXform.toIntValue(attributes.maxLength, 100),
  9151. border: BaseXform.toBoolValue(attributes.border, false),
  9152. gradient: BaseXform.toBoolValue(attributes.gradient, true),
  9153. negativeBarColorSameAsPositive: BaseXform.toBoolValue(attributes.negativeBarColorSameAsPositive, true),
  9154. negativeBarBorderColorSameAsPositive: BaseXform.toBoolValue(attributes.negativeBarBorderColorSameAsPositive, true),
  9155. axisPosition: BaseXform.toStringValue(attributes.axisPosition, 'auto'),
  9156. direction: BaseXform.toStringValue(attributes.direction, 'leftToRight')
  9157. };
  9158. }
  9159. onParserClose(name, parser) {
  9160. const [, prop] = name.split(':');
  9161. switch (prop) {
  9162. case 'cfvo':
  9163. this.model.cfvo.push(parser.model);
  9164. break;
  9165. default:
  9166. this.model[prop] = parser.model;
  9167. break;
  9168. }
  9169. }
  9170. }
  9171. module.exports = DatabarExtXform;
  9172. },{"../../base-xform":32,"../../composite-xform":48,"../../style/color-xform":128,"./cfvo-ext-xform":76}],80:[function(require,module,exports){
  9173. "use strict";
  9174. const BaseXform = require('../../base-xform');
  9175. class FExtXform extends BaseXform {
  9176. get tag() {
  9177. return 'xm:f';
  9178. }
  9179. render(xmlStream, model) {
  9180. xmlStream.leafNode(this.tag, null, model);
  9181. }
  9182. parseOpen() {
  9183. this.model = '';
  9184. }
  9185. parseText(text) {
  9186. this.model += text;
  9187. }
  9188. parseClose(name) {
  9189. return name !== this.tag;
  9190. }
  9191. }
  9192. module.exports = FExtXform;
  9193. },{"../../base-xform":32}],81:[function(require,module,exports){
  9194. "use strict";
  9195. const BaseXform = require('../../base-xform');
  9196. const CompositeXform = require('../../composite-xform');
  9197. const CfvoExtXform = require('./cfvo-ext-xform');
  9198. const CfIconExtXform = require('./cf-icon-ext-xform');
  9199. class IconSetExtXform extends CompositeXform {
  9200. constructor() {
  9201. super();
  9202. this.map = {
  9203. 'x14:cfvo': this.cfvoXform = new CfvoExtXform(),
  9204. 'x14:cfIcon': this.cfIconXform = new CfIconExtXform()
  9205. };
  9206. }
  9207. get tag() {
  9208. return 'x14:iconSet';
  9209. }
  9210. render(xmlStream, model) {
  9211. xmlStream.openNode(this.tag, {
  9212. iconSet: BaseXform.toStringAttribute(model.iconSet),
  9213. reverse: BaseXform.toBoolAttribute(model.reverse, false),
  9214. showValue: BaseXform.toBoolAttribute(model.showValue, true),
  9215. custom: BaseXform.toBoolAttribute(model.icons, false)
  9216. });
  9217. model.cfvo.forEach(cfvo => {
  9218. this.cfvoXform.render(xmlStream, cfvo);
  9219. });
  9220. if (model.icons) {
  9221. model.icons.forEach((icon, i) => {
  9222. icon.iconId = i;
  9223. this.cfIconXform.render(xmlStream, icon);
  9224. });
  9225. }
  9226. xmlStream.closeNode();
  9227. }
  9228. createNewModel(_ref) {
  9229. let {
  9230. attributes
  9231. } = _ref;
  9232. return {
  9233. cfvo: [],
  9234. iconSet: BaseXform.toStringValue(attributes.iconSet, '3TrafficLights'),
  9235. reverse: BaseXform.toBoolValue(attributes.reverse, false),
  9236. showValue: BaseXform.toBoolValue(attributes.showValue, true)
  9237. };
  9238. }
  9239. onParserClose(name, parser) {
  9240. const [, prop] = name.split(':');
  9241. switch (prop) {
  9242. case 'cfvo':
  9243. this.model.cfvo.push(parser.model);
  9244. break;
  9245. case 'cfIcon':
  9246. if (!this.model.icons) {
  9247. this.model.icons = [];
  9248. }
  9249. this.model.icons.push(parser.model);
  9250. break;
  9251. default:
  9252. this.model[prop] = parser.model;
  9253. break;
  9254. }
  9255. }
  9256. }
  9257. module.exports = IconSetExtXform;
  9258. },{"../../base-xform":32,"../../composite-xform":48,"./cf-icon-ext-xform":74,"./cfvo-ext-xform":76}],82:[function(require,module,exports){
  9259. "use strict";
  9260. const BaseXform = require('../../base-xform');
  9261. class SqrefExtXform extends BaseXform {
  9262. get tag() {
  9263. return 'xm:sqref';
  9264. }
  9265. render(xmlStream, model) {
  9266. xmlStream.leafNode(this.tag, null, model);
  9267. }
  9268. parseOpen() {
  9269. this.model = '';
  9270. }
  9271. parseText(text) {
  9272. this.model += text;
  9273. }
  9274. parseClose(name) {
  9275. return name !== this.tag;
  9276. }
  9277. }
  9278. module.exports = SqrefExtXform;
  9279. },{"../../base-xform":32}],83:[function(require,module,exports){
  9280. "use strict";
  9281. const BaseXform = require('../../base-xform');
  9282. const CompositeXform = require('../../composite-xform');
  9283. const Range = require('../../../../doc/range');
  9284. const DatabarXform = require('./databar-xform');
  9285. const ExtLstRefXform = require('./ext-lst-ref-xform');
  9286. const FormulaXform = require('./formula-xform');
  9287. const ColorScaleXform = require('./color-scale-xform');
  9288. const IconSetXform = require('./icon-set-xform');
  9289. const extIcons = {
  9290. '3Triangles': true,
  9291. '3Stars': true,
  9292. '5Boxes': true
  9293. };
  9294. const getTextFormula = model => {
  9295. if (model.formulae && model.formulae[0]) {
  9296. return model.formulae[0];
  9297. }
  9298. const range = new Range(model.ref);
  9299. const {
  9300. tl
  9301. } = range;
  9302. switch (model.operator) {
  9303. case 'containsText':
  9304. return `NOT(ISERROR(SEARCH("${model.text}",${tl})))`;
  9305. case 'containsBlanks':
  9306. return `LEN(TRIM(${tl}))=0`;
  9307. case 'notContainsBlanks':
  9308. return `LEN(TRIM(${tl}))>0`;
  9309. case 'containsErrors':
  9310. return `ISERROR(${tl})`;
  9311. case 'notContainsErrors':
  9312. return `NOT(ISERROR(${tl}))`;
  9313. default:
  9314. return undefined;
  9315. }
  9316. };
  9317. const getTimePeriodFormula = model => {
  9318. if (model.formulae && model.formulae[0]) {
  9319. return model.formulae[0];
  9320. }
  9321. const range = new Range(model.ref);
  9322. const {
  9323. tl
  9324. } = range;
  9325. switch (model.timePeriod) {
  9326. case 'thisWeek':
  9327. return `AND(TODAY()-ROUNDDOWN(${tl},0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(${tl},0)-TODAY()<=7-WEEKDAY(TODAY()))`;
  9328. case 'lastWeek':
  9329. return `AND(TODAY()-ROUNDDOWN(${tl},0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(${tl},0)<(WEEKDAY(TODAY())+7))`;
  9330. case 'nextWeek':
  9331. return `AND(ROUNDDOWN(${tl},0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(${tl},0)-TODAY()<(15-WEEKDAY(TODAY())))`;
  9332. case 'yesterday':
  9333. return `FLOOR(${tl},1)=TODAY()-1`;
  9334. case 'today':
  9335. return `FLOOR(${tl},1)=TODAY()`;
  9336. case 'tomorrow':
  9337. return `FLOOR(${tl},1)=TODAY()+1`;
  9338. case 'last7Days':
  9339. return `AND(TODAY()-FLOOR(${tl},1)<=6,FLOOR(${tl},1)<=TODAY())`;
  9340. case 'lastMonth':
  9341. return `AND(MONTH(${tl})=MONTH(EDATE(TODAY(),0-1)),YEAR(${tl})=YEAR(EDATE(TODAY(),0-1)))`;
  9342. case 'thisMonth':
  9343. return `AND(MONTH(${tl})=MONTH(TODAY()),YEAR(${tl})=YEAR(TODAY()))`;
  9344. case 'nextMonth':
  9345. return `AND(MONTH(${tl})=MONTH(EDATE(TODAY(),0+1)),YEAR(${tl})=YEAR(EDATE(TODAY(),0+1)))`;
  9346. default:
  9347. return undefined;
  9348. }
  9349. };
  9350. const opType = attributes => {
  9351. const {
  9352. type,
  9353. operator
  9354. } = attributes;
  9355. switch (type) {
  9356. case 'containsText':
  9357. case 'containsBlanks':
  9358. case 'notContainsBlanks':
  9359. case 'containsErrors':
  9360. case 'notContainsErrors':
  9361. return {
  9362. type: 'containsText',
  9363. operator: type
  9364. };
  9365. default:
  9366. return {
  9367. type,
  9368. operator
  9369. };
  9370. }
  9371. };
  9372. class CfRuleXform extends CompositeXform {
  9373. constructor() {
  9374. super();
  9375. this.map = {
  9376. dataBar: this.databarXform = new DatabarXform(),
  9377. extLst: this.extLstRefXform = new ExtLstRefXform(),
  9378. formula: this.formulaXform = new FormulaXform(),
  9379. colorScale: this.colorScaleXform = new ColorScaleXform(),
  9380. iconSet: this.iconSetXform = new IconSetXform()
  9381. };
  9382. }
  9383. get tag() {
  9384. return 'cfRule';
  9385. }
  9386. static isPrimitive(rule) {
  9387. // is this rule primitive?
  9388. if (rule.type === 'iconSet') {
  9389. if (rule.custom || extIcons[rule.iconSet]) {
  9390. return false;
  9391. }
  9392. }
  9393. return true;
  9394. }
  9395. render(xmlStream, model) {
  9396. switch (model.type) {
  9397. case 'expression':
  9398. this.renderExpression(xmlStream, model);
  9399. break;
  9400. case 'cellIs':
  9401. this.renderCellIs(xmlStream, model);
  9402. break;
  9403. case 'top10':
  9404. this.renderTop10(xmlStream, model);
  9405. break;
  9406. case 'aboveAverage':
  9407. this.renderAboveAverage(xmlStream, model);
  9408. break;
  9409. case 'dataBar':
  9410. this.renderDataBar(xmlStream, model);
  9411. break;
  9412. case 'colorScale':
  9413. this.renderColorScale(xmlStream, model);
  9414. break;
  9415. case 'iconSet':
  9416. this.renderIconSet(xmlStream, model);
  9417. break;
  9418. case 'containsText':
  9419. this.renderText(xmlStream, model);
  9420. break;
  9421. case 'timePeriod':
  9422. this.renderTimePeriod(xmlStream, model);
  9423. break;
  9424. }
  9425. }
  9426. renderExpression(xmlStream, model) {
  9427. xmlStream.openNode(this.tag, {
  9428. type: 'expression',
  9429. dxfId: model.dxfId,
  9430. priority: model.priority
  9431. });
  9432. this.formulaXform.render(xmlStream, model.formulae[0]);
  9433. xmlStream.closeNode();
  9434. }
  9435. renderCellIs(xmlStream, model) {
  9436. xmlStream.openNode(this.tag, {
  9437. type: 'cellIs',
  9438. dxfId: model.dxfId,
  9439. priority: model.priority,
  9440. operator: model.operator
  9441. });
  9442. model.formulae.forEach(formula => {
  9443. this.formulaXform.render(xmlStream, formula);
  9444. });
  9445. xmlStream.closeNode();
  9446. }
  9447. renderTop10(xmlStream, model) {
  9448. xmlStream.leafNode(this.tag, {
  9449. type: 'top10',
  9450. dxfId: model.dxfId,
  9451. priority: model.priority,
  9452. percent: BaseXform.toBoolAttribute(model.percent, false),
  9453. bottom: BaseXform.toBoolAttribute(model.bottom, false),
  9454. rank: BaseXform.toIntValue(model.rank, 10, true)
  9455. });
  9456. }
  9457. renderAboveAverage(xmlStream, model) {
  9458. xmlStream.leafNode(this.tag, {
  9459. type: 'aboveAverage',
  9460. dxfId: model.dxfId,
  9461. priority: model.priority,
  9462. aboveAverage: BaseXform.toBoolAttribute(model.aboveAverage, true)
  9463. });
  9464. }
  9465. renderDataBar(xmlStream, model) {
  9466. xmlStream.openNode(this.tag, {
  9467. type: 'dataBar',
  9468. priority: model.priority
  9469. });
  9470. this.databarXform.render(xmlStream, model);
  9471. this.extLstRefXform.render(xmlStream, model);
  9472. xmlStream.closeNode();
  9473. }
  9474. renderColorScale(xmlStream, model) {
  9475. xmlStream.openNode(this.tag, {
  9476. type: 'colorScale',
  9477. priority: model.priority
  9478. });
  9479. this.colorScaleXform.render(xmlStream, model);
  9480. xmlStream.closeNode();
  9481. }
  9482. renderIconSet(xmlStream, model) {
  9483. // iconset is all primitive or all extLst
  9484. if (!CfRuleXform.isPrimitive(model)) {
  9485. return;
  9486. }
  9487. xmlStream.openNode(this.tag, {
  9488. type: 'iconSet',
  9489. priority: model.priority
  9490. });
  9491. this.iconSetXform.render(xmlStream, model);
  9492. xmlStream.closeNode();
  9493. }
  9494. renderText(xmlStream, model) {
  9495. xmlStream.openNode(this.tag, {
  9496. type: model.operator,
  9497. dxfId: model.dxfId,
  9498. priority: model.priority,
  9499. operator: BaseXform.toStringAttribute(model.operator, 'containsText')
  9500. });
  9501. const formula = getTextFormula(model);
  9502. if (formula) {
  9503. this.formulaXform.render(xmlStream, formula);
  9504. }
  9505. xmlStream.closeNode();
  9506. }
  9507. renderTimePeriod(xmlStream, model) {
  9508. xmlStream.openNode(this.tag, {
  9509. type: 'timePeriod',
  9510. dxfId: model.dxfId,
  9511. priority: model.priority,
  9512. timePeriod: model.timePeriod
  9513. });
  9514. const formula = getTimePeriodFormula(model);
  9515. if (formula) {
  9516. this.formulaXform.render(xmlStream, formula);
  9517. }
  9518. xmlStream.closeNode();
  9519. }
  9520. createNewModel(_ref) {
  9521. let {
  9522. attributes
  9523. } = _ref;
  9524. return {
  9525. ...opType(attributes),
  9526. dxfId: BaseXform.toIntValue(attributes.dxfId),
  9527. priority: BaseXform.toIntValue(attributes.priority),
  9528. timePeriod: attributes.timePeriod,
  9529. percent: BaseXform.toBoolValue(attributes.percent),
  9530. bottom: BaseXform.toBoolValue(attributes.bottom),
  9531. rank: BaseXform.toIntValue(attributes.rank),
  9532. aboveAverage: BaseXform.toBoolValue(attributes.aboveAverage)
  9533. };
  9534. }
  9535. onParserClose(name, parser) {
  9536. switch (name) {
  9537. case 'dataBar':
  9538. case 'extLst':
  9539. case 'colorScale':
  9540. case 'iconSet':
  9541. // merge parser model with ours
  9542. Object.assign(this.model, parser.model);
  9543. break;
  9544. case 'formula':
  9545. // except - formula is a string and appends to formulae
  9546. this.model.formulae = this.model.formulae || [];
  9547. this.model.formulae.push(parser.model);
  9548. break;
  9549. }
  9550. }
  9551. }
  9552. module.exports = CfRuleXform;
  9553. },{"../../../../doc/range":10,"../../base-xform":32,"../../composite-xform":48,"./color-scale-xform":85,"./databar-xform":88,"./ext-lst-ref-xform":89,"./formula-xform":90,"./icon-set-xform":91}],84:[function(require,module,exports){
  9554. "use strict";
  9555. const BaseXform = require('../../base-xform');
  9556. class CfvoXform extends BaseXform {
  9557. get tag() {
  9558. return 'cfvo';
  9559. }
  9560. render(xmlStream, model) {
  9561. xmlStream.leafNode(this.tag, {
  9562. type: model.type,
  9563. val: model.value
  9564. });
  9565. }
  9566. parseOpen(node) {
  9567. this.model = {
  9568. type: node.attributes.type,
  9569. value: BaseXform.toFloatValue(node.attributes.val)
  9570. };
  9571. }
  9572. parseClose(name) {
  9573. return name !== this.tag;
  9574. }
  9575. }
  9576. module.exports = CfvoXform;
  9577. },{"../../base-xform":32}],85:[function(require,module,exports){
  9578. "use strict";
  9579. const CompositeXform = require('../../composite-xform');
  9580. const ColorXform = require('../../style/color-xform');
  9581. const CfvoXform = require('./cfvo-xform');
  9582. class ColorScaleXform extends CompositeXform {
  9583. constructor() {
  9584. super();
  9585. this.map = {
  9586. cfvo: this.cfvoXform = new CfvoXform(),
  9587. color: this.colorXform = new ColorXform()
  9588. };
  9589. }
  9590. get tag() {
  9591. return 'colorScale';
  9592. }
  9593. render(xmlStream, model) {
  9594. xmlStream.openNode(this.tag);
  9595. model.cfvo.forEach(cfvo => {
  9596. this.cfvoXform.render(xmlStream, cfvo);
  9597. });
  9598. model.color.forEach(color => {
  9599. this.colorXform.render(xmlStream, color);
  9600. });
  9601. xmlStream.closeNode();
  9602. }
  9603. createNewModel(node) {
  9604. return {
  9605. cfvo: [],
  9606. color: []
  9607. };
  9608. }
  9609. onParserClose(name, parser) {
  9610. this.model[name].push(parser.model);
  9611. }
  9612. }
  9613. module.exports = ColorScaleXform;
  9614. },{"../../composite-xform":48,"../../style/color-xform":128,"./cfvo-xform":84}],86:[function(require,module,exports){
  9615. "use strict";
  9616. const CompositeXform = require('../../composite-xform');
  9617. const CfRuleXform = require('./cf-rule-xform');
  9618. class ConditionalFormattingXform extends CompositeXform {
  9619. constructor() {
  9620. super();
  9621. this.map = {
  9622. cfRule: new CfRuleXform()
  9623. };
  9624. }
  9625. get tag() {
  9626. return 'conditionalFormatting';
  9627. }
  9628. render(xmlStream, model) {
  9629. // if there are no primitive rules, exit now
  9630. if (!model.rules.some(CfRuleXform.isPrimitive)) {
  9631. return;
  9632. }
  9633. xmlStream.openNode(this.tag, {
  9634. sqref: model.ref
  9635. });
  9636. model.rules.forEach(rule => {
  9637. if (CfRuleXform.isPrimitive(rule)) {
  9638. rule.ref = model.ref;
  9639. this.map.cfRule.render(xmlStream, rule);
  9640. }
  9641. });
  9642. xmlStream.closeNode();
  9643. }
  9644. createNewModel(_ref) {
  9645. let {
  9646. attributes
  9647. } = _ref;
  9648. return {
  9649. ref: attributes.sqref,
  9650. rules: []
  9651. };
  9652. }
  9653. onParserClose(name, parser) {
  9654. this.model.rules.push(parser.model);
  9655. }
  9656. }
  9657. module.exports = ConditionalFormattingXform;
  9658. },{"../../composite-xform":48,"./cf-rule-xform":83}],87:[function(require,module,exports){
  9659. "use strict";
  9660. const BaseXform = require('../../base-xform');
  9661. const ConditionalFormattingXform = require('./conditional-formatting-xform');
  9662. class ConditionalFormattingsXform extends BaseXform {
  9663. constructor() {
  9664. super();
  9665. this.cfXform = new ConditionalFormattingXform();
  9666. }
  9667. get tag() {
  9668. return 'conditionalFormatting';
  9669. }
  9670. reset() {
  9671. this.model = [];
  9672. }
  9673. prepare(model, options) {
  9674. // ensure each rule has a priority value
  9675. let nextPriority = model.reduce((p, cf) => Math.max(p, ...cf.rules.map(rule => rule.priority || 0)), 1);
  9676. model.forEach(cf => {
  9677. cf.rules.forEach(rule => {
  9678. if (!rule.priority) {
  9679. rule.priority = nextPriority++;
  9680. }
  9681. if (rule.style) {
  9682. rule.dxfId = options.styles.addDxfStyle(rule.style);
  9683. }
  9684. });
  9685. });
  9686. }
  9687. render(xmlStream, model) {
  9688. model.forEach(cf => {
  9689. this.cfXform.render(xmlStream, cf);
  9690. });
  9691. }
  9692. parseOpen(node) {
  9693. if (this.parser) {
  9694. this.parser.parseOpen(node);
  9695. return true;
  9696. }
  9697. switch (node.name) {
  9698. case 'conditionalFormatting':
  9699. this.parser = this.cfXform;
  9700. this.parser.parseOpen(node);
  9701. return true;
  9702. default:
  9703. return false;
  9704. }
  9705. }
  9706. parseText(text) {
  9707. if (this.parser) {
  9708. this.parser.parseText(text);
  9709. }
  9710. }
  9711. parseClose(name) {
  9712. if (this.parser) {
  9713. if (!this.parser.parseClose(name)) {
  9714. this.model.push(this.parser.model);
  9715. this.parser = undefined;
  9716. return false;
  9717. }
  9718. return true;
  9719. }
  9720. return false;
  9721. }
  9722. reconcile(model, options) {
  9723. model.forEach(cf => {
  9724. cf.rules.forEach(rule => {
  9725. if (rule.dxfId !== undefined) {
  9726. rule.style = options.styles.getDxfStyle(rule.dxfId);
  9727. delete rule.dxfId;
  9728. }
  9729. });
  9730. });
  9731. }
  9732. }
  9733. module.exports = ConditionalFormattingsXform;
  9734. },{"../../base-xform":32,"./conditional-formatting-xform":86}],88:[function(require,module,exports){
  9735. "use strict";
  9736. const CompositeXform = require('../../composite-xform');
  9737. const ColorXform = require('../../style/color-xform');
  9738. const CfvoXform = require('./cfvo-xform');
  9739. class DatabarXform extends CompositeXform {
  9740. constructor() {
  9741. super();
  9742. this.map = {
  9743. cfvo: this.cfvoXform = new CfvoXform(),
  9744. color: this.colorXform = new ColorXform()
  9745. };
  9746. }
  9747. get tag() {
  9748. return 'dataBar';
  9749. }
  9750. render(xmlStream, model) {
  9751. xmlStream.openNode(this.tag);
  9752. model.cfvo.forEach(cfvo => {
  9753. this.cfvoXform.render(xmlStream, cfvo);
  9754. });
  9755. this.colorXform.render(xmlStream, model.color);
  9756. xmlStream.closeNode();
  9757. }
  9758. createNewModel() {
  9759. return {
  9760. cfvo: []
  9761. };
  9762. }
  9763. onParserClose(name, parser) {
  9764. switch (name) {
  9765. case 'cfvo':
  9766. this.model.cfvo.push(parser.model);
  9767. break;
  9768. case 'color':
  9769. this.model.color = parser.model;
  9770. break;
  9771. }
  9772. }
  9773. }
  9774. module.exports = DatabarXform;
  9775. },{"../../composite-xform":48,"../../style/color-xform":128,"./cfvo-xform":84}],89:[function(require,module,exports){
  9776. "use strict";
  9777. /* eslint-disable max-classes-per-file */
  9778. const BaseXform = require('../../base-xform');
  9779. const CompositeXform = require('../../composite-xform');
  9780. class X14IdXform extends BaseXform {
  9781. get tag() {
  9782. return 'x14:id';
  9783. }
  9784. render(xmlStream, model) {
  9785. xmlStream.leafNode(this.tag, null, model);
  9786. }
  9787. parseOpen() {
  9788. this.model = '';
  9789. }
  9790. parseText(text) {
  9791. this.model += text;
  9792. }
  9793. parseClose(name) {
  9794. return name !== this.tag;
  9795. }
  9796. }
  9797. class ExtXform extends CompositeXform {
  9798. constructor() {
  9799. super();
  9800. this.map = {
  9801. 'x14:id': this.idXform = new X14IdXform()
  9802. };
  9803. }
  9804. get tag() {
  9805. return 'ext';
  9806. }
  9807. render(xmlStream, model) {
  9808. xmlStream.openNode(this.tag, {
  9809. uri: '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}',
  9810. 'xmlns:x14': 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'
  9811. });
  9812. this.idXform.render(xmlStream, model.x14Id);
  9813. xmlStream.closeNode();
  9814. }
  9815. createNewModel() {
  9816. return {};
  9817. }
  9818. onParserClose(name, parser) {
  9819. this.model.x14Id = parser.model;
  9820. }
  9821. }
  9822. class ExtLstRefXform extends CompositeXform {
  9823. constructor() {
  9824. super();
  9825. this.map = {
  9826. ext: new ExtXform()
  9827. };
  9828. }
  9829. get tag() {
  9830. return 'extLst';
  9831. }
  9832. render(xmlStream, model) {
  9833. xmlStream.openNode(this.tag);
  9834. this.map.ext.render(xmlStream, model);
  9835. xmlStream.closeNode();
  9836. }
  9837. createNewModel() {
  9838. return {};
  9839. }
  9840. onParserClose(name, parser) {
  9841. Object.assign(this.model, parser.model);
  9842. }
  9843. }
  9844. module.exports = ExtLstRefXform;
  9845. },{"../../base-xform":32,"../../composite-xform":48}],90:[function(require,module,exports){
  9846. "use strict";
  9847. const BaseXform = require('../../base-xform');
  9848. class FormulaXform extends BaseXform {
  9849. get tag() {
  9850. return 'formula';
  9851. }
  9852. render(xmlStream, model) {
  9853. xmlStream.leafNode(this.tag, null, model);
  9854. }
  9855. parseOpen() {
  9856. this.model = '';
  9857. }
  9858. parseText(text) {
  9859. this.model += text;
  9860. }
  9861. parseClose(name) {
  9862. return name !== this.tag;
  9863. }
  9864. }
  9865. module.exports = FormulaXform;
  9866. },{"../../base-xform":32}],91:[function(require,module,exports){
  9867. "use strict";
  9868. const BaseXform = require('../../base-xform');
  9869. const CompositeXform = require('../../composite-xform');
  9870. const CfvoXform = require('./cfvo-xform');
  9871. class IconSetXform extends CompositeXform {
  9872. constructor() {
  9873. super();
  9874. this.map = {
  9875. cfvo: this.cfvoXform = new CfvoXform()
  9876. };
  9877. }
  9878. get tag() {
  9879. return 'iconSet';
  9880. }
  9881. render(xmlStream, model) {
  9882. xmlStream.openNode(this.tag, {
  9883. iconSet: BaseXform.toStringAttribute(model.iconSet, '3TrafficLights'),
  9884. reverse: BaseXform.toBoolAttribute(model.reverse, false),
  9885. showValue: BaseXform.toBoolAttribute(model.showValue, true)
  9886. });
  9887. model.cfvo.forEach(cfvo => {
  9888. this.cfvoXform.render(xmlStream, cfvo);
  9889. });
  9890. xmlStream.closeNode();
  9891. }
  9892. createNewModel(_ref) {
  9893. let {
  9894. attributes
  9895. } = _ref;
  9896. return {
  9897. iconSet: BaseXform.toStringValue(attributes.iconSet, '3TrafficLights'),
  9898. reverse: BaseXform.toBoolValue(attributes.reverse),
  9899. showValue: BaseXform.toBoolValue(attributes.showValue),
  9900. cfvo: []
  9901. };
  9902. }
  9903. onParserClose(name, parser) {
  9904. this.model[name].push(parser.model);
  9905. }
  9906. }
  9907. module.exports = IconSetXform;
  9908. },{"../../base-xform":32,"../../composite-xform":48,"./cfvo-xform":84}],92:[function(require,module,exports){
  9909. "use strict";
  9910. const utils = require('../../../utils/utils');
  9911. const BaseXform = require('../base-xform');
  9912. class ColXform extends BaseXform {
  9913. get tag() {
  9914. return 'col';
  9915. }
  9916. prepare(model, options) {
  9917. const styleId = options.styles.addStyleModel(model.style || {});
  9918. if (styleId) {
  9919. model.styleId = styleId;
  9920. }
  9921. }
  9922. render(xmlStream, model) {
  9923. xmlStream.openNode('col');
  9924. xmlStream.addAttribute('min', model.min);
  9925. xmlStream.addAttribute('max', model.max);
  9926. if (model.width) {
  9927. xmlStream.addAttribute('width', model.width);
  9928. }
  9929. if (model.styleId) {
  9930. xmlStream.addAttribute('style', model.styleId);
  9931. }
  9932. if (model.hidden) {
  9933. xmlStream.addAttribute('hidden', '1');
  9934. }
  9935. if (model.bestFit) {
  9936. xmlStream.addAttribute('bestFit', '1');
  9937. }
  9938. if (model.outlineLevel) {
  9939. xmlStream.addAttribute('outlineLevel', model.outlineLevel);
  9940. }
  9941. if (model.collapsed) {
  9942. xmlStream.addAttribute('collapsed', '1');
  9943. }
  9944. xmlStream.addAttribute('customWidth', '1');
  9945. xmlStream.closeNode();
  9946. }
  9947. parseOpen(node) {
  9948. if (node.name === 'col') {
  9949. const model = this.model = {
  9950. min: parseInt(node.attributes.min || '0', 10),
  9951. max: parseInt(node.attributes.max || '0', 10),
  9952. width: node.attributes.width === undefined ? undefined : parseFloat(node.attributes.width || '0')
  9953. };
  9954. if (node.attributes.style) {
  9955. model.styleId = parseInt(node.attributes.style, 10);
  9956. }
  9957. if (utils.parseBoolean(node.attributes.hidden)) {
  9958. model.hidden = true;
  9959. }
  9960. if (utils.parseBoolean(node.attributes.bestFit)) {
  9961. model.bestFit = true;
  9962. }
  9963. if (node.attributes.outlineLevel) {
  9964. model.outlineLevel = parseInt(node.attributes.outlineLevel, 10);
  9965. }
  9966. if (utils.parseBoolean(node.attributes.collapsed)) {
  9967. model.collapsed = true;
  9968. }
  9969. return true;
  9970. }
  9971. return false;
  9972. }
  9973. parseText() {}
  9974. parseClose() {
  9975. return false;
  9976. }
  9977. reconcile(model, options) {
  9978. // reconcile column styles
  9979. if (model.styleId) {
  9980. model.style = options.styles.getStyleModel(model.styleId);
  9981. }
  9982. }
  9983. }
  9984. module.exports = ColXform;
  9985. },{"../../../utils/utils":27,"../base-xform":32}],93:[function(require,module,exports){
  9986. "use strict";
  9987. const _ = require('../../../utils/under-dash');
  9988. const utils = require('../../../utils/utils');
  9989. const colCache = require('../../../utils/col-cache');
  9990. const BaseXform = require('../base-xform');
  9991. const Range = require('../../../doc/range');
  9992. function assign(definedName, attributes, name, defaultValue) {
  9993. const value = attributes[name];
  9994. if (value !== undefined) {
  9995. definedName[name] = value;
  9996. } else if (defaultValue !== undefined) {
  9997. definedName[name] = defaultValue;
  9998. }
  9999. }
  10000. function assignBool(definedName, attributes, name, defaultValue) {
  10001. const value = attributes[name];
  10002. if (value !== undefined) {
  10003. definedName[name] = utils.parseBoolean(value);
  10004. } else if (defaultValue !== undefined) {
  10005. definedName[name] = defaultValue;
  10006. }
  10007. }
  10008. function optimiseDataValidations(model) {
  10009. // Squeeze alike data validations together into rectangular ranges
  10010. // to reduce file size and speed up Excel load time
  10011. const dvList = _.map(model, (dataValidation, address) => ({
  10012. address,
  10013. dataValidation,
  10014. marked: false
  10015. })).sort((a, b) => _.strcmp(a.address, b.address));
  10016. const dvMap = _.keyBy(dvList, 'address');
  10017. const matchCol = (addr, height, col) => {
  10018. for (let i = 0; i < height; i++) {
  10019. const otherAddress = colCache.encodeAddress(addr.row + i, col);
  10020. if (!model[otherAddress] || !_.isEqual(model[addr.address], model[otherAddress])) {
  10021. return false;
  10022. }
  10023. }
  10024. return true;
  10025. };
  10026. return dvList.map(dv => {
  10027. if (!dv.marked) {
  10028. const addr = colCache.decodeEx(dv.address);
  10029. if (addr.dimensions) {
  10030. dvMap[addr.dimensions].marked = true;
  10031. return {
  10032. ...dv.dataValidation,
  10033. sqref: dv.address
  10034. };
  10035. }
  10036. // iterate downwards - finding matching cells
  10037. let height = 1;
  10038. let otherAddress = colCache.encodeAddress(addr.row + height, addr.col);
  10039. while (model[otherAddress] && _.isEqual(dv.dataValidation, model[otherAddress])) {
  10040. height++;
  10041. otherAddress = colCache.encodeAddress(addr.row + height, addr.col);
  10042. }
  10043. // iterate rightwards...
  10044. let width = 1;
  10045. while (matchCol(addr, height, addr.col + width)) {
  10046. width++;
  10047. }
  10048. // mark all included addresses
  10049. for (let i = 0; i < height; i++) {
  10050. for (let j = 0; j < width; j++) {
  10051. otherAddress = colCache.encodeAddress(addr.row + i, addr.col + j);
  10052. dvMap[otherAddress].marked = true;
  10053. }
  10054. }
  10055. if (height > 1 || width > 1) {
  10056. const bottom = addr.row + (height - 1);
  10057. const right = addr.col + (width - 1);
  10058. return {
  10059. ...dv.dataValidation,
  10060. sqref: `${dv.address}:${colCache.encodeAddress(bottom, right)}`
  10061. };
  10062. }
  10063. return {
  10064. ...dv.dataValidation,
  10065. sqref: dv.address
  10066. };
  10067. }
  10068. return null;
  10069. }).filter(Boolean);
  10070. }
  10071. class DataValidationsXform extends BaseXform {
  10072. get tag() {
  10073. return 'dataValidations';
  10074. }
  10075. render(xmlStream, model) {
  10076. const optimizedModel = optimiseDataValidations(model);
  10077. if (optimizedModel.length) {
  10078. xmlStream.openNode('dataValidations', {
  10079. count: optimizedModel.length
  10080. });
  10081. optimizedModel.forEach(value => {
  10082. xmlStream.openNode('dataValidation');
  10083. if (value.type !== 'any') {
  10084. xmlStream.addAttribute('type', value.type);
  10085. if (value.operator && value.type !== 'list' && value.operator !== 'between') {
  10086. xmlStream.addAttribute('operator', value.operator);
  10087. }
  10088. if (value.allowBlank) {
  10089. xmlStream.addAttribute('allowBlank', '1');
  10090. }
  10091. }
  10092. if (value.showInputMessage) {
  10093. xmlStream.addAttribute('showInputMessage', '1');
  10094. }
  10095. if (value.promptTitle) {
  10096. xmlStream.addAttribute('promptTitle', value.promptTitle);
  10097. }
  10098. if (value.prompt) {
  10099. xmlStream.addAttribute('prompt', value.prompt);
  10100. }
  10101. if (value.showErrorMessage) {
  10102. xmlStream.addAttribute('showErrorMessage', '1');
  10103. }
  10104. if (value.errorStyle) {
  10105. xmlStream.addAttribute('errorStyle', value.errorStyle);
  10106. }
  10107. if (value.errorTitle) {
  10108. xmlStream.addAttribute('errorTitle', value.errorTitle);
  10109. }
  10110. if (value.error) {
  10111. xmlStream.addAttribute('error', value.error);
  10112. }
  10113. xmlStream.addAttribute('sqref', value.sqref);
  10114. (value.formulae || []).forEach((formula, index) => {
  10115. xmlStream.openNode(`formula${index + 1}`);
  10116. if (value.type === 'date') {
  10117. xmlStream.writeText(utils.dateToExcel(new Date(formula)));
  10118. } else {
  10119. xmlStream.writeText(formula);
  10120. }
  10121. xmlStream.closeNode();
  10122. });
  10123. xmlStream.closeNode();
  10124. });
  10125. xmlStream.closeNode();
  10126. }
  10127. }
  10128. parseOpen(node) {
  10129. switch (node.name) {
  10130. case 'dataValidations':
  10131. this.model = {};
  10132. return true;
  10133. case 'dataValidation':
  10134. {
  10135. this._address = node.attributes.sqref;
  10136. const dataValidation = {
  10137. type: node.attributes.type || 'any',
  10138. formulae: []
  10139. };
  10140. if (node.attributes.type) {
  10141. assignBool(dataValidation, node.attributes, 'allowBlank');
  10142. }
  10143. assignBool(dataValidation, node.attributes, 'showInputMessage');
  10144. assignBool(dataValidation, node.attributes, 'showErrorMessage');
  10145. switch (dataValidation.type) {
  10146. case 'any':
  10147. case 'list':
  10148. case 'custom':
  10149. break;
  10150. default:
  10151. assign(dataValidation, node.attributes, 'operator', 'between');
  10152. break;
  10153. }
  10154. assign(dataValidation, node.attributes, 'promptTitle');
  10155. assign(dataValidation, node.attributes, 'prompt');
  10156. assign(dataValidation, node.attributes, 'errorStyle');
  10157. assign(dataValidation, node.attributes, 'errorTitle');
  10158. assign(dataValidation, node.attributes, 'error');
  10159. this._dataValidation = dataValidation;
  10160. return true;
  10161. }
  10162. case 'formula1':
  10163. case 'formula2':
  10164. this._formula = [];
  10165. return true;
  10166. default:
  10167. return false;
  10168. }
  10169. }
  10170. parseText(text) {
  10171. if (this._formula) {
  10172. this._formula.push(text);
  10173. }
  10174. }
  10175. parseClose(name) {
  10176. switch (name) {
  10177. case 'dataValidations':
  10178. return false;
  10179. case 'dataValidation':
  10180. {
  10181. if (!this._dataValidation.formulae || !this._dataValidation.formulae.length) {
  10182. delete this._dataValidation.formulae;
  10183. delete this._dataValidation.operator;
  10184. }
  10185. // The four known cases: 1. E4:L9 N4:U9 2.E4 L9 3. N4:U9 4. E4
  10186. const list = this._address.split(/\s+/g) || [];
  10187. list.forEach(addr => {
  10188. if (addr.includes(':')) {
  10189. const range = new Range(addr);
  10190. range.forEachAddress(address => {
  10191. this.model[address] = this._dataValidation;
  10192. });
  10193. } else {
  10194. this.model[addr] = this._dataValidation;
  10195. }
  10196. });
  10197. return true;
  10198. }
  10199. case 'formula1':
  10200. case 'formula2':
  10201. {
  10202. let formula = this._formula.join('');
  10203. switch (this._dataValidation.type) {
  10204. case 'whole':
  10205. case 'textLength':
  10206. formula = parseInt(formula, 10);
  10207. break;
  10208. case 'decimal':
  10209. formula = parseFloat(formula);
  10210. break;
  10211. case 'date':
  10212. formula = utils.excelToDate(parseFloat(formula));
  10213. break;
  10214. default:
  10215. break;
  10216. }
  10217. this._dataValidation.formulae.push(formula);
  10218. this._formula = undefined;
  10219. return true;
  10220. }
  10221. default:
  10222. return true;
  10223. }
  10224. }
  10225. }
  10226. module.exports = DataValidationsXform;
  10227. },{"../../../doc/range":10,"../../../utils/col-cache":19,"../../../utils/under-dash":26,"../../../utils/utils":27,"../base-xform":32}],94:[function(require,module,exports){
  10228. "use strict";
  10229. const BaseXform = require('../base-xform');
  10230. class DimensionXform extends BaseXform {
  10231. get tag() {
  10232. return 'dimension';
  10233. }
  10234. render(xmlStream, model) {
  10235. if (model) {
  10236. xmlStream.leafNode('dimension', {
  10237. ref: model
  10238. });
  10239. }
  10240. }
  10241. parseOpen(node) {
  10242. if (node.name === 'dimension') {
  10243. this.model = node.attributes.ref;
  10244. return true;
  10245. }
  10246. return false;
  10247. }
  10248. parseText() {}
  10249. parseClose() {
  10250. return false;
  10251. }
  10252. }
  10253. module.exports = DimensionXform;
  10254. },{"../base-xform":32}],95:[function(require,module,exports){
  10255. "use strict";
  10256. const BaseXform = require('../base-xform');
  10257. class DrawingXform extends BaseXform {
  10258. get tag() {
  10259. return 'drawing';
  10260. }
  10261. render(xmlStream, model) {
  10262. if (model) {
  10263. xmlStream.leafNode(this.tag, {
  10264. 'r:id': model.rId
  10265. });
  10266. }
  10267. }
  10268. parseOpen(node) {
  10269. switch (node.name) {
  10270. case this.tag:
  10271. this.model = {
  10272. rId: node.attributes['r:id']
  10273. };
  10274. return true;
  10275. default:
  10276. return false;
  10277. }
  10278. }
  10279. parseText() {}
  10280. parseClose() {
  10281. return false;
  10282. }
  10283. }
  10284. module.exports = DrawingXform;
  10285. },{"../base-xform":32}],96:[function(require,module,exports){
  10286. "use strict";
  10287. /* eslint-disable max-classes-per-file */
  10288. const CompositeXform = require('../composite-xform');
  10289. const ConditionalFormattingsExt = require('./cf-ext/conditional-formattings-ext-xform');
  10290. class ExtXform extends CompositeXform {
  10291. constructor() {
  10292. super();
  10293. this.map = {
  10294. 'x14:conditionalFormattings': this.conditionalFormattings = new ConditionalFormattingsExt()
  10295. };
  10296. }
  10297. get tag() {
  10298. return 'ext';
  10299. }
  10300. hasContent(model) {
  10301. return this.conditionalFormattings.hasContent(model.conditionalFormattings);
  10302. }
  10303. prepare(model, options) {
  10304. this.conditionalFormattings.prepare(model.conditionalFormattings, options);
  10305. }
  10306. render(xmlStream, model) {
  10307. xmlStream.openNode('ext', {
  10308. uri: '{78C0D931-6437-407d-A8EE-F0AAD7539E65}',
  10309. 'xmlns:x14': 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'
  10310. });
  10311. this.conditionalFormattings.render(xmlStream, model.conditionalFormattings);
  10312. xmlStream.closeNode();
  10313. }
  10314. createNewModel() {
  10315. return {};
  10316. }
  10317. onParserClose(name, parser) {
  10318. this.model[name] = parser.model;
  10319. }
  10320. }
  10321. class ExtLstXform extends CompositeXform {
  10322. constructor() {
  10323. super();
  10324. this.map = {
  10325. ext: this.ext = new ExtXform()
  10326. };
  10327. }
  10328. get tag() {
  10329. return 'extLst';
  10330. }
  10331. prepare(model, options) {
  10332. this.ext.prepare(model, options);
  10333. }
  10334. hasContent(model) {
  10335. return this.ext.hasContent(model);
  10336. }
  10337. render(xmlStream, model) {
  10338. if (!this.hasContent(model)) {
  10339. return;
  10340. }
  10341. xmlStream.openNode('extLst');
  10342. this.ext.render(xmlStream, model);
  10343. xmlStream.closeNode();
  10344. }
  10345. createNewModel() {
  10346. return {};
  10347. }
  10348. onParserClose(name, parser) {
  10349. Object.assign(this.model, parser.model);
  10350. }
  10351. }
  10352. module.exports = ExtLstXform;
  10353. },{"../composite-xform":48,"./cf-ext/conditional-formattings-ext-xform":78}],97:[function(require,module,exports){
  10354. "use strict";
  10355. const BaseXform = require('../base-xform');
  10356. class HeaderFooterXform extends BaseXform {
  10357. get tag() {
  10358. return 'headerFooter';
  10359. }
  10360. render(xmlStream, model) {
  10361. if (model) {
  10362. xmlStream.addRollback();
  10363. let createTag = false;
  10364. xmlStream.openNode('headerFooter');
  10365. if (model.differentFirst) {
  10366. xmlStream.addAttribute('differentFirst', '1');
  10367. createTag = true;
  10368. }
  10369. if (model.differentOddEven) {
  10370. xmlStream.addAttribute('differentOddEven', '1');
  10371. createTag = true;
  10372. }
  10373. if (model.oddHeader && typeof model.oddHeader === 'string') {
  10374. xmlStream.leafNode('oddHeader', null, model.oddHeader);
  10375. createTag = true;
  10376. }
  10377. if (model.oddFooter && typeof model.oddFooter === 'string') {
  10378. xmlStream.leafNode('oddFooter', null, model.oddFooter);
  10379. createTag = true;
  10380. }
  10381. if (model.evenHeader && typeof model.evenHeader === 'string') {
  10382. xmlStream.leafNode('evenHeader', null, model.evenHeader);
  10383. createTag = true;
  10384. }
  10385. if (model.evenFooter && typeof model.evenFooter === 'string') {
  10386. xmlStream.leafNode('evenFooter', null, model.evenFooter);
  10387. createTag = true;
  10388. }
  10389. if (model.firstHeader && typeof model.firstHeader === 'string') {
  10390. xmlStream.leafNode('firstHeader', null, model.firstHeader);
  10391. createTag = true;
  10392. }
  10393. if (model.firstFooter && typeof model.firstFooter === 'string') {
  10394. xmlStream.leafNode('firstFooter', null, model.firstFooter);
  10395. createTag = true;
  10396. }
  10397. if (createTag) {
  10398. xmlStream.closeNode();
  10399. xmlStream.commit();
  10400. } else {
  10401. xmlStream.rollback();
  10402. }
  10403. }
  10404. }
  10405. parseOpen(node) {
  10406. switch (node.name) {
  10407. case 'headerFooter':
  10408. this.model = {};
  10409. if (node.attributes.differentFirst) {
  10410. this.model.differentFirst = parseInt(node.attributes.differentFirst, 0) === 1;
  10411. }
  10412. if (node.attributes.differentOddEven) {
  10413. this.model.differentOddEven = parseInt(node.attributes.differentOddEven, 0) === 1;
  10414. }
  10415. return true;
  10416. case 'oddHeader':
  10417. this.currentNode = 'oddHeader';
  10418. return true;
  10419. case 'oddFooter':
  10420. this.currentNode = 'oddFooter';
  10421. return true;
  10422. case 'evenHeader':
  10423. this.currentNode = 'evenHeader';
  10424. return true;
  10425. case 'evenFooter':
  10426. this.currentNode = 'evenFooter';
  10427. return true;
  10428. case 'firstHeader':
  10429. this.currentNode = 'firstHeader';
  10430. return true;
  10431. case 'firstFooter':
  10432. this.currentNode = 'firstFooter';
  10433. return true;
  10434. default:
  10435. return false;
  10436. }
  10437. }
  10438. parseText(text) {
  10439. switch (this.currentNode) {
  10440. case 'oddHeader':
  10441. this.model.oddHeader = text;
  10442. break;
  10443. case 'oddFooter':
  10444. this.model.oddFooter = text;
  10445. break;
  10446. case 'evenHeader':
  10447. this.model.evenHeader = text;
  10448. break;
  10449. case 'evenFooter':
  10450. this.model.evenFooter = text;
  10451. break;
  10452. case 'firstHeader':
  10453. this.model.firstHeader = text;
  10454. break;
  10455. case 'firstFooter':
  10456. this.model.firstFooter = text;
  10457. break;
  10458. default:
  10459. break;
  10460. }
  10461. }
  10462. parseClose() {
  10463. switch (this.currentNode) {
  10464. case 'oddHeader':
  10465. case 'oddFooter':
  10466. case 'evenHeader':
  10467. case 'evenFooter':
  10468. case 'firstHeader':
  10469. case 'firstFooter':
  10470. this.currentNode = undefined;
  10471. return true;
  10472. default:
  10473. return false;
  10474. }
  10475. }
  10476. }
  10477. module.exports = HeaderFooterXform;
  10478. },{"../base-xform":32}],98:[function(require,module,exports){
  10479. "use strict";
  10480. const BaseXform = require('../base-xform');
  10481. class HyperlinkXform extends BaseXform {
  10482. get tag() {
  10483. return 'hyperlink';
  10484. }
  10485. render(xmlStream, model) {
  10486. if (this.isInternalLink(model)) {
  10487. xmlStream.leafNode('hyperlink', {
  10488. ref: model.address,
  10489. 'r:id': model.rId,
  10490. tooltip: model.tooltip,
  10491. location: model.target
  10492. });
  10493. } else {
  10494. xmlStream.leafNode('hyperlink', {
  10495. ref: model.address,
  10496. 'r:id': model.rId,
  10497. tooltip: model.tooltip
  10498. });
  10499. }
  10500. }
  10501. parseOpen(node) {
  10502. if (node.name === 'hyperlink') {
  10503. this.model = {
  10504. address: node.attributes.ref,
  10505. rId: node.attributes['r:id'],
  10506. tooltip: node.attributes.tooltip
  10507. };
  10508. // This is an internal link
  10509. if (node.attributes.location) {
  10510. this.model.target = node.attributes.location;
  10511. }
  10512. return true;
  10513. }
  10514. return false;
  10515. }
  10516. parseText() {}
  10517. parseClose() {
  10518. return false;
  10519. }
  10520. isInternalLink(model) {
  10521. // @example: Sheet2!D3, return true
  10522. return model.target && /^[^!]+![a-zA-Z]+[\d]+$/.test(model.target);
  10523. }
  10524. }
  10525. module.exports = HyperlinkXform;
  10526. },{"../base-xform":32}],99:[function(require,module,exports){
  10527. "use strict";
  10528. const BaseXform = require('../base-xform');
  10529. class MergeCellXform extends BaseXform {
  10530. get tag() {
  10531. return 'mergeCell';
  10532. }
  10533. render(xmlStream, model) {
  10534. xmlStream.leafNode('mergeCell', {
  10535. ref: model
  10536. });
  10537. }
  10538. parseOpen(node) {
  10539. if (node.name === 'mergeCell') {
  10540. this.model = node.attributes.ref;
  10541. return true;
  10542. }
  10543. return false;
  10544. }
  10545. parseText() {}
  10546. parseClose() {
  10547. return false;
  10548. }
  10549. }
  10550. module.exports = MergeCellXform;
  10551. },{"../base-xform":32}],100:[function(require,module,exports){
  10552. "use strict";
  10553. const _ = require('../../../utils/under-dash');
  10554. const Range = require('../../../doc/range');
  10555. const colCache = require('../../../utils/col-cache');
  10556. const Enums = require('../../../doc/enums');
  10557. class Merges {
  10558. constructor() {
  10559. // optional mergeCells is array of ranges (like the xml)
  10560. this.merges = {};
  10561. }
  10562. add(merge) {
  10563. // merge is {address, master}
  10564. if (this.merges[merge.master]) {
  10565. this.merges[merge.master].expandToAddress(merge.address);
  10566. } else {
  10567. const range = `${merge.master}:${merge.address}`;
  10568. this.merges[merge.master] = new Range(range);
  10569. }
  10570. }
  10571. get mergeCells() {
  10572. return _.map(this.merges, merge => merge.range);
  10573. }
  10574. reconcile(mergeCells, rows) {
  10575. // reconcile merge list with merge cells
  10576. _.each(mergeCells, merge => {
  10577. const dimensions = colCache.decode(merge);
  10578. for (let i = dimensions.top; i <= dimensions.bottom; i++) {
  10579. const row = rows[i - 1];
  10580. for (let j = dimensions.left; j <= dimensions.right; j++) {
  10581. const cell = row.cells[j - 1];
  10582. if (!cell) {
  10583. // nulls are not included in document - so if master cell has no value - add a null one here
  10584. row.cells[j] = {
  10585. type: Enums.ValueType.Null,
  10586. address: colCache.encodeAddress(i, j)
  10587. };
  10588. } else if (cell.type === Enums.ValueType.Merge) {
  10589. cell.master = dimensions.tl;
  10590. }
  10591. }
  10592. }
  10593. });
  10594. }
  10595. getMasterAddress(address) {
  10596. // if address has been merged, return its master's address. Assumes reconcile has been called
  10597. const range = this.hash[address];
  10598. return range && range.tl;
  10599. }
  10600. }
  10601. module.exports = Merges;
  10602. },{"../../../doc/enums":7,"../../../doc/range":10,"../../../utils/col-cache":19,"../../../utils/under-dash":26}],101:[function(require,module,exports){
  10603. "use strict";
  10604. const BaseXform = require('../base-xform');
  10605. const isDefined = attr => typeof attr !== 'undefined';
  10606. class OutlinePropertiesXform extends BaseXform {
  10607. get tag() {
  10608. return 'outlinePr';
  10609. }
  10610. render(xmlStream, model) {
  10611. if (model && (isDefined(model.summaryBelow) || isDefined(model.summaryRight))) {
  10612. xmlStream.leafNode(this.tag, {
  10613. summaryBelow: isDefined(model.summaryBelow) ? Number(model.summaryBelow) : undefined,
  10614. summaryRight: isDefined(model.summaryRight) ? Number(model.summaryRight) : undefined
  10615. });
  10616. return true;
  10617. }
  10618. return false;
  10619. }
  10620. parseOpen(node) {
  10621. if (node.name === this.tag) {
  10622. this.model = {
  10623. summaryBelow: isDefined(node.attributes.summaryBelow) ? Boolean(Number(node.attributes.summaryBelow)) : undefined,
  10624. summaryRight: isDefined(node.attributes.summaryRight) ? Boolean(Number(node.attributes.summaryRight)) : undefined
  10625. };
  10626. return true;
  10627. }
  10628. return false;
  10629. }
  10630. parseText() {}
  10631. parseClose() {
  10632. return false;
  10633. }
  10634. }
  10635. module.exports = OutlinePropertiesXform;
  10636. },{"../base-xform":32}],102:[function(require,module,exports){
  10637. "use strict";
  10638. const BaseXform = require('../base-xform');
  10639. class PageBreaksXform extends BaseXform {
  10640. get tag() {
  10641. return 'brk';
  10642. }
  10643. render(xmlStream, model) {
  10644. xmlStream.leafNode('brk', model);
  10645. }
  10646. parseOpen(node) {
  10647. if (node.name === 'brk') {
  10648. this.model = node.attributes.ref;
  10649. return true;
  10650. }
  10651. return false;
  10652. }
  10653. parseText() {}
  10654. parseClose() {
  10655. return false;
  10656. }
  10657. }
  10658. module.exports = PageBreaksXform;
  10659. },{"../base-xform":32}],103:[function(require,module,exports){
  10660. "use strict";
  10661. const _ = require('../../../utils/under-dash');
  10662. const BaseXform = require('../base-xform');
  10663. class PageMarginsXform extends BaseXform {
  10664. get tag() {
  10665. return 'pageMargins';
  10666. }
  10667. render(xmlStream, model) {
  10668. if (model) {
  10669. const attributes = {
  10670. left: model.left,
  10671. right: model.right,
  10672. top: model.top,
  10673. bottom: model.bottom,
  10674. header: model.header,
  10675. footer: model.footer
  10676. };
  10677. if (_.some(attributes, value => value !== undefined)) {
  10678. xmlStream.leafNode(this.tag, attributes);
  10679. }
  10680. }
  10681. }
  10682. parseOpen(node) {
  10683. switch (node.name) {
  10684. case this.tag:
  10685. this.model = {
  10686. left: parseFloat(node.attributes.left || 0.7),
  10687. right: parseFloat(node.attributes.right || 0.7),
  10688. top: parseFloat(node.attributes.top || 0.75),
  10689. bottom: parseFloat(node.attributes.bottom || 0.75),
  10690. header: parseFloat(node.attributes.header || 0.3),
  10691. footer: parseFloat(node.attributes.footer || 0.3)
  10692. };
  10693. return true;
  10694. default:
  10695. return false;
  10696. }
  10697. }
  10698. parseText() {}
  10699. parseClose() {
  10700. return false;
  10701. }
  10702. }
  10703. module.exports = PageMarginsXform;
  10704. },{"../../../utils/under-dash":26,"../base-xform":32}],104:[function(require,module,exports){
  10705. "use strict";
  10706. const BaseXform = require('../base-xform');
  10707. class PageSetupPropertiesXform extends BaseXform {
  10708. get tag() {
  10709. return 'pageSetUpPr';
  10710. }
  10711. render(xmlStream, model) {
  10712. if (model && model.fitToPage) {
  10713. xmlStream.leafNode(this.tag, {
  10714. fitToPage: model.fitToPage ? '1' : undefined
  10715. });
  10716. return true;
  10717. }
  10718. return false;
  10719. }
  10720. parseOpen(node) {
  10721. if (node.name === this.tag) {
  10722. this.model = {
  10723. fitToPage: node.attributes.fitToPage === '1'
  10724. };
  10725. return true;
  10726. }
  10727. return false;
  10728. }
  10729. parseText() {}
  10730. parseClose() {
  10731. return false;
  10732. }
  10733. }
  10734. module.exports = PageSetupPropertiesXform;
  10735. },{"../base-xform":32}],105:[function(require,module,exports){
  10736. "use strict";
  10737. const _ = require('../../../utils/under-dash');
  10738. const BaseXform = require('../base-xform');
  10739. function booleanToXml(model) {
  10740. return model ? '1' : undefined;
  10741. }
  10742. function pageOrderToXml(model) {
  10743. switch (model) {
  10744. case 'overThenDown':
  10745. return model;
  10746. default:
  10747. return undefined;
  10748. }
  10749. }
  10750. function cellCommentsToXml(model) {
  10751. switch (model) {
  10752. case 'atEnd':
  10753. case 'asDisplyed':
  10754. return model;
  10755. default:
  10756. return undefined;
  10757. }
  10758. }
  10759. function errorsToXml(model) {
  10760. switch (model) {
  10761. case 'dash':
  10762. case 'blank':
  10763. case 'NA':
  10764. return model;
  10765. default:
  10766. return undefined;
  10767. }
  10768. }
  10769. function pageSizeToModel(value) {
  10770. return value !== undefined ? parseInt(value, 10) : undefined;
  10771. }
  10772. class PageSetupXform extends BaseXform {
  10773. get tag() {
  10774. return 'pageSetup';
  10775. }
  10776. render(xmlStream, model) {
  10777. if (model) {
  10778. const attributes = {
  10779. paperSize: model.paperSize,
  10780. orientation: model.orientation,
  10781. horizontalDpi: model.horizontalDpi,
  10782. verticalDpi: model.verticalDpi,
  10783. pageOrder: pageOrderToXml(model.pageOrder),
  10784. blackAndWhite: booleanToXml(model.blackAndWhite),
  10785. draft: booleanToXml(model.draft),
  10786. cellComments: cellCommentsToXml(model.cellComments),
  10787. errors: errorsToXml(model.errors),
  10788. scale: model.scale,
  10789. fitToWidth: model.fitToWidth,
  10790. fitToHeight: model.fitToHeight,
  10791. firstPageNumber: model.firstPageNumber,
  10792. useFirstPageNumber: booleanToXml(model.firstPageNumber),
  10793. usePrinterDefaults: booleanToXml(model.usePrinterDefaults),
  10794. copies: model.copies
  10795. };
  10796. if (_.some(attributes, value => value !== undefined)) {
  10797. xmlStream.leafNode(this.tag, attributes);
  10798. }
  10799. }
  10800. }
  10801. parseOpen(node) {
  10802. switch (node.name) {
  10803. case this.tag:
  10804. this.model = {
  10805. paperSize: pageSizeToModel(node.attributes.paperSize),
  10806. orientation: node.attributes.orientation || 'portrait',
  10807. horizontalDpi: parseInt(node.attributes.horizontalDpi || '4294967295', 10),
  10808. verticalDpi: parseInt(node.attributes.verticalDpi || '4294967295', 10),
  10809. pageOrder: node.attributes.pageOrder || 'downThenOver',
  10810. blackAndWhite: node.attributes.blackAndWhite === '1',
  10811. draft: node.attributes.draft === '1',
  10812. cellComments: node.attributes.cellComments || 'None',
  10813. errors: node.attributes.errors || 'displayed',
  10814. scale: parseInt(node.attributes.scale || '100', 10),
  10815. fitToWidth: parseInt(node.attributes.fitToWidth || '1', 10),
  10816. fitToHeight: parseInt(node.attributes.fitToHeight || '1', 10),
  10817. firstPageNumber: parseInt(node.attributes.firstPageNumber || '1', 10),
  10818. useFirstPageNumber: node.attributes.useFirstPageNumber === '1',
  10819. usePrinterDefaults: node.attributes.usePrinterDefaults === '1',
  10820. copies: parseInt(node.attributes.copies || '1', 10)
  10821. };
  10822. return true;
  10823. default:
  10824. return false;
  10825. }
  10826. }
  10827. parseText() {}
  10828. parseClose() {
  10829. return false;
  10830. }
  10831. }
  10832. module.exports = PageSetupXform;
  10833. },{"../../../utils/under-dash":26,"../base-xform":32}],106:[function(require,module,exports){
  10834. "use strict";
  10835. const BaseXform = require('../base-xform');
  10836. class PictureXform extends BaseXform {
  10837. get tag() {
  10838. return 'picture';
  10839. }
  10840. render(xmlStream, model) {
  10841. if (model) {
  10842. xmlStream.leafNode(this.tag, {
  10843. 'r:id': model.rId
  10844. });
  10845. }
  10846. }
  10847. parseOpen(node) {
  10848. switch (node.name) {
  10849. case this.tag:
  10850. this.model = {
  10851. rId: node.attributes['r:id']
  10852. };
  10853. return true;
  10854. default:
  10855. return false;
  10856. }
  10857. }
  10858. parseText() {}
  10859. parseClose() {
  10860. return false;
  10861. }
  10862. }
  10863. module.exports = PictureXform;
  10864. },{"../base-xform":32}],107:[function(require,module,exports){
  10865. "use strict";
  10866. const _ = require('../../../utils/under-dash');
  10867. const BaseXform = require('../base-xform');
  10868. function booleanToXml(model) {
  10869. return model ? '1' : undefined;
  10870. }
  10871. class PrintOptionsXform extends BaseXform {
  10872. get tag() {
  10873. return 'printOptions';
  10874. }
  10875. render(xmlStream, model) {
  10876. if (model) {
  10877. const attributes = {
  10878. headings: booleanToXml(model.showRowColHeaders),
  10879. gridLines: booleanToXml(model.showGridLines),
  10880. horizontalCentered: booleanToXml(model.horizontalCentered),
  10881. verticalCentered: booleanToXml(model.verticalCentered)
  10882. };
  10883. if (_.some(attributes, value => value !== undefined)) {
  10884. xmlStream.leafNode(this.tag, attributes);
  10885. }
  10886. }
  10887. }
  10888. parseOpen(node) {
  10889. switch (node.name) {
  10890. case this.tag:
  10891. this.model = {
  10892. showRowColHeaders: node.attributes.headings === '1',
  10893. showGridLines: node.attributes.gridLines === '1',
  10894. horizontalCentered: node.attributes.horizontalCentered === '1',
  10895. verticalCentered: node.attributes.verticalCentered === '1'
  10896. };
  10897. return true;
  10898. default:
  10899. return false;
  10900. }
  10901. }
  10902. parseText() {}
  10903. parseClose() {
  10904. return false;
  10905. }
  10906. }
  10907. module.exports = PrintOptionsXform;
  10908. },{"../../../utils/under-dash":26,"../base-xform":32}],108:[function(require,module,exports){
  10909. 'use strict';
  10910. const PageBreaksXform = require('./page-breaks-xform');
  10911. const ListXform = require('../list-xform');
  10912. class RowBreaksXform extends ListXform {
  10913. constructor() {
  10914. const options = {
  10915. tag: 'rowBreaks',
  10916. count: true,
  10917. childXform: new PageBreaksXform()
  10918. };
  10919. super(options);
  10920. }
  10921. // get tag() { return 'rowBreaks'; }
  10922. render(xmlStream, model) {
  10923. if (model && model.length) {
  10924. xmlStream.openNode(this.tag, this.$);
  10925. if (this.count) {
  10926. xmlStream.addAttribute(this.$count, model.length);
  10927. xmlStream.addAttribute('manualBreakCount', model.length);
  10928. }
  10929. const {
  10930. childXform
  10931. } = this;
  10932. model.forEach(childModel => {
  10933. childXform.render(xmlStream, childModel);
  10934. });
  10935. xmlStream.closeNode();
  10936. } else if (this.empty) {
  10937. xmlStream.leafNode(this.tag);
  10938. }
  10939. }
  10940. }
  10941. module.exports = RowBreaksXform;
  10942. },{"../list-xform":71,"./page-breaks-xform":102}],109:[function(require,module,exports){
  10943. "use strict";
  10944. const BaseXform = require('../base-xform');
  10945. const utils = require('../../../utils/utils');
  10946. const CellXform = require('./cell-xform');
  10947. class RowXform extends BaseXform {
  10948. constructor(options) {
  10949. super();
  10950. this.maxItems = options && options.maxItems;
  10951. this.map = {
  10952. c: new CellXform()
  10953. };
  10954. }
  10955. get tag() {
  10956. return 'row';
  10957. }
  10958. prepare(model, options) {
  10959. const styleId = options.styles.addStyleModel(model.style);
  10960. if (styleId) {
  10961. model.styleId = styleId;
  10962. }
  10963. const cellXform = this.map.c;
  10964. model.cells.forEach(cellModel => {
  10965. cellXform.prepare(cellModel, options);
  10966. });
  10967. }
  10968. render(xmlStream, model, options) {
  10969. xmlStream.openNode('row');
  10970. xmlStream.addAttribute('r', model.number);
  10971. if (model.height) {
  10972. xmlStream.addAttribute('ht', model.height);
  10973. xmlStream.addAttribute('customHeight', '1');
  10974. }
  10975. if (model.hidden) {
  10976. xmlStream.addAttribute('hidden', '1');
  10977. }
  10978. if (model.min > 0 && model.max > 0 && model.min <= model.max) {
  10979. xmlStream.addAttribute('spans', `${model.min}:${model.max}`);
  10980. }
  10981. if (model.styleId) {
  10982. xmlStream.addAttribute('s', model.styleId);
  10983. xmlStream.addAttribute('customFormat', '1');
  10984. }
  10985. xmlStream.addAttribute('x14ac:dyDescent', '0.25');
  10986. if (model.outlineLevel) {
  10987. xmlStream.addAttribute('outlineLevel', model.outlineLevel);
  10988. }
  10989. if (model.collapsed) {
  10990. xmlStream.addAttribute('collapsed', '1');
  10991. }
  10992. const cellXform = this.map.c;
  10993. model.cells.forEach(cellModel => {
  10994. cellXform.render(xmlStream, cellModel, options);
  10995. });
  10996. xmlStream.closeNode();
  10997. }
  10998. parseOpen(node) {
  10999. if (this.parser) {
  11000. this.parser.parseOpen(node);
  11001. return true;
  11002. }
  11003. if (node.name === 'row') {
  11004. this.numRowsSeen += 1;
  11005. const spans = node.attributes.spans ? node.attributes.spans.split(':').map(span => parseInt(span, 10)) : [undefined, undefined];
  11006. const model = this.model = {
  11007. number: parseInt(node.attributes.r, 10),
  11008. min: spans[0],
  11009. max: spans[1],
  11010. cells: []
  11011. };
  11012. if (node.attributes.s) {
  11013. model.styleId = parseInt(node.attributes.s, 10);
  11014. }
  11015. if (utils.parseBoolean(node.attributes.hidden)) {
  11016. model.hidden = true;
  11017. }
  11018. if (utils.parseBoolean(node.attributes.bestFit)) {
  11019. model.bestFit = true;
  11020. }
  11021. if (node.attributes.ht) {
  11022. model.height = parseFloat(node.attributes.ht);
  11023. }
  11024. if (node.attributes.outlineLevel) {
  11025. model.outlineLevel = parseInt(node.attributes.outlineLevel, 10);
  11026. }
  11027. if (utils.parseBoolean(node.attributes.collapsed)) {
  11028. model.collapsed = true;
  11029. }
  11030. return true;
  11031. }
  11032. this.parser = this.map[node.name];
  11033. if (this.parser) {
  11034. this.parser.parseOpen(node);
  11035. return true;
  11036. }
  11037. return false;
  11038. }
  11039. parseText(text) {
  11040. if (this.parser) {
  11041. this.parser.parseText(text);
  11042. }
  11043. }
  11044. parseClose(name) {
  11045. if (this.parser) {
  11046. if (!this.parser.parseClose(name)) {
  11047. this.model.cells.push(this.parser.model);
  11048. if (this.maxItems && this.model.cells.length > this.maxItems) {
  11049. throw new Error(`Max column count (${this.maxItems}) exceeded`);
  11050. }
  11051. this.parser = undefined;
  11052. }
  11053. return true;
  11054. }
  11055. return false;
  11056. }
  11057. reconcile(model, options) {
  11058. model.style = model.styleId ? options.styles.getStyleModel(model.styleId) : {};
  11059. if (model.styleId !== undefined) {
  11060. model.styleId = undefined;
  11061. }
  11062. const cellXform = this.map.c;
  11063. model.cells.forEach(cellModel => {
  11064. cellXform.reconcile(cellModel, options);
  11065. });
  11066. }
  11067. }
  11068. module.exports = RowXform;
  11069. },{"../../../utils/utils":27,"../base-xform":32,"./cell-xform":73}],110:[function(require,module,exports){
  11070. "use strict";
  11071. const _ = require('../../../utils/under-dash');
  11072. const BaseXform = require('../base-xform');
  11073. class SheetFormatPropertiesXform extends BaseXform {
  11074. get tag() {
  11075. return 'sheetFormatPr';
  11076. }
  11077. render(xmlStream, model) {
  11078. if (model) {
  11079. const attributes = {
  11080. defaultRowHeight: model.defaultRowHeight,
  11081. outlineLevelRow: model.outlineLevelRow,
  11082. outlineLevelCol: model.outlineLevelCol,
  11083. 'x14ac:dyDescent': model.dyDescent
  11084. };
  11085. if (model.defaultColWidth) {
  11086. attributes.defaultColWidth = model.defaultColWidth;
  11087. }
  11088. // default value for 'defaultRowHeight' is 15, this should not be 'custom'
  11089. if (!model.defaultRowHeight || model.defaultRowHeight !== 15) {
  11090. attributes.customHeight = '1';
  11091. }
  11092. if (_.some(attributes, value => value !== undefined)) {
  11093. xmlStream.leafNode('sheetFormatPr', attributes);
  11094. }
  11095. }
  11096. }
  11097. parseOpen(node) {
  11098. if (node.name === 'sheetFormatPr') {
  11099. this.model = {
  11100. defaultRowHeight: parseFloat(node.attributes.defaultRowHeight || '0'),
  11101. dyDescent: parseFloat(node.attributes['x14ac:dyDescent'] || '0'),
  11102. outlineLevelRow: parseInt(node.attributes.outlineLevelRow || '0', 10),
  11103. outlineLevelCol: parseInt(node.attributes.outlineLevelCol || '0', 10)
  11104. };
  11105. if (node.attributes.defaultColWidth) {
  11106. this.model.defaultColWidth = parseFloat(node.attributes.defaultColWidth);
  11107. }
  11108. return true;
  11109. }
  11110. return false;
  11111. }
  11112. parseText() {}
  11113. parseClose() {
  11114. return false;
  11115. }
  11116. }
  11117. module.exports = SheetFormatPropertiesXform;
  11118. },{"../../../utils/under-dash":26,"../base-xform":32}],111:[function(require,module,exports){
  11119. "use strict";
  11120. const BaseXform = require('../base-xform');
  11121. const ColorXform = require('../style/color-xform');
  11122. const PageSetupPropertiesXform = require('./page-setup-properties-xform');
  11123. const OutlinePropertiesXform = require('./outline-properties-xform');
  11124. class SheetPropertiesXform extends BaseXform {
  11125. constructor() {
  11126. super();
  11127. this.map = {
  11128. tabColor: new ColorXform('tabColor'),
  11129. pageSetUpPr: new PageSetupPropertiesXform(),
  11130. outlinePr: new OutlinePropertiesXform()
  11131. };
  11132. }
  11133. get tag() {
  11134. return 'sheetPr';
  11135. }
  11136. render(xmlStream, model) {
  11137. if (model) {
  11138. xmlStream.addRollback();
  11139. xmlStream.openNode('sheetPr');
  11140. let inner = false;
  11141. inner = this.map.tabColor.render(xmlStream, model.tabColor) || inner;
  11142. inner = this.map.pageSetUpPr.render(xmlStream, model.pageSetup) || inner;
  11143. inner = this.map.outlinePr.render(xmlStream, model.outlineProperties) || inner;
  11144. if (inner) {
  11145. xmlStream.closeNode();
  11146. xmlStream.commit();
  11147. } else {
  11148. xmlStream.rollback();
  11149. }
  11150. }
  11151. }
  11152. parseOpen(node) {
  11153. if (this.parser) {
  11154. this.parser.parseOpen(node);
  11155. return true;
  11156. }
  11157. if (node.name === this.tag) {
  11158. this.reset();
  11159. return true;
  11160. }
  11161. if (this.map[node.name]) {
  11162. this.parser = this.map[node.name];
  11163. this.parser.parseOpen(node);
  11164. return true;
  11165. }
  11166. return false;
  11167. }
  11168. parseText(text) {
  11169. if (this.parser) {
  11170. this.parser.parseText(text);
  11171. return true;
  11172. }
  11173. return false;
  11174. }
  11175. parseClose(name) {
  11176. if (this.parser) {
  11177. if (!this.parser.parseClose(name)) {
  11178. this.parser = undefined;
  11179. }
  11180. return true;
  11181. }
  11182. if (this.map.tabColor.model || this.map.pageSetUpPr.model || this.map.outlinePr.model) {
  11183. this.model = {};
  11184. if (this.map.tabColor.model) {
  11185. this.model.tabColor = this.map.tabColor.model;
  11186. }
  11187. if (this.map.pageSetUpPr.model) {
  11188. this.model.pageSetup = this.map.pageSetUpPr.model;
  11189. }
  11190. if (this.map.outlinePr.model) {
  11191. this.model.outlineProperties = this.map.outlinePr.model;
  11192. }
  11193. } else {
  11194. this.model = null;
  11195. }
  11196. return false;
  11197. }
  11198. }
  11199. module.exports = SheetPropertiesXform;
  11200. },{"../base-xform":32,"../style/color-xform":128,"./outline-properties-xform":101,"./page-setup-properties-xform":104}],112:[function(require,module,exports){
  11201. "use strict";
  11202. const _ = require('../../../utils/under-dash');
  11203. const BaseXform = require('../base-xform');
  11204. function booleanToXml(model, value) {
  11205. return model ? value : undefined;
  11206. }
  11207. function xmlToBoolean(value, equals) {
  11208. return value === equals ? true : undefined;
  11209. }
  11210. class SheetProtectionXform extends BaseXform {
  11211. get tag() {
  11212. return 'sheetProtection';
  11213. }
  11214. render(xmlStream, model) {
  11215. if (model) {
  11216. const attributes = {
  11217. sheet: booleanToXml(model.sheet, '1'),
  11218. selectLockedCells: model.selectLockedCells === false ? '1' : undefined,
  11219. selectUnlockedCells: model.selectUnlockedCells === false ? '1' : undefined,
  11220. formatCells: booleanToXml(model.formatCells, '0'),
  11221. formatColumns: booleanToXml(model.formatColumns, '0'),
  11222. formatRows: booleanToXml(model.formatRows, '0'),
  11223. insertColumns: booleanToXml(model.insertColumns, '0'),
  11224. insertRows: booleanToXml(model.insertRows, '0'),
  11225. insertHyperlinks: booleanToXml(model.insertHyperlinks, '0'),
  11226. deleteColumns: booleanToXml(model.deleteColumns, '0'),
  11227. deleteRows: booleanToXml(model.deleteRows, '0'),
  11228. sort: booleanToXml(model.sort, '0'),
  11229. autoFilter: booleanToXml(model.autoFilter, '0'),
  11230. pivotTables: booleanToXml(model.pivotTables, '0')
  11231. };
  11232. if (model.sheet) {
  11233. attributes.algorithmName = model.algorithmName;
  11234. attributes.hashValue = model.hashValue;
  11235. attributes.saltValue = model.saltValue;
  11236. attributes.spinCount = model.spinCount;
  11237. attributes.objects = booleanToXml(model.objects === false, '1');
  11238. attributes.scenarios = booleanToXml(model.scenarios === false, '1');
  11239. }
  11240. if (_.some(attributes, value => value !== undefined)) {
  11241. xmlStream.leafNode(this.tag, attributes);
  11242. }
  11243. }
  11244. }
  11245. parseOpen(node) {
  11246. switch (node.name) {
  11247. case this.tag:
  11248. this.model = {
  11249. sheet: xmlToBoolean(node.attributes.sheet, '1'),
  11250. objects: node.attributes.objects === '1' ? false : undefined,
  11251. scenarios: node.attributes.scenarios === '1' ? false : undefined,
  11252. selectLockedCells: node.attributes.selectLockedCells === '1' ? false : undefined,
  11253. selectUnlockedCells: node.attributes.selectUnlockedCells === '1' ? false : undefined,
  11254. formatCells: xmlToBoolean(node.attributes.formatCells, '0'),
  11255. formatColumns: xmlToBoolean(node.attributes.formatColumns, '0'),
  11256. formatRows: xmlToBoolean(node.attributes.formatRows, '0'),
  11257. insertColumns: xmlToBoolean(node.attributes.insertColumns, '0'),
  11258. insertRows: xmlToBoolean(node.attributes.insertRows, '0'),
  11259. insertHyperlinks: xmlToBoolean(node.attributes.insertHyperlinks, '0'),
  11260. deleteColumns: xmlToBoolean(node.attributes.deleteColumns, '0'),
  11261. deleteRows: xmlToBoolean(node.attributes.deleteRows, '0'),
  11262. sort: xmlToBoolean(node.attributes.sort, '0'),
  11263. autoFilter: xmlToBoolean(node.attributes.autoFilter, '0'),
  11264. pivotTables: xmlToBoolean(node.attributes.pivotTables, '0')
  11265. };
  11266. if (node.attributes.algorithmName) {
  11267. this.model.algorithmName = node.attributes.algorithmName;
  11268. this.model.hashValue = node.attributes.hashValue;
  11269. this.model.saltValue = node.attributes.saltValue;
  11270. this.model.spinCount = parseInt(node.attributes.spinCount, 10);
  11271. }
  11272. return true;
  11273. default:
  11274. return false;
  11275. }
  11276. }
  11277. parseText() {}
  11278. parseClose() {
  11279. return false;
  11280. }
  11281. }
  11282. module.exports = SheetProtectionXform;
  11283. },{"../../../utils/under-dash":26,"../base-xform":32}],113:[function(require,module,exports){
  11284. "use strict";
  11285. const colCache = require('../../../utils/col-cache');
  11286. const BaseXform = require('../base-xform');
  11287. const VIEW_STATES = {
  11288. frozen: 'frozen',
  11289. frozenSplit: 'frozen',
  11290. split: 'split'
  11291. };
  11292. class SheetViewXform extends BaseXform {
  11293. get tag() {
  11294. return 'sheetView';
  11295. }
  11296. prepare(model) {
  11297. switch (model.state) {
  11298. case 'frozen':
  11299. case 'split':
  11300. break;
  11301. default:
  11302. model.state = 'normal';
  11303. break;
  11304. }
  11305. }
  11306. render(xmlStream, model) {
  11307. xmlStream.openNode('sheetView', {
  11308. workbookViewId: model.workbookViewId || 0
  11309. });
  11310. const add = function (name, value, included) {
  11311. if (included) {
  11312. xmlStream.addAttribute(name, value);
  11313. }
  11314. };
  11315. add('rightToLeft', '1', model.rightToLeft === true);
  11316. add('tabSelected', '1', model.tabSelected);
  11317. add('showRuler', '0', model.showRuler === false);
  11318. add('showRowColHeaders', '0', model.showRowColHeaders === false);
  11319. add('showGridLines', '0', model.showGridLines === false);
  11320. add('zoomScale', model.zoomScale, model.zoomScale);
  11321. add('zoomScaleNormal', model.zoomScaleNormal, model.zoomScaleNormal);
  11322. add('view', model.style, model.style);
  11323. let topLeftCell;
  11324. let xSplit;
  11325. let ySplit;
  11326. let activePane;
  11327. switch (model.state) {
  11328. case 'frozen':
  11329. xSplit = model.xSplit || 0;
  11330. ySplit = model.ySplit || 0;
  11331. topLeftCell = model.topLeftCell || colCache.getAddress(ySplit + 1, xSplit + 1).address;
  11332. activePane = model.xSplit && model.ySplit && 'bottomRight' || model.xSplit && 'topRight' || 'bottomLeft';
  11333. xmlStream.leafNode('pane', {
  11334. xSplit: model.xSplit || undefined,
  11335. ySplit: model.ySplit || undefined,
  11336. topLeftCell,
  11337. activePane,
  11338. state: 'frozen'
  11339. });
  11340. xmlStream.leafNode('selection', {
  11341. pane: activePane,
  11342. activeCell: model.activeCell,
  11343. sqref: model.activeCell
  11344. });
  11345. break;
  11346. case 'split':
  11347. if (model.activePane === 'topLeft') {
  11348. model.activePane = undefined;
  11349. }
  11350. xmlStream.leafNode('pane', {
  11351. xSplit: model.xSplit || undefined,
  11352. ySplit: model.ySplit || undefined,
  11353. topLeftCell: model.topLeftCell,
  11354. activePane: model.activePane
  11355. });
  11356. xmlStream.leafNode('selection', {
  11357. pane: model.activePane,
  11358. activeCell: model.activeCell,
  11359. sqref: model.activeCell
  11360. });
  11361. break;
  11362. case 'normal':
  11363. if (model.activeCell) {
  11364. xmlStream.leafNode('selection', {
  11365. activeCell: model.activeCell,
  11366. sqref: model.activeCell
  11367. });
  11368. }
  11369. break;
  11370. default:
  11371. break;
  11372. }
  11373. xmlStream.closeNode();
  11374. }
  11375. parseOpen(node) {
  11376. switch (node.name) {
  11377. case 'sheetView':
  11378. this.sheetView = {
  11379. workbookViewId: parseInt(node.attributes.workbookViewId, 10),
  11380. rightToLeft: node.attributes.rightToLeft === '1',
  11381. tabSelected: node.attributes.tabSelected === '1',
  11382. showRuler: !(node.attributes.showRuler === '0'),
  11383. showRowColHeaders: !(node.attributes.showRowColHeaders === '0'),
  11384. showGridLines: !(node.attributes.showGridLines === '0'),
  11385. zoomScale: parseInt(node.attributes.zoomScale || '100', 10),
  11386. zoomScaleNormal: parseInt(node.attributes.zoomScaleNormal || '100', 10),
  11387. style: node.attributes.view
  11388. };
  11389. this.pane = undefined;
  11390. this.selections = {};
  11391. return true;
  11392. case 'pane':
  11393. this.pane = {
  11394. xSplit: parseInt(node.attributes.xSplit || '0', 10),
  11395. ySplit: parseInt(node.attributes.ySplit || '0', 10),
  11396. topLeftCell: node.attributes.topLeftCell,
  11397. activePane: node.attributes.activePane || 'topLeft',
  11398. state: node.attributes.state
  11399. };
  11400. return true;
  11401. case 'selection':
  11402. {
  11403. const name = node.attributes.pane || 'topLeft';
  11404. this.selections[name] = {
  11405. pane: name,
  11406. activeCell: node.attributes.activeCell
  11407. };
  11408. return true;
  11409. }
  11410. default:
  11411. return false;
  11412. }
  11413. }
  11414. parseText() {}
  11415. parseClose(name) {
  11416. let model;
  11417. let selection;
  11418. switch (name) {
  11419. case 'sheetView':
  11420. if (this.sheetView && this.pane) {
  11421. model = this.model = {
  11422. workbookViewId: this.sheetView.workbookViewId,
  11423. rightToLeft: this.sheetView.rightToLeft,
  11424. state: VIEW_STATES[this.pane.state] || 'split',
  11425. // split is default
  11426. xSplit: this.pane.xSplit,
  11427. ySplit: this.pane.ySplit,
  11428. topLeftCell: this.pane.topLeftCell,
  11429. showRuler: this.sheetView.showRuler,
  11430. showRowColHeaders: this.sheetView.showRowColHeaders,
  11431. showGridLines: this.sheetView.showGridLines,
  11432. zoomScale: this.sheetView.zoomScale,
  11433. zoomScaleNormal: this.sheetView.zoomScaleNormal
  11434. };
  11435. if (this.model.state === 'split') {
  11436. model.activePane = this.pane.activePane;
  11437. }
  11438. selection = this.selections[this.pane.activePane];
  11439. if (selection && selection.activeCell) {
  11440. model.activeCell = selection.activeCell;
  11441. }
  11442. if (this.sheetView.style) {
  11443. model.style = this.sheetView.style;
  11444. }
  11445. } else {
  11446. model = this.model = {
  11447. workbookViewId: this.sheetView.workbookViewId,
  11448. rightToLeft: this.sheetView.rightToLeft,
  11449. state: 'normal',
  11450. showRuler: this.sheetView.showRuler,
  11451. showRowColHeaders: this.sheetView.showRowColHeaders,
  11452. showGridLines: this.sheetView.showGridLines,
  11453. zoomScale: this.sheetView.zoomScale,
  11454. zoomScaleNormal: this.sheetView.zoomScaleNormal
  11455. };
  11456. selection = this.selections.topLeft;
  11457. if (selection && selection.activeCell) {
  11458. model.activeCell = selection.activeCell;
  11459. }
  11460. if (this.sheetView.style) {
  11461. model.style = this.sheetView.style;
  11462. }
  11463. }
  11464. return false;
  11465. default:
  11466. return true;
  11467. }
  11468. }
  11469. reconcile() {}
  11470. }
  11471. module.exports = SheetViewXform;
  11472. },{"../../../utils/col-cache":19,"../base-xform":32}],114:[function(require,module,exports){
  11473. "use strict";
  11474. const BaseXform = require('../base-xform');
  11475. class TablePartXform extends BaseXform {
  11476. get tag() {
  11477. return 'tablePart';
  11478. }
  11479. render(xmlStream, model) {
  11480. if (model) {
  11481. xmlStream.leafNode(this.tag, {
  11482. 'r:id': model.rId
  11483. });
  11484. }
  11485. }
  11486. parseOpen(node) {
  11487. switch (node.name) {
  11488. case this.tag:
  11489. this.model = {
  11490. rId: node.attributes['r:id']
  11491. };
  11492. return true;
  11493. default:
  11494. return false;
  11495. }
  11496. }
  11497. parseText() {}
  11498. parseClose() {
  11499. return false;
  11500. }
  11501. }
  11502. module.exports = TablePartXform;
  11503. },{"../base-xform":32}],115:[function(require,module,exports){
  11504. "use strict";
  11505. const _ = require('../../../utils/under-dash');
  11506. const colCache = require('../../../utils/col-cache');
  11507. const XmlStream = require('../../../utils/xml-stream');
  11508. const RelType = require('../../rel-type');
  11509. const Merges = require('./merges');
  11510. const BaseXform = require('../base-xform');
  11511. const ListXform = require('../list-xform');
  11512. const RowXform = require('./row-xform');
  11513. const ColXform = require('./col-xform');
  11514. const DimensionXform = require('./dimension-xform');
  11515. const HyperlinkXform = require('./hyperlink-xform');
  11516. const MergeCellXform = require('./merge-cell-xform');
  11517. const DataValidationsXform = require('./data-validations-xform');
  11518. const SheetPropertiesXform = require('./sheet-properties-xform');
  11519. const SheetFormatPropertiesXform = require('./sheet-format-properties-xform');
  11520. const SheetViewXform = require('./sheet-view-xform');
  11521. const SheetProtectionXform = require('./sheet-protection-xform');
  11522. const PageMarginsXform = require('./page-margins-xform');
  11523. const PageSetupXform = require('./page-setup-xform');
  11524. const PrintOptionsXform = require('./print-options-xform');
  11525. const AutoFilterXform = require('./auto-filter-xform');
  11526. const PictureXform = require('./picture-xform');
  11527. const DrawingXform = require('./drawing-xform');
  11528. const TablePartXform = require('./table-part-xform');
  11529. const RowBreaksXform = require('./row-breaks-xform');
  11530. const HeaderFooterXform = require('./header-footer-xform');
  11531. const ConditionalFormattingsXform = require('./cf/conditional-formattings-xform');
  11532. const ExtListXform = require('./ext-lst-xform');
  11533. const mergeRule = (rule, extRule) => {
  11534. Object.keys(extRule).forEach(key => {
  11535. const value = rule[key];
  11536. const extValue = extRule[key];
  11537. if (value === undefined && extValue !== undefined) {
  11538. rule[key] = extValue;
  11539. }
  11540. });
  11541. };
  11542. const mergeConditionalFormattings = (model, extModel) => {
  11543. // conditional formattings are rendered in worksheet.conditionalFormatting and also in
  11544. // worksheet.extLst.ext.x14:conditionalFormattings
  11545. // some (e.g. dataBar) are even spread across both!
  11546. if (!extModel || !extModel.length) {
  11547. return model;
  11548. }
  11549. if (!model || !model.length) {
  11550. return extModel;
  11551. }
  11552. // index model rules by x14Id
  11553. const cfMap = {};
  11554. const ruleMap = {};
  11555. model.forEach(cf => {
  11556. cfMap[cf.ref] = cf;
  11557. cf.rules.forEach(rule => {
  11558. const {
  11559. x14Id
  11560. } = rule;
  11561. if (x14Id) {
  11562. ruleMap[x14Id] = rule;
  11563. }
  11564. });
  11565. });
  11566. extModel.forEach(extCf => {
  11567. extCf.rules.forEach(extRule => {
  11568. const rule = ruleMap[extRule.x14Id];
  11569. if (rule) {
  11570. // merge with matching rule
  11571. mergeRule(rule, extRule);
  11572. } else if (cfMap[extCf.ref]) {
  11573. // reuse existing cf ref
  11574. cfMap[extCf.ref].rules.push(extRule);
  11575. } else {
  11576. // create new cf
  11577. model.push({
  11578. ref: extCf.ref,
  11579. rules: [extRule]
  11580. });
  11581. }
  11582. });
  11583. });
  11584. // need to cope with rules in extModel that don't exist in model
  11585. return model;
  11586. };
  11587. class WorkSheetXform extends BaseXform {
  11588. constructor(options) {
  11589. super();
  11590. const {
  11591. maxRows,
  11592. maxCols,
  11593. ignoreNodes
  11594. } = options || {};
  11595. this.ignoreNodes = ignoreNodes || [];
  11596. this.map = {
  11597. sheetPr: new SheetPropertiesXform(),
  11598. dimension: new DimensionXform(),
  11599. sheetViews: new ListXform({
  11600. tag: 'sheetViews',
  11601. count: false,
  11602. childXform: new SheetViewXform()
  11603. }),
  11604. sheetFormatPr: new SheetFormatPropertiesXform(),
  11605. cols: new ListXform({
  11606. tag: 'cols',
  11607. count: false,
  11608. childXform: new ColXform()
  11609. }),
  11610. sheetData: new ListXform({
  11611. tag: 'sheetData',
  11612. count: false,
  11613. empty: true,
  11614. childXform: new RowXform({
  11615. maxItems: maxCols
  11616. }),
  11617. maxItems: maxRows
  11618. }),
  11619. autoFilter: new AutoFilterXform(),
  11620. mergeCells: new ListXform({
  11621. tag: 'mergeCells',
  11622. count: true,
  11623. childXform: new MergeCellXform()
  11624. }),
  11625. rowBreaks: new RowBreaksXform(),
  11626. hyperlinks: new ListXform({
  11627. tag: 'hyperlinks',
  11628. count: false,
  11629. childXform: new HyperlinkXform()
  11630. }),
  11631. pageMargins: new PageMarginsXform(),
  11632. dataValidations: new DataValidationsXform(),
  11633. pageSetup: new PageSetupXform(),
  11634. headerFooter: new HeaderFooterXform(),
  11635. printOptions: new PrintOptionsXform(),
  11636. picture: new PictureXform(),
  11637. drawing: new DrawingXform(),
  11638. sheetProtection: new SheetProtectionXform(),
  11639. tableParts: new ListXform({
  11640. tag: 'tableParts',
  11641. count: true,
  11642. childXform: new TablePartXform()
  11643. }),
  11644. conditionalFormatting: new ConditionalFormattingsXform(),
  11645. extLst: new ExtListXform()
  11646. };
  11647. }
  11648. prepare(model, options) {
  11649. options.merges = new Merges();
  11650. model.hyperlinks = options.hyperlinks = [];
  11651. model.comments = options.comments = [];
  11652. options.formulae = {};
  11653. options.siFormulae = 0;
  11654. this.map.cols.prepare(model.cols, options);
  11655. this.map.sheetData.prepare(model.rows, options);
  11656. this.map.conditionalFormatting.prepare(model.conditionalFormattings, options);
  11657. model.mergeCells = options.merges.mergeCells;
  11658. // prepare relationships
  11659. const rels = model.rels = [];
  11660. function nextRid(r) {
  11661. return `rId${r.length + 1}`;
  11662. }
  11663. model.hyperlinks.forEach(hyperlink => {
  11664. const rId = nextRid(rels);
  11665. hyperlink.rId = rId;
  11666. rels.push({
  11667. Id: rId,
  11668. Type: RelType.Hyperlink,
  11669. Target: hyperlink.target,
  11670. TargetMode: 'External'
  11671. });
  11672. });
  11673. // prepare comment relationships
  11674. if (model.comments.length > 0) {
  11675. const comment = {
  11676. Id: nextRid(rels),
  11677. Type: RelType.Comments,
  11678. Target: `../comments${model.id}.xml`
  11679. };
  11680. rels.push(comment);
  11681. const vmlDrawing = {
  11682. Id: nextRid(rels),
  11683. Type: RelType.VmlDrawing,
  11684. Target: `../drawings/vmlDrawing${model.id}.vml`
  11685. };
  11686. rels.push(vmlDrawing);
  11687. model.comments.forEach(item => {
  11688. item.refAddress = colCache.decodeAddress(item.ref);
  11689. });
  11690. options.commentRefs.push({
  11691. commentName: `comments${model.id}`,
  11692. vmlDrawing: `vmlDrawing${model.id}`
  11693. });
  11694. }
  11695. const drawingRelsHash = [];
  11696. let bookImage;
  11697. model.media.forEach(medium => {
  11698. if (medium.type === 'background') {
  11699. const rId = nextRid(rels);
  11700. bookImage = options.media[medium.imageId];
  11701. rels.push({
  11702. Id: rId,
  11703. Type: RelType.Image,
  11704. Target: `../media/${bookImage.name}.${bookImage.extension}`
  11705. });
  11706. model.background = {
  11707. rId
  11708. };
  11709. model.image = options.media[medium.imageId];
  11710. } else if (medium.type === 'image') {
  11711. let {
  11712. drawing
  11713. } = model;
  11714. bookImage = options.media[medium.imageId];
  11715. if (!drawing) {
  11716. drawing = model.drawing = {
  11717. rId: nextRid(rels),
  11718. name: `drawing${++options.drawingsCount}`,
  11719. anchors: [],
  11720. rels: []
  11721. };
  11722. options.drawings.push(drawing);
  11723. rels.push({
  11724. Id: drawing.rId,
  11725. Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing',
  11726. Target: `../drawings/${drawing.name}.xml`
  11727. });
  11728. }
  11729. let rIdImage = this.preImageId === medium.imageId ? drawingRelsHash[medium.imageId] : drawingRelsHash[drawing.rels.length];
  11730. if (!rIdImage) {
  11731. rIdImage = nextRid(drawing.rels);
  11732. drawingRelsHash[drawing.rels.length] = rIdImage;
  11733. drawing.rels.push({
  11734. Id: rIdImage,
  11735. Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
  11736. Target: `../media/${bookImage.name}.${bookImage.extension}`
  11737. });
  11738. }
  11739. const anchor = {
  11740. picture: {
  11741. rId: rIdImage
  11742. },
  11743. range: medium.range
  11744. };
  11745. if (medium.hyperlinks && medium.hyperlinks.hyperlink) {
  11746. const rIdHyperLink = nextRid(drawing.rels);
  11747. drawingRelsHash[drawing.rels.length] = rIdHyperLink;
  11748. anchor.picture.hyperlinks = {
  11749. tooltip: medium.hyperlinks.tooltip,
  11750. rId: rIdHyperLink
  11751. };
  11752. drawing.rels.push({
  11753. Id: rIdHyperLink,
  11754. Type: RelType.Hyperlink,
  11755. Target: medium.hyperlinks.hyperlink,
  11756. TargetMode: 'External'
  11757. });
  11758. }
  11759. this.preImageId = medium.imageId;
  11760. drawing.anchors.push(anchor);
  11761. }
  11762. });
  11763. // prepare tables
  11764. model.tables.forEach(table => {
  11765. // relationships
  11766. const rId = nextRid(rels);
  11767. table.rId = rId;
  11768. rels.push({
  11769. Id: rId,
  11770. Type: RelType.Table,
  11771. Target: `../tables/${table.target}`
  11772. });
  11773. // dynamic styles
  11774. table.columns.forEach(column => {
  11775. const {
  11776. style
  11777. } = column;
  11778. if (style) {
  11779. column.dxfId = options.styles.addDxfStyle(style);
  11780. }
  11781. });
  11782. });
  11783. // prepare ext items
  11784. this.map.extLst.prepare(model, options);
  11785. }
  11786. render(xmlStream, model) {
  11787. xmlStream.openXml(XmlStream.StdDocAttributes);
  11788. xmlStream.openNode('worksheet', WorkSheetXform.WORKSHEET_ATTRIBUTES);
  11789. const sheetFormatPropertiesModel = model.properties ? {
  11790. defaultRowHeight: model.properties.defaultRowHeight,
  11791. dyDescent: model.properties.dyDescent,
  11792. outlineLevelCol: model.properties.outlineLevelCol,
  11793. outlineLevelRow: model.properties.outlineLevelRow
  11794. } : undefined;
  11795. if (model.properties && model.properties.defaultColWidth) {
  11796. sheetFormatPropertiesModel.defaultColWidth = model.properties.defaultColWidth;
  11797. }
  11798. const sheetPropertiesModel = {
  11799. outlineProperties: model.properties && model.properties.outlineProperties,
  11800. tabColor: model.properties && model.properties.tabColor,
  11801. pageSetup: model.pageSetup && model.pageSetup.fitToPage ? {
  11802. fitToPage: model.pageSetup.fitToPage
  11803. } : undefined
  11804. };
  11805. const pageMarginsModel = model.pageSetup && model.pageSetup.margins;
  11806. const printOptionsModel = {
  11807. showRowColHeaders: model.pageSetup && model.pageSetup.showRowColHeaders,
  11808. showGridLines: model.pageSetup && model.pageSetup.showGridLines,
  11809. horizontalCentered: model.pageSetup && model.pageSetup.horizontalCentered,
  11810. verticalCentered: model.pageSetup && model.pageSetup.verticalCentered
  11811. };
  11812. const sheetProtectionModel = model.sheetProtection;
  11813. this.map.sheetPr.render(xmlStream, sheetPropertiesModel);
  11814. this.map.dimension.render(xmlStream, model.dimensions);
  11815. this.map.sheetViews.render(xmlStream, model.views);
  11816. this.map.sheetFormatPr.render(xmlStream, sheetFormatPropertiesModel);
  11817. this.map.cols.render(xmlStream, model.cols);
  11818. this.map.sheetData.render(xmlStream, model.rows);
  11819. this.map.sheetProtection.render(xmlStream, sheetProtectionModel); // Note: must be after sheetData and before autoFilter
  11820. this.map.autoFilter.render(xmlStream, model.autoFilter);
  11821. this.map.mergeCells.render(xmlStream, model.mergeCells);
  11822. this.map.conditionalFormatting.render(xmlStream, model.conditionalFormattings); // Note: must be before dataValidations
  11823. this.map.dataValidations.render(xmlStream, model.dataValidations);
  11824. // For some reason hyperlinks have to be after the data validations
  11825. this.map.hyperlinks.render(xmlStream, model.hyperlinks);
  11826. this.map.printOptions.render(xmlStream, printOptionsModel); // Note: must be before pageMargins
  11827. this.map.pageMargins.render(xmlStream, pageMarginsModel);
  11828. this.map.pageSetup.render(xmlStream, model.pageSetup);
  11829. this.map.headerFooter.render(xmlStream, model.headerFooter);
  11830. this.map.rowBreaks.render(xmlStream, model.rowBreaks);
  11831. this.map.drawing.render(xmlStream, model.drawing); // Note: must be after rowBreaks
  11832. this.map.picture.render(xmlStream, model.background); // Note: must be after drawing
  11833. this.map.tableParts.render(xmlStream, model.tables);
  11834. this.map.extLst.render(xmlStream, model);
  11835. if (model.rels) {
  11836. // add a <legacyDrawing /> node for each comment
  11837. model.rels.forEach(rel => {
  11838. if (rel.Type === RelType.VmlDrawing) {
  11839. xmlStream.leafNode('legacyDrawing', {
  11840. 'r:id': rel.Id
  11841. });
  11842. }
  11843. });
  11844. }
  11845. xmlStream.closeNode();
  11846. }
  11847. parseOpen(node) {
  11848. if (this.parser) {
  11849. this.parser.parseOpen(node);
  11850. return true;
  11851. }
  11852. if (node.name === 'worksheet') {
  11853. _.each(this.map, xform => {
  11854. xform.reset();
  11855. });
  11856. return true;
  11857. }
  11858. if (this.map[node.name] && !this.ignoreNodes.includes(node.name)) {
  11859. this.parser = this.map[node.name];
  11860. this.parser.parseOpen(node);
  11861. }
  11862. return true;
  11863. }
  11864. parseText(text) {
  11865. if (this.parser) {
  11866. this.parser.parseText(text);
  11867. }
  11868. }
  11869. parseClose(name) {
  11870. if (this.parser) {
  11871. if (!this.parser.parseClose(name)) {
  11872. this.parser = undefined;
  11873. }
  11874. return true;
  11875. }
  11876. switch (name) {
  11877. case 'worksheet':
  11878. {
  11879. const properties = this.map.sheetFormatPr.model || {};
  11880. if (this.map.sheetPr.model && this.map.sheetPr.model.tabColor) {
  11881. properties.tabColor = this.map.sheetPr.model.tabColor;
  11882. }
  11883. if (this.map.sheetPr.model && this.map.sheetPr.model.outlineProperties) {
  11884. properties.outlineProperties = this.map.sheetPr.model.outlineProperties;
  11885. }
  11886. const sheetProperties = {
  11887. fitToPage: this.map.sheetPr.model && this.map.sheetPr.model.pageSetup && this.map.sheetPr.model.pageSetup.fitToPage || false,
  11888. margins: this.map.pageMargins.model
  11889. };
  11890. const pageSetup = Object.assign(sheetProperties, this.map.pageSetup.model, this.map.printOptions.model);
  11891. const conditionalFormattings = mergeConditionalFormattings(this.map.conditionalFormatting.model, this.map.extLst.model && this.map.extLst.model['x14:conditionalFormattings']);
  11892. this.model = {
  11893. dimensions: this.map.dimension.model,
  11894. cols: this.map.cols.model,
  11895. rows: this.map.sheetData.model,
  11896. mergeCells: this.map.mergeCells.model,
  11897. hyperlinks: this.map.hyperlinks.model,
  11898. dataValidations: this.map.dataValidations.model,
  11899. properties,
  11900. views: this.map.sheetViews.model,
  11901. pageSetup,
  11902. headerFooter: this.map.headerFooter.model,
  11903. background: this.map.picture.model,
  11904. drawing: this.map.drawing.model,
  11905. tables: this.map.tableParts.model,
  11906. conditionalFormattings
  11907. };
  11908. if (this.map.autoFilter.model) {
  11909. this.model.autoFilter = this.map.autoFilter.model;
  11910. }
  11911. if (this.map.sheetProtection.model) {
  11912. this.model.sheetProtection = this.map.sheetProtection.model;
  11913. }
  11914. return false;
  11915. }
  11916. default:
  11917. // not quite sure how we get here!
  11918. return true;
  11919. }
  11920. }
  11921. reconcile(model, options) {
  11922. // options.merges = new Merges();
  11923. // options.merges.reconcile(model.mergeCells, model.rows);
  11924. const rels = (model.relationships || []).reduce((h, rel) => {
  11925. h[rel.Id] = rel;
  11926. if (rel.Type === RelType.Comments) {
  11927. model.comments = options.comments[rel.Target].comments;
  11928. }
  11929. if (rel.Type === RelType.VmlDrawing && model.comments && model.comments.length) {
  11930. const vmlComment = options.vmlDrawings[rel.Target].comments;
  11931. model.comments.forEach((comment, index) => {
  11932. comment.note = Object.assign({}, comment.note, vmlComment[index]);
  11933. });
  11934. }
  11935. return h;
  11936. }, {});
  11937. options.commentsMap = (model.comments || []).reduce((h, comment) => {
  11938. if (comment.ref) {
  11939. h[comment.ref] = comment;
  11940. }
  11941. return h;
  11942. }, {});
  11943. options.hyperlinkMap = (model.hyperlinks || []).reduce((h, hyperlink) => {
  11944. if (hyperlink.rId) {
  11945. h[hyperlink.address] = rels[hyperlink.rId].Target;
  11946. }
  11947. return h;
  11948. }, {});
  11949. options.formulae = {};
  11950. // compact the rows and cells
  11951. model.rows = model.rows && model.rows.filter(Boolean) || [];
  11952. model.rows.forEach(row => {
  11953. row.cells = row.cells && row.cells.filter(Boolean) || [];
  11954. });
  11955. this.map.cols.reconcile(model.cols, options);
  11956. this.map.sheetData.reconcile(model.rows, options);
  11957. this.map.conditionalFormatting.reconcile(model.conditionalFormattings, options);
  11958. model.media = [];
  11959. if (model.drawing) {
  11960. const drawingRel = rels[model.drawing.rId];
  11961. const match = drawingRel.Target.match(/\/drawings\/([a-zA-Z0-9]+)[.][a-zA-Z]{3,4}$/);
  11962. if (match) {
  11963. const drawingName = match[1];
  11964. const drawing = options.drawings[drawingName];
  11965. drawing.anchors.forEach(anchor => {
  11966. if (anchor.medium) {
  11967. const image = {
  11968. type: 'image',
  11969. imageId: anchor.medium.index,
  11970. range: anchor.range,
  11971. hyperlinks: anchor.picture.hyperlinks
  11972. };
  11973. model.media.push(image);
  11974. }
  11975. });
  11976. }
  11977. }
  11978. const backgroundRel = model.background && rels[model.background.rId];
  11979. if (backgroundRel) {
  11980. const target = backgroundRel.Target.split('/media/')[1];
  11981. const imageId = options.mediaIndex && options.mediaIndex[target];
  11982. if (imageId !== undefined) {
  11983. model.media.push({
  11984. type: 'background',
  11985. imageId
  11986. });
  11987. }
  11988. }
  11989. model.tables = (model.tables || []).map(tablePart => {
  11990. const rel = rels[tablePart.rId];
  11991. return options.tables[rel.Target];
  11992. });
  11993. delete model.relationships;
  11994. delete model.hyperlinks;
  11995. delete model.comments;
  11996. }
  11997. }
  11998. WorkSheetXform.WORKSHEET_ATTRIBUTES = {
  11999. xmlns: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  12000. 'xmlns:r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  12001. 'xmlns:mc': 'http://schemas.openxmlformats.org/markup-compatibility/2006',
  12002. 'mc:Ignorable': 'x14ac',
  12003. 'xmlns:x14ac': 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac'
  12004. };
  12005. module.exports = WorkSheetXform;
  12006. },{"../../../utils/col-cache":19,"../../../utils/under-dash":26,"../../../utils/xml-stream":28,"../../rel-type":31,"../base-xform":32,"../list-xform":71,"./auto-filter-xform":72,"./cf/conditional-formattings-xform":87,"./col-xform":92,"./data-validations-xform":93,"./dimension-xform":94,"./drawing-xform":95,"./ext-lst-xform":96,"./header-footer-xform":97,"./hyperlink-xform":98,"./merge-cell-xform":99,"./merges":100,"./page-margins-xform":103,"./page-setup-xform":105,"./picture-xform":106,"./print-options-xform":107,"./row-breaks-xform":108,"./row-xform":109,"./sheet-format-properties-xform":110,"./sheet-properties-xform":111,"./sheet-protection-xform":112,"./sheet-view-xform":113,"./table-part-xform":114}],116:[function(require,module,exports){
  12007. "use strict";
  12008. const BaseXform = require('../base-xform');
  12009. class BooleanXform extends BaseXform {
  12010. constructor(options) {
  12011. super();
  12012. this.tag = options.tag;
  12013. this.attr = options.attr;
  12014. }
  12015. render(xmlStream, model) {
  12016. if (model) {
  12017. xmlStream.openNode(this.tag);
  12018. xmlStream.closeNode();
  12019. }
  12020. }
  12021. parseOpen(node) {
  12022. if (node.name === this.tag) {
  12023. this.model = true;
  12024. }
  12025. }
  12026. parseText() {}
  12027. parseClose() {
  12028. return false;
  12029. }
  12030. }
  12031. module.exports = BooleanXform;
  12032. },{"../base-xform":32}],117:[function(require,module,exports){
  12033. "use strict";
  12034. const BaseXform = require('../base-xform');
  12035. class DateXform extends BaseXform {
  12036. constructor(options) {
  12037. super();
  12038. this.tag = options.tag;
  12039. this.attr = options.attr;
  12040. this.attrs = options.attrs;
  12041. this._format = options.format || function (dt) {
  12042. try {
  12043. if (Number.isNaN(dt.getTime())) return '';
  12044. return dt.toISOString();
  12045. } catch (e) {
  12046. return '';
  12047. }
  12048. };
  12049. this._parse = options.parse || function (str) {
  12050. return new Date(str);
  12051. };
  12052. }
  12053. render(xmlStream, model) {
  12054. if (model) {
  12055. xmlStream.openNode(this.tag);
  12056. if (this.attrs) {
  12057. xmlStream.addAttributes(this.attrs);
  12058. }
  12059. if (this.attr) {
  12060. xmlStream.addAttribute(this.attr, this._format(model));
  12061. } else {
  12062. xmlStream.writeText(this._format(model));
  12063. }
  12064. xmlStream.closeNode();
  12065. }
  12066. }
  12067. parseOpen(node) {
  12068. if (node.name === this.tag) {
  12069. if (this.attr) {
  12070. this.model = this._parse(node.attributes[this.attr]);
  12071. } else {
  12072. this.text = [];
  12073. }
  12074. }
  12075. }
  12076. parseText(text) {
  12077. if (!this.attr) {
  12078. this.text.push(text);
  12079. }
  12080. }
  12081. parseClose() {
  12082. if (!this.attr) {
  12083. this.model = this._parse(this.text.join(''));
  12084. }
  12085. return false;
  12086. }
  12087. }
  12088. module.exports = DateXform;
  12089. },{"../base-xform":32}],118:[function(require,module,exports){
  12090. "use strict";
  12091. const BaseXform = require('../base-xform');
  12092. class IntegerXform extends BaseXform {
  12093. constructor(options) {
  12094. super();
  12095. this.tag = options.tag;
  12096. this.attr = options.attr;
  12097. this.attrs = options.attrs;
  12098. // option to render zero
  12099. this.zero = options.zero;
  12100. }
  12101. render(xmlStream, model) {
  12102. // int is different to float in that zero is not rendered
  12103. if (model || this.zero) {
  12104. xmlStream.openNode(this.tag);
  12105. if (this.attrs) {
  12106. xmlStream.addAttributes(this.attrs);
  12107. }
  12108. if (this.attr) {
  12109. xmlStream.addAttribute(this.attr, model);
  12110. } else {
  12111. xmlStream.writeText(model);
  12112. }
  12113. xmlStream.closeNode();
  12114. }
  12115. }
  12116. parseOpen(node) {
  12117. if (node.name === this.tag) {
  12118. if (this.attr) {
  12119. this.model = parseInt(node.attributes[this.attr], 10);
  12120. } else {
  12121. this.text = [];
  12122. }
  12123. return true;
  12124. }
  12125. return false;
  12126. }
  12127. parseText(text) {
  12128. if (!this.attr) {
  12129. this.text.push(text);
  12130. }
  12131. }
  12132. parseClose() {
  12133. if (!this.attr) {
  12134. this.model = parseInt(this.text.join('') || 0, 10);
  12135. }
  12136. return false;
  12137. }
  12138. }
  12139. module.exports = IntegerXform;
  12140. },{"../base-xform":32}],119:[function(require,module,exports){
  12141. "use strict";
  12142. const BaseXform = require('../base-xform');
  12143. class StringXform extends BaseXform {
  12144. constructor(options) {
  12145. super();
  12146. this.tag = options.tag;
  12147. this.attr = options.attr;
  12148. this.attrs = options.attrs;
  12149. }
  12150. render(xmlStream, model) {
  12151. if (model !== undefined) {
  12152. xmlStream.openNode(this.tag);
  12153. if (this.attrs) {
  12154. xmlStream.addAttributes(this.attrs);
  12155. }
  12156. if (this.attr) {
  12157. xmlStream.addAttribute(this.attr, model);
  12158. } else {
  12159. xmlStream.writeText(model);
  12160. }
  12161. xmlStream.closeNode();
  12162. }
  12163. }
  12164. parseOpen(node) {
  12165. if (node.name === this.tag) {
  12166. if (this.attr) {
  12167. this.model = node.attributes[this.attr];
  12168. } else {
  12169. this.text = [];
  12170. }
  12171. }
  12172. }
  12173. parseText(text) {
  12174. if (!this.attr) {
  12175. this.text.push(text);
  12176. }
  12177. }
  12178. parseClose() {
  12179. if (!this.attr) {
  12180. this.model = this.text.join('');
  12181. }
  12182. return false;
  12183. }
  12184. }
  12185. module.exports = StringXform;
  12186. },{"../base-xform":32}],120:[function(require,module,exports){
  12187. "use strict";
  12188. const BaseXform = require('./base-xform');
  12189. const XmlStream = require('../../utils/xml-stream');
  12190. // const model = {
  12191. // tag: 'name',
  12192. // $: {attr: 'value'},
  12193. // c: [
  12194. // { tag: 'child' }
  12195. // ],
  12196. // t: 'some text'
  12197. // };
  12198. function build(xmlStream, model) {
  12199. xmlStream.openNode(model.tag, model.$);
  12200. if (model.c) {
  12201. model.c.forEach(child => {
  12202. build(xmlStream, child);
  12203. });
  12204. }
  12205. if (model.t) {
  12206. xmlStream.writeText(model.t);
  12207. }
  12208. xmlStream.closeNode();
  12209. }
  12210. class StaticXform extends BaseXform {
  12211. constructor(model) {
  12212. super();
  12213. // This class is an optimisation for static (unimportant and unchanging) xml
  12214. // It is stateless - apart from its static model and so can be used as a singleton
  12215. // Being stateless - it will only track entry to and exit from it's root xml tag during parsing and nothing else
  12216. // Known issues:
  12217. // since stateless - parseOpen always returns true. Parent xform must know when to start using this xform
  12218. // if the root tag is recursive, the parsing will behave unpredictably
  12219. this._model = model;
  12220. }
  12221. render(xmlStream) {
  12222. if (!this._xml) {
  12223. const stream = new XmlStream();
  12224. build(stream, this._model);
  12225. this._xml = stream.xml;
  12226. }
  12227. xmlStream.writeXml(this._xml);
  12228. }
  12229. parseOpen() {
  12230. return true;
  12231. }
  12232. parseText() {}
  12233. parseClose(name) {
  12234. switch (name) {
  12235. case this._model.tag:
  12236. return false;
  12237. default:
  12238. return true;
  12239. }
  12240. }
  12241. }
  12242. module.exports = StaticXform;
  12243. },{"../../utils/xml-stream":28,"./base-xform":32}],121:[function(require,module,exports){
  12244. "use strict";
  12245. const TextXform = require('./text-xform');
  12246. const RichTextXform = require('./rich-text-xform');
  12247. const BaseXform = require('../base-xform');
  12248. // <rPh sb="0" eb="1">
  12249. // <t>(its pronounciation in KATAKANA)</t>
  12250. // </rPh>
  12251. class PhoneticTextXform extends BaseXform {
  12252. constructor() {
  12253. super();
  12254. this.map = {
  12255. r: new RichTextXform(),
  12256. t: new TextXform()
  12257. };
  12258. }
  12259. get tag() {
  12260. return 'rPh';
  12261. }
  12262. render(xmlStream, model) {
  12263. xmlStream.openNode(this.tag, {
  12264. sb: model.sb || 0,
  12265. eb: model.eb || 0
  12266. });
  12267. if (model && model.hasOwnProperty('richText') && model.richText) {
  12268. const {
  12269. r
  12270. } = this.map;
  12271. model.richText.forEach(text => {
  12272. r.render(xmlStream, text);
  12273. });
  12274. } else if (model) {
  12275. this.map.t.render(xmlStream, model.text);
  12276. }
  12277. xmlStream.closeNode();
  12278. }
  12279. parseOpen(node) {
  12280. const {
  12281. name
  12282. } = node;
  12283. if (this.parser) {
  12284. this.parser.parseOpen(node);
  12285. return true;
  12286. }
  12287. if (name === this.tag) {
  12288. this.model = {
  12289. sb: parseInt(node.attributes.sb, 10),
  12290. eb: parseInt(node.attributes.eb, 10)
  12291. };
  12292. return true;
  12293. }
  12294. this.parser = this.map[name];
  12295. if (this.parser) {
  12296. this.parser.parseOpen(node);
  12297. return true;
  12298. }
  12299. return false;
  12300. }
  12301. parseText(text) {
  12302. if (this.parser) {
  12303. this.parser.parseText(text);
  12304. }
  12305. }
  12306. parseClose(name) {
  12307. if (this.parser) {
  12308. if (!this.parser.parseClose(name)) {
  12309. switch (name) {
  12310. case 'r':
  12311. {
  12312. let rt = this.model.richText;
  12313. if (!rt) {
  12314. rt = this.model.richText = [];
  12315. }
  12316. rt.push(this.parser.model);
  12317. break;
  12318. }
  12319. case 't':
  12320. this.model.text = this.parser.model;
  12321. break;
  12322. default:
  12323. break;
  12324. }
  12325. this.parser = undefined;
  12326. }
  12327. return true;
  12328. }
  12329. switch (name) {
  12330. case this.tag:
  12331. return false;
  12332. default:
  12333. return true;
  12334. }
  12335. }
  12336. }
  12337. module.exports = PhoneticTextXform;
  12338. },{"../base-xform":32,"./rich-text-xform":122,"./text-xform":125}],122:[function(require,module,exports){
  12339. "use strict";
  12340. const TextXform = require('./text-xform');
  12341. const FontXform = require('../style/font-xform');
  12342. const BaseXform = require('../base-xform');
  12343. // <r>
  12344. // <rPr>
  12345. // <sz val="11"/>
  12346. // <color theme="1" tint="5"/>
  12347. // <rFont val="Calibri"/>
  12348. // <family val="2"/>
  12349. // <scheme val="minor"/>
  12350. // </rPr>
  12351. // <t xml:space="preserve"> is </t>
  12352. // </r>
  12353. class RichTextXform extends BaseXform {
  12354. constructor(model) {
  12355. super();
  12356. this.model = model;
  12357. }
  12358. get tag() {
  12359. return 'r';
  12360. }
  12361. get textXform() {
  12362. return this._textXform || (this._textXform = new TextXform());
  12363. }
  12364. get fontXform() {
  12365. return this._fontXform || (this._fontXform = new FontXform(RichTextXform.FONT_OPTIONS));
  12366. }
  12367. render(xmlStream, model) {
  12368. model = model || this.model;
  12369. xmlStream.openNode('r');
  12370. if (model.font) {
  12371. this.fontXform.render(xmlStream, model.font);
  12372. }
  12373. this.textXform.render(xmlStream, model.text);
  12374. xmlStream.closeNode();
  12375. }
  12376. parseOpen(node) {
  12377. if (this.parser) {
  12378. this.parser.parseOpen(node);
  12379. return true;
  12380. }
  12381. switch (node.name) {
  12382. case 'r':
  12383. this.model = {};
  12384. return true;
  12385. case 't':
  12386. this.parser = this.textXform;
  12387. this.parser.parseOpen(node);
  12388. return true;
  12389. case 'rPr':
  12390. this.parser = this.fontXform;
  12391. this.parser.parseOpen(node);
  12392. return true;
  12393. default:
  12394. return false;
  12395. }
  12396. }
  12397. parseText(text) {
  12398. if (this.parser) {
  12399. this.parser.parseText(text);
  12400. }
  12401. }
  12402. parseClose(name) {
  12403. switch (name) {
  12404. case 'r':
  12405. return false;
  12406. case 't':
  12407. this.model.text = this.parser.model;
  12408. this.parser = undefined;
  12409. return true;
  12410. case 'rPr':
  12411. this.model.font = this.parser.model;
  12412. this.parser = undefined;
  12413. return true;
  12414. default:
  12415. if (this.parser) {
  12416. this.parser.parseClose(name);
  12417. }
  12418. return true;
  12419. }
  12420. }
  12421. }
  12422. RichTextXform.FONT_OPTIONS = {
  12423. tagName: 'rPr',
  12424. fontNameTag: 'rFont'
  12425. };
  12426. module.exports = RichTextXform;
  12427. },{"../base-xform":32,"../style/font-xform":131,"./text-xform":125}],123:[function(require,module,exports){
  12428. "use strict";
  12429. const TextXform = require('./text-xform');
  12430. const RichTextXform = require('./rich-text-xform');
  12431. const PhoneticTextXform = require('./phonetic-text-xform');
  12432. const BaseXform = require('../base-xform');
  12433. // <si>
  12434. // <r></r><r></r>...
  12435. // </si>
  12436. // <si>
  12437. // <t></t>
  12438. // </si>
  12439. class SharedStringXform extends BaseXform {
  12440. constructor(model) {
  12441. super();
  12442. this.model = model;
  12443. this.map = {
  12444. r: new RichTextXform(),
  12445. t: new TextXform(),
  12446. rPh: new PhoneticTextXform()
  12447. };
  12448. }
  12449. get tag() {
  12450. return 'si';
  12451. }
  12452. render(xmlStream, model) {
  12453. xmlStream.openNode(this.tag);
  12454. if (model && model.hasOwnProperty('richText') && model.richText) {
  12455. if (model.richText.length) {
  12456. model.richText.forEach(text => {
  12457. this.map.r.render(xmlStream, text);
  12458. });
  12459. } else {
  12460. this.map.t.render(xmlStream, '');
  12461. }
  12462. } else if (model !== undefined && model !== null) {
  12463. this.map.t.render(xmlStream, model);
  12464. }
  12465. xmlStream.closeNode();
  12466. }
  12467. parseOpen(node) {
  12468. const {
  12469. name
  12470. } = node;
  12471. if (this.parser) {
  12472. this.parser.parseOpen(node);
  12473. return true;
  12474. }
  12475. if (name === this.tag) {
  12476. this.model = {};
  12477. return true;
  12478. }
  12479. this.parser = this.map[name];
  12480. if (this.parser) {
  12481. this.parser.parseOpen(node);
  12482. return true;
  12483. }
  12484. return false;
  12485. }
  12486. parseText(text) {
  12487. if (this.parser) {
  12488. this.parser.parseText(text);
  12489. }
  12490. }
  12491. parseClose(name) {
  12492. if (this.parser) {
  12493. if (!this.parser.parseClose(name)) {
  12494. switch (name) {
  12495. case 'r':
  12496. {
  12497. let rt = this.model.richText;
  12498. if (!rt) {
  12499. rt = this.model.richText = [];
  12500. }
  12501. rt.push(this.parser.model);
  12502. break;
  12503. }
  12504. case 't':
  12505. this.model = this.parser.model;
  12506. break;
  12507. default:
  12508. break;
  12509. }
  12510. this.parser = undefined;
  12511. }
  12512. return true;
  12513. }
  12514. switch (name) {
  12515. case this.tag:
  12516. return false;
  12517. default:
  12518. return true;
  12519. }
  12520. }
  12521. }
  12522. module.exports = SharedStringXform;
  12523. },{"../base-xform":32,"./phonetic-text-xform":121,"./rich-text-xform":122,"./text-xform":125}],124:[function(require,module,exports){
  12524. "use strict";
  12525. const XmlStream = require('../../../utils/xml-stream');
  12526. const BaseXform = require('../base-xform');
  12527. const SharedStringXform = require('./shared-string-xform');
  12528. class SharedStringsXform extends BaseXform {
  12529. constructor(model) {
  12530. super();
  12531. this.model = model || {
  12532. values: [],
  12533. count: 0
  12534. };
  12535. this.hash = Object.create(null);
  12536. this.rich = Object.create(null);
  12537. }
  12538. get sharedStringXform() {
  12539. return this._sharedStringXform || (this._sharedStringXform = new SharedStringXform());
  12540. }
  12541. get values() {
  12542. return this.model.values;
  12543. }
  12544. get uniqueCount() {
  12545. return this.model.values.length;
  12546. }
  12547. get count() {
  12548. return this.model.count;
  12549. }
  12550. getString(index) {
  12551. return this.model.values[index];
  12552. }
  12553. add(value) {
  12554. return value.richText ? this.addRichText(value) : this.addText(value);
  12555. }
  12556. addText(value) {
  12557. let index = this.hash[value];
  12558. if (index === undefined) {
  12559. index = this.hash[value] = this.model.values.length;
  12560. this.model.values.push(value);
  12561. }
  12562. this.model.count++;
  12563. return index;
  12564. }
  12565. addRichText(value) {
  12566. // TODO: add WeakMap here
  12567. const xml = this.sharedStringXform.toXml(value);
  12568. let index = this.rich[xml];
  12569. if (index === undefined) {
  12570. index = this.rich[xml] = this.model.values.length;
  12571. this.model.values.push(value);
  12572. }
  12573. this.model.count++;
  12574. return index;
  12575. }
  12576. // <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  12577. // <sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="<%=totalRefs%>" uniqueCount="<%=count%>">
  12578. // <si><t><%=text%></t></si>
  12579. // <si><r><rPr></rPr><t></t></r></si>
  12580. // </sst>
  12581. render(xmlStream, model) {
  12582. model = model || this._values;
  12583. xmlStream.openXml(XmlStream.StdDocAttributes);
  12584. xmlStream.openNode('sst', {
  12585. xmlns: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  12586. count: model.count,
  12587. uniqueCount: model.values.length
  12588. });
  12589. const sx = this.sharedStringXform;
  12590. model.values.forEach(sharedString => {
  12591. sx.render(xmlStream, sharedString);
  12592. });
  12593. xmlStream.closeNode();
  12594. }
  12595. parseOpen(node) {
  12596. if (this.parser) {
  12597. this.parser.parseOpen(node);
  12598. return true;
  12599. }
  12600. switch (node.name) {
  12601. case 'sst':
  12602. return true;
  12603. case 'si':
  12604. this.parser = this.sharedStringXform;
  12605. this.parser.parseOpen(node);
  12606. return true;
  12607. default:
  12608. throw new Error(`Unexpected xml node in parseOpen: ${JSON.stringify(node)}`);
  12609. }
  12610. }
  12611. parseText(text) {
  12612. if (this.parser) {
  12613. this.parser.parseText(text);
  12614. }
  12615. }
  12616. parseClose(name) {
  12617. if (this.parser) {
  12618. if (!this.parser.parseClose(name)) {
  12619. this.model.values.push(this.parser.model);
  12620. this.model.count++;
  12621. this.parser = undefined;
  12622. }
  12623. return true;
  12624. }
  12625. switch (name) {
  12626. case 'sst':
  12627. return false;
  12628. default:
  12629. throw new Error(`Unexpected xml node in parseClose: ${name}`);
  12630. }
  12631. }
  12632. }
  12633. module.exports = SharedStringsXform;
  12634. },{"../../../utils/xml-stream":28,"../base-xform":32,"./shared-string-xform":123}],125:[function(require,module,exports){
  12635. "use strict";
  12636. const BaseXform = require('../base-xform');
  12637. // <t xml:space="preserve"> is </t>
  12638. class TextXform extends BaseXform {
  12639. get tag() {
  12640. return 't';
  12641. }
  12642. render(xmlStream, model) {
  12643. xmlStream.openNode('t');
  12644. if (/^\s|\n|\s$/.test(model)) {
  12645. xmlStream.addAttribute('xml:space', 'preserve');
  12646. }
  12647. xmlStream.writeText(model);
  12648. xmlStream.closeNode();
  12649. }
  12650. get model() {
  12651. return this._text.join('').replace(/_x([0-9A-F]{4})_/g, ($0, $1) => String.fromCharCode(parseInt($1, 16)));
  12652. }
  12653. parseOpen(node) {
  12654. switch (node.name) {
  12655. case 't':
  12656. this._text = [];
  12657. return true;
  12658. default:
  12659. return false;
  12660. }
  12661. }
  12662. parseText(text) {
  12663. this._text.push(text);
  12664. }
  12665. parseClose() {
  12666. return false;
  12667. }
  12668. }
  12669. module.exports = TextXform;
  12670. },{"../base-xform":32}],126:[function(require,module,exports){
  12671. "use strict";
  12672. const Enums = require('../../../doc/enums');
  12673. const utils = require('../../../utils/utils');
  12674. const BaseXform = require('../base-xform');
  12675. const validation = {
  12676. horizontalValues: ['left', 'center', 'right', 'fill', 'centerContinuous', 'distributed', 'justify'].reduce((p, v) => {
  12677. p[v] = true;
  12678. return p;
  12679. }, {}),
  12680. horizontal(value) {
  12681. return this.horizontalValues[value] ? value : undefined;
  12682. },
  12683. verticalValues: ['top', 'middle', 'bottom', 'distributed', 'justify'].reduce((p, v) => {
  12684. p[v] = true;
  12685. return p;
  12686. }, {}),
  12687. vertical(value) {
  12688. if (value === 'middle') return 'center';
  12689. return this.verticalValues[value] ? value : undefined;
  12690. },
  12691. wrapText(value) {
  12692. return value ? true : undefined;
  12693. },
  12694. shrinkToFit(value) {
  12695. return value ? true : undefined;
  12696. },
  12697. textRotation(value) {
  12698. switch (value) {
  12699. case 'vertical':
  12700. return value;
  12701. default:
  12702. value = utils.validInt(value);
  12703. return value >= -90 && value <= 90 ? value : undefined;
  12704. }
  12705. },
  12706. indent(value) {
  12707. value = utils.validInt(value);
  12708. return Math.max(0, value);
  12709. },
  12710. readingOrder(value) {
  12711. switch (value) {
  12712. case 'ltr':
  12713. return Enums.ReadingOrder.LeftToRight;
  12714. case 'rtl':
  12715. return Enums.ReadingOrder.RightToLeft;
  12716. default:
  12717. return undefined;
  12718. }
  12719. }
  12720. };
  12721. const textRotationXform = {
  12722. toXml(textRotation) {
  12723. textRotation = validation.textRotation(textRotation);
  12724. if (textRotation) {
  12725. if (textRotation === 'vertical') {
  12726. return 255;
  12727. }
  12728. const tr = Math.round(textRotation);
  12729. if (tr >= 0 && tr <= 90) {
  12730. return tr;
  12731. }
  12732. if (tr < 0 && tr >= -90) {
  12733. return 90 - tr;
  12734. }
  12735. }
  12736. return undefined;
  12737. },
  12738. toModel(textRotation) {
  12739. const tr = utils.validInt(textRotation);
  12740. if (tr !== undefined) {
  12741. if (tr === 255) {
  12742. return 'vertical';
  12743. }
  12744. if (tr >= 0 && tr <= 90) {
  12745. return tr;
  12746. }
  12747. if (tr > 90 && tr <= 180) {
  12748. return 90 - tr;
  12749. }
  12750. }
  12751. return undefined;
  12752. }
  12753. };
  12754. // Alignment encapsulates translation from style.alignment model to/from xlsx
  12755. class AlignmentXform extends BaseXform {
  12756. get tag() {
  12757. return 'alignment';
  12758. }
  12759. render(xmlStream, model) {
  12760. xmlStream.addRollback();
  12761. xmlStream.openNode('alignment');
  12762. let isValid = false;
  12763. function add(name, value) {
  12764. if (value) {
  12765. xmlStream.addAttribute(name, value);
  12766. isValid = true;
  12767. }
  12768. }
  12769. add('horizontal', validation.horizontal(model.horizontal));
  12770. add('vertical', validation.vertical(model.vertical));
  12771. add('wrapText', validation.wrapText(model.wrapText) ? '1' : false);
  12772. add('shrinkToFit', validation.shrinkToFit(model.shrinkToFit) ? '1' : false);
  12773. add('indent', validation.indent(model.indent));
  12774. add('textRotation', textRotationXform.toXml(model.textRotation));
  12775. add('readingOrder', validation.readingOrder(model.readingOrder));
  12776. xmlStream.closeNode();
  12777. if (isValid) {
  12778. xmlStream.commit();
  12779. } else {
  12780. xmlStream.rollback();
  12781. }
  12782. }
  12783. parseOpen(node) {
  12784. const model = {};
  12785. let valid = false;
  12786. function add(truthy, name, value) {
  12787. if (truthy) {
  12788. model[name] = value;
  12789. valid = true;
  12790. }
  12791. }
  12792. add(node.attributes.horizontal, 'horizontal', node.attributes.horizontal);
  12793. add(node.attributes.vertical, 'vertical', node.attributes.vertical === 'center' ? 'middle' : node.attributes.vertical);
  12794. add(node.attributes.wrapText, 'wrapText', utils.parseBoolean(node.attributes.wrapText));
  12795. add(node.attributes.shrinkToFit, 'shrinkToFit', utils.parseBoolean(node.attributes.shrinkToFit));
  12796. add(node.attributes.indent, 'indent', parseInt(node.attributes.indent, 10));
  12797. add(node.attributes.textRotation, 'textRotation', textRotationXform.toModel(node.attributes.textRotation));
  12798. add(node.attributes.readingOrder, 'readingOrder', node.attributes.readingOrder === '2' ? 'rtl' : 'ltr');
  12799. this.model = valid ? model : null;
  12800. }
  12801. parseText() {}
  12802. parseClose() {
  12803. return false;
  12804. }
  12805. }
  12806. module.exports = AlignmentXform;
  12807. },{"../../../doc/enums":7,"../../../utils/utils":27,"../base-xform":32}],127:[function(require,module,exports){
  12808. "use strict";
  12809. /* eslint-disable max-classes-per-file */
  12810. const BaseXform = require('../base-xform');
  12811. const utils = require('../../../utils/utils');
  12812. const ColorXform = require('./color-xform');
  12813. class EdgeXform extends BaseXform {
  12814. constructor(name) {
  12815. super();
  12816. this.name = name;
  12817. this.map = {
  12818. color: new ColorXform()
  12819. };
  12820. }
  12821. get tag() {
  12822. return this.name;
  12823. }
  12824. render(xmlStream, model, defaultColor) {
  12825. const color = model && model.color || defaultColor || this.defaultColor;
  12826. xmlStream.openNode(this.name);
  12827. if (model && model.style) {
  12828. xmlStream.addAttribute('style', model.style);
  12829. if (color) {
  12830. this.map.color.render(xmlStream, color);
  12831. }
  12832. }
  12833. xmlStream.closeNode();
  12834. }
  12835. parseOpen(node) {
  12836. if (this.parser) {
  12837. this.parser.parseOpen(node);
  12838. return true;
  12839. }
  12840. switch (node.name) {
  12841. case this.name:
  12842. {
  12843. const {
  12844. style
  12845. } = node.attributes;
  12846. if (style) {
  12847. this.model = {
  12848. style
  12849. };
  12850. } else {
  12851. this.model = undefined;
  12852. }
  12853. return true;
  12854. }
  12855. case 'color':
  12856. this.parser = this.map.color;
  12857. this.parser.parseOpen(node);
  12858. return true;
  12859. default:
  12860. return false;
  12861. }
  12862. }
  12863. parseText(text) {
  12864. if (this.parser) {
  12865. this.parser.parseText(text);
  12866. }
  12867. }
  12868. parseClose(name) {
  12869. if (this.parser) {
  12870. if (!this.parser.parseClose(name)) {
  12871. this.parser = undefined;
  12872. }
  12873. return true;
  12874. }
  12875. if (name === this.name) {
  12876. if (this.map.color.model) {
  12877. if (!this.model) {
  12878. this.model = {};
  12879. }
  12880. this.model.color = this.map.color.model;
  12881. }
  12882. }
  12883. return false;
  12884. }
  12885. validStyle(value) {
  12886. return EdgeXform.validStyleValues[value];
  12887. }
  12888. }
  12889. EdgeXform.validStyleValues = ['thin', 'dashed', 'dotted', 'dashDot', 'hair', 'dashDotDot', 'slantDashDot', 'mediumDashed', 'mediumDashDotDot', 'mediumDashDot', 'medium', 'double', 'thick'].reduce((p, v) => {
  12890. p[v] = true;
  12891. return p;
  12892. }, {});
  12893. // Border encapsulates translation from border model to/from xlsx
  12894. class BorderXform extends BaseXform {
  12895. constructor() {
  12896. super();
  12897. this.map = {
  12898. top: new EdgeXform('top'),
  12899. left: new EdgeXform('left'),
  12900. bottom: new EdgeXform('bottom'),
  12901. right: new EdgeXform('right'),
  12902. diagonal: new EdgeXform('diagonal')
  12903. };
  12904. }
  12905. render(xmlStream, model) {
  12906. const {
  12907. color
  12908. } = model;
  12909. xmlStream.openNode('border');
  12910. if (model.diagonal && model.diagonal.style) {
  12911. if (model.diagonal.up) {
  12912. xmlStream.addAttribute('diagonalUp', '1');
  12913. }
  12914. if (model.diagonal.down) {
  12915. xmlStream.addAttribute('diagonalDown', '1');
  12916. }
  12917. }
  12918. function add(edgeModel, edgeXform) {
  12919. if (edgeModel && !edgeModel.color && model.color) {
  12920. // don't mess with incoming models
  12921. edgeModel = {
  12922. ...edgeModel,
  12923. color: model.color
  12924. };
  12925. }
  12926. edgeXform.render(xmlStream, edgeModel, color);
  12927. }
  12928. add(model.left, this.map.left);
  12929. add(model.right, this.map.right);
  12930. add(model.top, this.map.top);
  12931. add(model.bottom, this.map.bottom);
  12932. add(model.diagonal, this.map.diagonal);
  12933. xmlStream.closeNode();
  12934. }
  12935. parseOpen(node) {
  12936. if (this.parser) {
  12937. this.parser.parseOpen(node);
  12938. return true;
  12939. }
  12940. switch (node.name) {
  12941. case 'border':
  12942. this.reset();
  12943. this.diagonalUp = utils.parseBoolean(node.attributes.diagonalUp);
  12944. this.diagonalDown = utils.parseBoolean(node.attributes.diagonalDown);
  12945. return true;
  12946. default:
  12947. this.parser = this.map[node.name];
  12948. if (this.parser) {
  12949. this.parser.parseOpen(node);
  12950. return true;
  12951. }
  12952. return false;
  12953. }
  12954. }
  12955. parseText(text) {
  12956. if (this.parser) {
  12957. this.parser.parseText(text);
  12958. }
  12959. }
  12960. parseClose(name) {
  12961. if (this.parser) {
  12962. if (!this.parser.parseClose(name)) {
  12963. this.parser = undefined;
  12964. }
  12965. return true;
  12966. }
  12967. if (name === 'border') {
  12968. const model = this.model = {};
  12969. const add = function (key, edgeModel, extensions) {
  12970. if (edgeModel) {
  12971. if (extensions) {
  12972. Object.assign(edgeModel, extensions);
  12973. }
  12974. model[key] = edgeModel;
  12975. }
  12976. };
  12977. add('left', this.map.left.model);
  12978. add('right', this.map.right.model);
  12979. add('top', this.map.top.model);
  12980. add('bottom', this.map.bottom.model);
  12981. add('diagonal', this.map.diagonal.model, {
  12982. up: this.diagonalUp,
  12983. down: this.diagonalDown
  12984. });
  12985. }
  12986. return false;
  12987. }
  12988. }
  12989. module.exports = BorderXform;
  12990. },{"../../../utils/utils":27,"../base-xform":32,"./color-xform":128}],128:[function(require,module,exports){
  12991. "use strict";
  12992. const BaseXform = require('../base-xform');
  12993. // Color encapsulates translation from color model to/from xlsx
  12994. class ColorXform extends BaseXform {
  12995. constructor(name) {
  12996. super();
  12997. // this.name controls the xm node name
  12998. this.name = name || 'color';
  12999. }
  13000. get tag() {
  13001. return this.name;
  13002. }
  13003. render(xmlStream, model) {
  13004. if (model) {
  13005. xmlStream.openNode(this.name);
  13006. if (model.argb) {
  13007. xmlStream.addAttribute('rgb', model.argb);
  13008. } else if (model.theme !== undefined) {
  13009. xmlStream.addAttribute('theme', model.theme);
  13010. if (model.tint !== undefined) {
  13011. xmlStream.addAttribute('tint', model.tint);
  13012. }
  13013. } else if (model.indexed !== undefined) {
  13014. xmlStream.addAttribute('indexed', model.indexed);
  13015. } else {
  13016. xmlStream.addAttribute('auto', '1');
  13017. }
  13018. xmlStream.closeNode();
  13019. return true;
  13020. }
  13021. return false;
  13022. }
  13023. parseOpen(node) {
  13024. if (node.name === this.name) {
  13025. if (node.attributes.rgb) {
  13026. this.model = {
  13027. argb: node.attributes.rgb
  13028. };
  13029. } else if (node.attributes.theme) {
  13030. this.model = {
  13031. theme: parseInt(node.attributes.theme, 10)
  13032. };
  13033. if (node.attributes.tint) {
  13034. this.model.tint = parseFloat(node.attributes.tint);
  13035. }
  13036. } else if (node.attributes.indexed) {
  13037. this.model = {
  13038. indexed: parseInt(node.attributes.indexed, 10)
  13039. };
  13040. } else {
  13041. this.model = undefined;
  13042. }
  13043. return true;
  13044. }
  13045. return false;
  13046. }
  13047. parseText() {}
  13048. parseClose() {
  13049. return false;
  13050. }
  13051. }
  13052. module.exports = ColorXform;
  13053. },{"../base-xform":32}],129:[function(require,module,exports){
  13054. "use strict";
  13055. const BaseXform = require('../base-xform');
  13056. const AlignmentXform = require('./alignment-xform');
  13057. const BorderXform = require('./border-xform');
  13058. const FillXform = require('./fill-xform');
  13059. const FontXform = require('./font-xform');
  13060. const NumFmtXform = require('./numfmt-xform');
  13061. const ProtectionXform = require('./protection-xform');
  13062. // <xf numFmtId="[numFmtId]" fontId="[fontId]" fillId="[fillId]" borderId="[xf.borderId]" xfId="[xfId]">
  13063. // Optional <alignment>
  13064. // Optional <protection>
  13065. // </xf>
  13066. // Style assists translation from style model to/from xlsx
  13067. class DxfXform extends BaseXform {
  13068. constructor() {
  13069. super();
  13070. this.map = {
  13071. alignment: new AlignmentXform(),
  13072. border: new BorderXform(),
  13073. fill: new FillXform(),
  13074. font: new FontXform(),
  13075. numFmt: new NumFmtXform(),
  13076. protection: new ProtectionXform()
  13077. };
  13078. }
  13079. get tag() {
  13080. return 'dxf';
  13081. }
  13082. // how do we generate dxfid?
  13083. render(xmlStream, model) {
  13084. xmlStream.openNode(this.tag);
  13085. if (model.font) {
  13086. this.map.font.render(xmlStream, model.font);
  13087. }
  13088. if (model.numFmt && model.numFmtId) {
  13089. const numFmtModel = {
  13090. id: model.numFmtId,
  13091. formatCode: model.numFmt
  13092. };
  13093. this.map.numFmt.render(xmlStream, numFmtModel);
  13094. }
  13095. if (model.fill) {
  13096. this.map.fill.render(xmlStream, model.fill);
  13097. }
  13098. if (model.alignment) {
  13099. this.map.alignment.render(xmlStream, model.alignment);
  13100. }
  13101. if (model.border) {
  13102. this.map.border.render(xmlStream, model.border);
  13103. }
  13104. if (model.protection) {
  13105. this.map.protection.render(xmlStream, model.protection);
  13106. }
  13107. xmlStream.closeNode();
  13108. }
  13109. parseOpen(node) {
  13110. if (this.parser) {
  13111. this.parser.parseOpen(node);
  13112. return true;
  13113. }
  13114. switch (node.name) {
  13115. case this.tag:
  13116. // this node is often repeated. Need to reset children
  13117. this.reset();
  13118. return true;
  13119. default:
  13120. this.parser = this.map[node.name];
  13121. if (this.parser) {
  13122. this.parser.parseOpen(node);
  13123. }
  13124. return true;
  13125. }
  13126. }
  13127. parseText(text) {
  13128. if (this.parser) {
  13129. this.parser.parseText(text);
  13130. }
  13131. }
  13132. parseClose(name) {
  13133. if (this.parser) {
  13134. if (!this.parser.parseClose(name)) {
  13135. this.parser = undefined;
  13136. }
  13137. return true;
  13138. }
  13139. if (name === this.tag) {
  13140. this.model = {
  13141. alignment: this.map.alignment.model,
  13142. border: this.map.border.model,
  13143. fill: this.map.fill.model,
  13144. font: this.map.font.model,
  13145. numFmt: this.map.numFmt.model,
  13146. protection: this.map.protection.model
  13147. };
  13148. return false;
  13149. }
  13150. return true;
  13151. }
  13152. }
  13153. module.exports = DxfXform;
  13154. },{"../base-xform":32,"./alignment-xform":126,"./border-xform":127,"./fill-xform":130,"./font-xform":131,"./numfmt-xform":132,"./protection-xform":133}],130:[function(require,module,exports){
  13155. "use strict";
  13156. /* eslint-disable max-classes-per-file */
  13157. const BaseXform = require('../base-xform');
  13158. const ColorXform = require('./color-xform');
  13159. class StopXform extends BaseXform {
  13160. constructor() {
  13161. super();
  13162. this.map = {
  13163. color: new ColorXform()
  13164. };
  13165. }
  13166. get tag() {
  13167. return 'stop';
  13168. }
  13169. render(xmlStream, model) {
  13170. xmlStream.openNode('stop');
  13171. xmlStream.addAttribute('position', model.position);
  13172. this.map.color.render(xmlStream, model.color);
  13173. xmlStream.closeNode();
  13174. }
  13175. parseOpen(node) {
  13176. if (this.parser) {
  13177. this.parser.parseOpen(node);
  13178. return true;
  13179. }
  13180. switch (node.name) {
  13181. case 'stop':
  13182. this.model = {
  13183. position: parseFloat(node.attributes.position)
  13184. };
  13185. return true;
  13186. case 'color':
  13187. this.parser = this.map.color;
  13188. this.parser.parseOpen(node);
  13189. return true;
  13190. default:
  13191. return false;
  13192. }
  13193. }
  13194. parseText() {}
  13195. parseClose(name) {
  13196. if (this.parser) {
  13197. if (!this.parser.parseClose(name)) {
  13198. this.model.color = this.parser.model;
  13199. this.parser = undefined;
  13200. }
  13201. return true;
  13202. }
  13203. return false;
  13204. }
  13205. }
  13206. class PatternFillXform extends BaseXform {
  13207. constructor() {
  13208. super();
  13209. this.map = {
  13210. fgColor: new ColorXform('fgColor'),
  13211. bgColor: new ColorXform('bgColor')
  13212. };
  13213. }
  13214. get name() {
  13215. return 'pattern';
  13216. }
  13217. get tag() {
  13218. return 'patternFill';
  13219. }
  13220. render(xmlStream, model) {
  13221. xmlStream.openNode('patternFill');
  13222. xmlStream.addAttribute('patternType', model.pattern);
  13223. if (model.fgColor) {
  13224. this.map.fgColor.render(xmlStream, model.fgColor);
  13225. }
  13226. if (model.bgColor) {
  13227. this.map.bgColor.render(xmlStream, model.bgColor);
  13228. }
  13229. xmlStream.closeNode();
  13230. }
  13231. parseOpen(node) {
  13232. if (this.parser) {
  13233. this.parser.parseOpen(node);
  13234. return true;
  13235. }
  13236. switch (node.name) {
  13237. case 'patternFill':
  13238. this.model = {
  13239. type: 'pattern',
  13240. pattern: node.attributes.patternType
  13241. };
  13242. return true;
  13243. default:
  13244. this.parser = this.map[node.name];
  13245. if (this.parser) {
  13246. this.parser.parseOpen(node);
  13247. return true;
  13248. }
  13249. return false;
  13250. }
  13251. }
  13252. parseText(text) {
  13253. if (this.parser) {
  13254. this.parser.parseText(text);
  13255. }
  13256. }
  13257. parseClose(name) {
  13258. if (this.parser) {
  13259. if (!this.parser.parseClose(name)) {
  13260. if (this.parser.model) {
  13261. this.model[name] = this.parser.model;
  13262. }
  13263. this.parser = undefined;
  13264. }
  13265. return true;
  13266. }
  13267. return false;
  13268. }
  13269. }
  13270. class GradientFillXform extends BaseXform {
  13271. constructor() {
  13272. super();
  13273. this.map = {
  13274. stop: new StopXform()
  13275. };
  13276. // if (model) {
  13277. // this.gradient = model.gradient;
  13278. // if (model.center) {
  13279. // this.center = model.center;
  13280. // }
  13281. // if (model.degree !== undefined) {
  13282. // this.degree = model.degree;
  13283. // }
  13284. // this.stops = model.stops.map(function(stop) { return new StopXform(stop); });
  13285. // } else {
  13286. // this.stops = [];
  13287. // }
  13288. }
  13289. get name() {
  13290. return 'gradient';
  13291. }
  13292. get tag() {
  13293. return 'gradientFill';
  13294. }
  13295. render(xmlStream, model) {
  13296. xmlStream.openNode('gradientFill');
  13297. switch (model.gradient) {
  13298. case 'angle':
  13299. xmlStream.addAttribute('degree', model.degree);
  13300. break;
  13301. case 'path':
  13302. xmlStream.addAttribute('type', 'path');
  13303. if (model.center.left) {
  13304. xmlStream.addAttribute('left', model.center.left);
  13305. if (model.center.right === undefined) {
  13306. xmlStream.addAttribute('right', model.center.left);
  13307. }
  13308. }
  13309. if (model.center.right) {
  13310. xmlStream.addAttribute('right', model.center.right);
  13311. }
  13312. if (model.center.top) {
  13313. xmlStream.addAttribute('top', model.center.top);
  13314. if (model.center.bottom === undefined) {
  13315. xmlStream.addAttribute('bottom', model.center.top);
  13316. }
  13317. }
  13318. if (model.center.bottom) {
  13319. xmlStream.addAttribute('bottom', model.center.bottom);
  13320. }
  13321. break;
  13322. default:
  13323. break;
  13324. }
  13325. const stopXform = this.map.stop;
  13326. model.stops.forEach(stopModel => {
  13327. stopXform.render(xmlStream, stopModel);
  13328. });
  13329. xmlStream.closeNode();
  13330. }
  13331. parseOpen(node) {
  13332. if (this.parser) {
  13333. this.parser.parseOpen(node);
  13334. return true;
  13335. }
  13336. switch (node.name) {
  13337. case 'gradientFill':
  13338. {
  13339. const model = this.model = {
  13340. stops: []
  13341. };
  13342. if (node.attributes.degree) {
  13343. model.gradient = 'angle';
  13344. model.degree = parseInt(node.attributes.degree, 10);
  13345. } else if (node.attributes.type === 'path') {
  13346. model.gradient = 'path';
  13347. model.center = {
  13348. left: node.attributes.left ? parseFloat(node.attributes.left) : 0,
  13349. top: node.attributes.top ? parseFloat(node.attributes.top) : 0
  13350. };
  13351. if (node.attributes.right !== node.attributes.left) {
  13352. model.center.right = node.attributes.right ? parseFloat(node.attributes.right) : 0;
  13353. }
  13354. if (node.attributes.bottom !== node.attributes.top) {
  13355. model.center.bottom = node.attributes.bottom ? parseFloat(node.attributes.bottom) : 0;
  13356. }
  13357. }
  13358. return true;
  13359. }
  13360. case 'stop':
  13361. this.parser = this.map.stop;
  13362. this.parser.parseOpen(node);
  13363. return true;
  13364. default:
  13365. return false;
  13366. }
  13367. }
  13368. parseText(text) {
  13369. if (this.parser) {
  13370. this.parser.parseText(text);
  13371. }
  13372. }
  13373. parseClose(name) {
  13374. if (this.parser) {
  13375. if (!this.parser.parseClose(name)) {
  13376. this.model.stops.push(this.parser.model);
  13377. this.parser = undefined;
  13378. }
  13379. return true;
  13380. }
  13381. return false;
  13382. }
  13383. }
  13384. // Fill encapsulates translation from fill model to/from xlsx
  13385. class FillXform extends BaseXform {
  13386. constructor() {
  13387. super();
  13388. this.map = {
  13389. patternFill: new PatternFillXform(),
  13390. gradientFill: new GradientFillXform()
  13391. };
  13392. }
  13393. get tag() {
  13394. return 'fill';
  13395. }
  13396. render(xmlStream, model) {
  13397. xmlStream.addRollback();
  13398. xmlStream.openNode('fill');
  13399. switch (model.type) {
  13400. case 'pattern':
  13401. this.map.patternFill.render(xmlStream, model);
  13402. break;
  13403. case 'gradient':
  13404. this.map.gradientFill.render(xmlStream, model);
  13405. break;
  13406. default:
  13407. xmlStream.rollback();
  13408. return;
  13409. }
  13410. xmlStream.closeNode();
  13411. xmlStream.commit();
  13412. }
  13413. parseOpen(node) {
  13414. if (this.parser) {
  13415. this.parser.parseOpen(node);
  13416. return true;
  13417. }
  13418. switch (node.name) {
  13419. case 'fill':
  13420. this.model = {};
  13421. return true;
  13422. default:
  13423. this.parser = this.map[node.name];
  13424. if (this.parser) {
  13425. this.parser.parseOpen(node);
  13426. return true;
  13427. }
  13428. return false;
  13429. }
  13430. }
  13431. parseText(text) {
  13432. if (this.parser) {
  13433. this.parser.parseText(text);
  13434. }
  13435. }
  13436. parseClose(name) {
  13437. if (this.parser) {
  13438. if (!this.parser.parseClose(name)) {
  13439. this.model = this.parser.model;
  13440. this.model.type = this.parser.name;
  13441. this.parser = undefined;
  13442. }
  13443. return true;
  13444. }
  13445. return false;
  13446. }
  13447. validStyle(value) {
  13448. return FillXform.validPatternValues[value];
  13449. }
  13450. }
  13451. FillXform.validPatternValues = ['none', 'solid', 'darkVertical', 'darkGray', 'mediumGray', 'lightGray', 'gray125', 'gray0625', 'darkHorizontal', 'darkVertical', 'darkDown', 'darkUp', 'darkGrid', 'darkTrellis', 'lightHorizontal', 'lightVertical', 'lightDown', 'lightUp', 'lightGrid', 'lightTrellis', 'lightGrid'].reduce((p, v) => {
  13452. p[v] = true;
  13453. return p;
  13454. }, {});
  13455. FillXform.StopXform = StopXform;
  13456. FillXform.PatternFillXform = PatternFillXform;
  13457. FillXform.GradientFillXform = GradientFillXform;
  13458. module.exports = FillXform;
  13459. },{"../base-xform":32,"./color-xform":128}],131:[function(require,module,exports){
  13460. 'use strict';
  13461. const ColorXform = require('./color-xform');
  13462. const BooleanXform = require('../simple/boolean-xform');
  13463. const IntegerXform = require('../simple/integer-xform');
  13464. const StringXform = require('../simple/string-xform');
  13465. const UnderlineXform = require('./underline-xform');
  13466. const _ = require('../../../utils/under-dash');
  13467. const BaseXform = require('../base-xform');
  13468. // Font encapsulates translation from font model to xlsx
  13469. class FontXform extends BaseXform {
  13470. constructor(options) {
  13471. super();
  13472. this.options = options || FontXform.OPTIONS;
  13473. this.map = {
  13474. b: {
  13475. prop: 'bold',
  13476. xform: new BooleanXform({
  13477. tag: 'b',
  13478. attr: 'val'
  13479. })
  13480. },
  13481. i: {
  13482. prop: 'italic',
  13483. xform: new BooleanXform({
  13484. tag: 'i',
  13485. attr: 'val'
  13486. })
  13487. },
  13488. u: {
  13489. prop: 'underline',
  13490. xform: new UnderlineXform()
  13491. },
  13492. charset: {
  13493. prop: 'charset',
  13494. xform: new IntegerXform({
  13495. tag: 'charset',
  13496. attr: 'val'
  13497. })
  13498. },
  13499. color: {
  13500. prop: 'color',
  13501. xform: new ColorXform()
  13502. },
  13503. condense: {
  13504. prop: 'condense',
  13505. xform: new BooleanXform({
  13506. tag: 'condense',
  13507. attr: 'val'
  13508. })
  13509. },
  13510. extend: {
  13511. prop: 'extend',
  13512. xform: new BooleanXform({
  13513. tag: 'extend',
  13514. attr: 'val'
  13515. })
  13516. },
  13517. family: {
  13518. prop: 'family',
  13519. xform: new IntegerXform({
  13520. tag: 'family',
  13521. attr: 'val'
  13522. })
  13523. },
  13524. outline: {
  13525. prop: 'outline',
  13526. xform: new BooleanXform({
  13527. tag: 'outline',
  13528. attr: 'val'
  13529. })
  13530. },
  13531. vertAlign: {
  13532. prop: 'vertAlign',
  13533. xform: new StringXform({
  13534. tag: 'vertAlign',
  13535. attr: 'val'
  13536. })
  13537. },
  13538. scheme: {
  13539. prop: 'scheme',
  13540. xform: new StringXform({
  13541. tag: 'scheme',
  13542. attr: 'val'
  13543. })
  13544. },
  13545. shadow: {
  13546. prop: 'shadow',
  13547. xform: new BooleanXform({
  13548. tag: 'shadow',
  13549. attr: 'val'
  13550. })
  13551. },
  13552. strike: {
  13553. prop: 'strike',
  13554. xform: new BooleanXform({
  13555. tag: 'strike',
  13556. attr: 'val'
  13557. })
  13558. },
  13559. sz: {
  13560. prop: 'size',
  13561. xform: new IntegerXform({
  13562. tag: 'sz',
  13563. attr: 'val'
  13564. })
  13565. }
  13566. };
  13567. this.map[this.options.fontNameTag] = {
  13568. prop: 'name',
  13569. xform: new StringXform({
  13570. tag: this.options.fontNameTag,
  13571. attr: 'val'
  13572. })
  13573. };
  13574. }
  13575. get tag() {
  13576. return this.options.tagName;
  13577. }
  13578. render(xmlStream, model) {
  13579. const {
  13580. map
  13581. } = this;
  13582. xmlStream.openNode(this.options.tagName);
  13583. _.each(this.map, (defn, tag) => {
  13584. map[tag].xform.render(xmlStream, model[defn.prop]);
  13585. });
  13586. xmlStream.closeNode();
  13587. }
  13588. parseOpen(node) {
  13589. if (this.parser) {
  13590. this.parser.parseOpen(node);
  13591. return true;
  13592. }
  13593. if (this.map[node.name]) {
  13594. this.parser = this.map[node.name].xform;
  13595. return this.parser.parseOpen(node);
  13596. }
  13597. switch (node.name) {
  13598. case this.options.tagName:
  13599. this.model = {};
  13600. return true;
  13601. default:
  13602. return false;
  13603. }
  13604. }
  13605. parseText(text) {
  13606. if (this.parser) {
  13607. this.parser.parseText(text);
  13608. }
  13609. }
  13610. parseClose(name) {
  13611. if (this.parser && !this.parser.parseClose(name)) {
  13612. const item = this.map[name];
  13613. if (this.parser.model) {
  13614. this.model[item.prop] = this.parser.model;
  13615. }
  13616. this.parser = undefined;
  13617. return true;
  13618. }
  13619. switch (name) {
  13620. case this.options.tagName:
  13621. return false;
  13622. default:
  13623. return true;
  13624. }
  13625. }
  13626. }
  13627. FontXform.OPTIONS = {
  13628. tagName: 'font',
  13629. fontNameTag: 'name'
  13630. };
  13631. module.exports = FontXform;
  13632. },{"../../../utils/under-dash":26,"../base-xform":32,"../simple/boolean-xform":116,"../simple/integer-xform":118,"../simple/string-xform":119,"./color-xform":128,"./underline-xform":136}],132:[function(require,module,exports){
  13633. "use strict";
  13634. const _ = require('../../../utils/under-dash');
  13635. const defaultNumFormats = require('../../defaultnumformats');
  13636. const BaseXform = require('../base-xform');
  13637. function hashDefaultFormats() {
  13638. const hash = {};
  13639. _.each(defaultNumFormats, (dnf, id) => {
  13640. if (dnf.f) {
  13641. hash[dnf.f] = parseInt(id, 10);
  13642. }
  13643. // at some point, add the other cultures here...
  13644. });
  13645. return hash;
  13646. }
  13647. const defaultFmtHash = hashDefaultFormats();
  13648. // NumFmt encapsulates translation between number format and xlsx
  13649. class NumFmtXform extends BaseXform {
  13650. constructor(id, formatCode) {
  13651. super();
  13652. this.id = id;
  13653. this.formatCode = formatCode;
  13654. }
  13655. get tag() {
  13656. return 'numFmt';
  13657. }
  13658. render(xmlStream, model) {
  13659. xmlStream.leafNode('numFmt', {
  13660. numFmtId: model.id,
  13661. formatCode: model.formatCode
  13662. });
  13663. }
  13664. parseOpen(node) {
  13665. switch (node.name) {
  13666. case 'numFmt':
  13667. this.model = {
  13668. id: parseInt(node.attributes.numFmtId, 10),
  13669. formatCode: node.attributes.formatCode.replace(/[\\](.)/g, '$1')
  13670. };
  13671. return true;
  13672. default:
  13673. return false;
  13674. }
  13675. }
  13676. parseText() {}
  13677. parseClose() {
  13678. return false;
  13679. }
  13680. }
  13681. NumFmtXform.getDefaultFmtId = function getDefaultFmtId(formatCode) {
  13682. return defaultFmtHash[formatCode];
  13683. };
  13684. NumFmtXform.getDefaultFmtCode = function getDefaultFmtCode(numFmtId) {
  13685. return defaultNumFormats[numFmtId] && defaultNumFormats[numFmtId].f;
  13686. };
  13687. module.exports = NumFmtXform;
  13688. },{"../../../utils/under-dash":26,"../../defaultnumformats":30,"../base-xform":32}],133:[function(require,module,exports){
  13689. "use strict";
  13690. const BaseXform = require('../base-xform');
  13691. const validation = {
  13692. boolean(value, dflt) {
  13693. if (value === undefined) {
  13694. return dflt;
  13695. }
  13696. return value;
  13697. }
  13698. };
  13699. // Protection encapsulates translation from style.protection model to/from xlsx
  13700. class ProtectionXform extends BaseXform {
  13701. get tag() {
  13702. return 'protection';
  13703. }
  13704. render(xmlStream, model) {
  13705. xmlStream.addRollback();
  13706. xmlStream.openNode('protection');
  13707. let isValid = false;
  13708. function add(name, value) {
  13709. if (value !== undefined) {
  13710. xmlStream.addAttribute(name, value);
  13711. isValid = true;
  13712. }
  13713. }
  13714. add('locked', validation.boolean(model.locked, true) ? undefined : '0');
  13715. add('hidden', validation.boolean(model.hidden, false) ? '1' : undefined);
  13716. xmlStream.closeNode();
  13717. if (isValid) {
  13718. xmlStream.commit();
  13719. } else {
  13720. xmlStream.rollback();
  13721. }
  13722. }
  13723. parseOpen(node) {
  13724. const model = {
  13725. locked: !(node.attributes.locked === '0'),
  13726. hidden: node.attributes.hidden === '1'
  13727. };
  13728. // only want to record models that differ from defaults
  13729. const isSignificant = !model.locked || model.hidden;
  13730. this.model = isSignificant ? model : null;
  13731. }
  13732. parseText() {}
  13733. parseClose() {
  13734. return false;
  13735. }
  13736. }
  13737. module.exports = ProtectionXform;
  13738. },{"../base-xform":32}],134:[function(require,module,exports){
  13739. "use strict";
  13740. const BaseXform = require('../base-xform');
  13741. const AlignmentXform = require('./alignment-xform');
  13742. const ProtectionXform = require('./protection-xform');
  13743. // <xf numFmtId="[numFmtId]" fontId="[fontId]" fillId="[fillId]" borderId="[xf.borderId]" xfId="[xfId]">
  13744. // Optional <alignment>
  13745. // Optional <protection>
  13746. // </xf>
  13747. // Style assists translation from style model to/from xlsx
  13748. class StyleXform extends BaseXform {
  13749. constructor(options) {
  13750. super();
  13751. this.xfId = !!(options && options.xfId);
  13752. this.map = {
  13753. alignment: new AlignmentXform(),
  13754. protection: new ProtectionXform()
  13755. };
  13756. }
  13757. get tag() {
  13758. return 'xf';
  13759. }
  13760. render(xmlStream, model) {
  13761. xmlStream.openNode('xf', {
  13762. numFmtId: model.numFmtId || 0,
  13763. fontId: model.fontId || 0,
  13764. fillId: model.fillId || 0,
  13765. borderId: model.borderId || 0
  13766. });
  13767. if (this.xfId) {
  13768. xmlStream.addAttribute('xfId', model.xfId || 0);
  13769. }
  13770. if (model.numFmtId) {
  13771. xmlStream.addAttribute('applyNumberFormat', '1');
  13772. }
  13773. if (model.fontId) {
  13774. xmlStream.addAttribute('applyFont', '1');
  13775. }
  13776. if (model.fillId) {
  13777. xmlStream.addAttribute('applyFill', '1');
  13778. }
  13779. if (model.borderId) {
  13780. xmlStream.addAttribute('applyBorder', '1');
  13781. }
  13782. if (model.alignment) {
  13783. xmlStream.addAttribute('applyAlignment', '1');
  13784. }
  13785. if (model.protection) {
  13786. xmlStream.addAttribute('applyProtection', '1');
  13787. }
  13788. /**
  13789. * Rendering tags causes close of XML stream.
  13790. * Therefore adding attributes must be done before rendering tags.
  13791. */
  13792. if (model.alignment) {
  13793. this.map.alignment.render(xmlStream, model.alignment);
  13794. }
  13795. if (model.protection) {
  13796. this.map.protection.render(xmlStream, model.protection);
  13797. }
  13798. xmlStream.closeNode();
  13799. }
  13800. parseOpen(node) {
  13801. if (this.parser) {
  13802. this.parser.parseOpen(node);
  13803. return true;
  13804. }
  13805. // used during sax parsing of xml to build font object
  13806. switch (node.name) {
  13807. case 'xf':
  13808. this.model = {
  13809. numFmtId: parseInt(node.attributes.numFmtId, 10),
  13810. fontId: parseInt(node.attributes.fontId, 10),
  13811. fillId: parseInt(node.attributes.fillId, 10),
  13812. borderId: parseInt(node.attributes.borderId, 10)
  13813. };
  13814. if (this.xfId) {
  13815. this.model.xfId = parseInt(node.attributes.xfId, 10);
  13816. }
  13817. return true;
  13818. case 'alignment':
  13819. this.parser = this.map.alignment;
  13820. this.parser.parseOpen(node);
  13821. return true;
  13822. case 'protection':
  13823. this.parser = this.map.protection;
  13824. this.parser.parseOpen(node);
  13825. return true;
  13826. default:
  13827. return false;
  13828. }
  13829. }
  13830. parseText(text) {
  13831. if (this.parser) {
  13832. this.parser.parseText(text);
  13833. }
  13834. }
  13835. parseClose(name) {
  13836. if (this.parser) {
  13837. if (!this.parser.parseClose(name)) {
  13838. if (this.map.protection === this.parser) {
  13839. this.model.protection = this.parser.model;
  13840. } else {
  13841. this.model.alignment = this.parser.model;
  13842. }
  13843. this.parser = undefined;
  13844. }
  13845. return true;
  13846. }
  13847. return name !== 'xf';
  13848. }
  13849. }
  13850. module.exports = StyleXform;
  13851. },{"../base-xform":32,"./alignment-xform":126,"./protection-xform":133}],135:[function(require,module,exports){
  13852. "use strict";
  13853. /* eslint-disable max-classes-per-file */
  13854. const Enums = require('../../../doc/enums');
  13855. const XmlStream = require('../../../utils/xml-stream');
  13856. const BaseXform = require('../base-xform');
  13857. const StaticXform = require('../static-xform');
  13858. const ListXform = require('../list-xform');
  13859. const FontXform = require('./font-xform');
  13860. const FillXform = require('./fill-xform');
  13861. const BorderXform = require('./border-xform');
  13862. const NumFmtXform = require('./numfmt-xform');
  13863. const StyleXform = require('./style-xform');
  13864. const DxfXform = require('./dxf-xform');
  13865. // custom numfmt ids start here
  13866. const NUMFMT_BASE = 164;
  13867. // =============================================================================
  13868. // StylesXform is used to generate and parse the styles.xml file
  13869. // it manages the collections of fonts, number formats, alignments, etc
  13870. class StylesXform extends BaseXform {
  13871. constructor(initialise) {
  13872. super();
  13873. this.map = {
  13874. numFmts: new ListXform({
  13875. tag: 'numFmts',
  13876. count: true,
  13877. childXform: new NumFmtXform()
  13878. }),
  13879. fonts: new ListXform({
  13880. tag: 'fonts',
  13881. count: true,
  13882. childXform: new FontXform(),
  13883. $: {
  13884. 'x14ac:knownFonts': 1
  13885. }
  13886. }),
  13887. fills: new ListXform({
  13888. tag: 'fills',
  13889. count: true,
  13890. childXform: new FillXform()
  13891. }),
  13892. borders: new ListXform({
  13893. tag: 'borders',
  13894. count: true,
  13895. childXform: new BorderXform()
  13896. }),
  13897. cellStyleXfs: new ListXform({
  13898. tag: 'cellStyleXfs',
  13899. count: true,
  13900. childXform: new StyleXform()
  13901. }),
  13902. cellXfs: new ListXform({
  13903. tag: 'cellXfs',
  13904. count: true,
  13905. childXform: new StyleXform({
  13906. xfId: true
  13907. })
  13908. }),
  13909. dxfs: new ListXform({
  13910. tag: 'dxfs',
  13911. always: true,
  13912. count: true,
  13913. childXform: new DxfXform()
  13914. }),
  13915. // for style manager
  13916. numFmt: new NumFmtXform(),
  13917. font: new FontXform(),
  13918. fill: new FillXform(),
  13919. border: new BorderXform(),
  13920. style: new StyleXform({
  13921. xfId: true
  13922. }),
  13923. cellStyles: StylesXform.STATIC_XFORMS.cellStyles,
  13924. tableStyles: StylesXform.STATIC_XFORMS.tableStyles,
  13925. extLst: StylesXform.STATIC_XFORMS.extLst
  13926. };
  13927. if (initialise) {
  13928. // StylesXform also acts as style manager and is used to build up styles-model during worksheet processing
  13929. this.init();
  13930. }
  13931. }
  13932. initIndex() {
  13933. this.index = {
  13934. style: {},
  13935. numFmt: {},
  13936. numFmtNextId: 164,
  13937. // start custom format ids here
  13938. font: {},
  13939. border: {},
  13940. fill: {}
  13941. };
  13942. }
  13943. init() {
  13944. // Prepare for Style Manager role
  13945. this.model = {
  13946. styles: [],
  13947. numFmts: [],
  13948. fonts: [],
  13949. borders: [],
  13950. fills: [],
  13951. dxfs: []
  13952. };
  13953. this.initIndex();
  13954. // default (zero) border
  13955. this._addBorder({});
  13956. // add default (all zero) style
  13957. this._addStyle({
  13958. numFmtId: 0,
  13959. fontId: 0,
  13960. fillId: 0,
  13961. borderId: 0,
  13962. xfId: 0
  13963. });
  13964. // add default fills
  13965. this._addFill({
  13966. type: 'pattern',
  13967. pattern: 'none'
  13968. });
  13969. this._addFill({
  13970. type: 'pattern',
  13971. pattern: 'gray125'
  13972. });
  13973. this.weakMap = new WeakMap();
  13974. }
  13975. render(xmlStream, model) {
  13976. model = model || this.model;
  13977. //
  13978. // <fonts count="2" x14ac:knownFonts="1">
  13979. xmlStream.openXml(XmlStream.StdDocAttributes);
  13980. xmlStream.openNode('styleSheet', StylesXform.STYLESHEET_ATTRIBUTES);
  13981. if (this.index) {
  13982. // model has been built by style manager role (contains xml)
  13983. if (model.numFmts && model.numFmts.length) {
  13984. xmlStream.openNode('numFmts', {
  13985. count: model.numFmts.length
  13986. });
  13987. model.numFmts.forEach(numFmtXml => {
  13988. xmlStream.writeXml(numFmtXml);
  13989. });
  13990. xmlStream.closeNode();
  13991. }
  13992. if (!model.fonts.length) {
  13993. // default (zero) font
  13994. this._addFont({
  13995. size: 11,
  13996. color: {
  13997. theme: 1
  13998. },
  13999. name: 'Calibri',
  14000. family: 2,
  14001. scheme: 'minor'
  14002. });
  14003. }
  14004. xmlStream.openNode('fonts', {
  14005. count: model.fonts.length,
  14006. 'x14ac:knownFonts': 1
  14007. });
  14008. model.fonts.forEach(fontXml => {
  14009. xmlStream.writeXml(fontXml);
  14010. });
  14011. xmlStream.closeNode();
  14012. xmlStream.openNode('fills', {
  14013. count: model.fills.length
  14014. });
  14015. model.fills.forEach(fillXml => {
  14016. xmlStream.writeXml(fillXml);
  14017. });
  14018. xmlStream.closeNode();
  14019. xmlStream.openNode('borders', {
  14020. count: model.borders.length
  14021. });
  14022. model.borders.forEach(borderXml => {
  14023. xmlStream.writeXml(borderXml);
  14024. });
  14025. xmlStream.closeNode();
  14026. this.map.cellStyleXfs.render(xmlStream, [{
  14027. numFmtId: 0,
  14028. fontId: 0,
  14029. fillId: 0,
  14030. borderId: 0,
  14031. xfId: 0
  14032. }]);
  14033. xmlStream.openNode('cellXfs', {
  14034. count: model.styles.length
  14035. });
  14036. model.styles.forEach(styleXml => {
  14037. xmlStream.writeXml(styleXml);
  14038. });
  14039. xmlStream.closeNode();
  14040. } else {
  14041. // model is plain JSON and needs to be xformed
  14042. this.map.numFmts.render(xmlStream, model.numFmts);
  14043. this.map.fonts.render(xmlStream, model.fonts);
  14044. this.map.fills.render(xmlStream, model.fills);
  14045. this.map.borders.render(xmlStream, model.borders);
  14046. this.map.cellStyleXfs.render(xmlStream, [{
  14047. numFmtId: 0,
  14048. fontId: 0,
  14049. fillId: 0,
  14050. borderId: 0,
  14051. xfId: 0
  14052. }]);
  14053. this.map.cellXfs.render(xmlStream, model.styles);
  14054. }
  14055. StylesXform.STATIC_XFORMS.cellStyles.render(xmlStream);
  14056. this.map.dxfs.render(xmlStream, model.dxfs);
  14057. StylesXform.STATIC_XFORMS.tableStyles.render(xmlStream);
  14058. StylesXform.STATIC_XFORMS.extLst.render(xmlStream);
  14059. xmlStream.closeNode();
  14060. }
  14061. parseOpen(node) {
  14062. if (this.parser) {
  14063. this.parser.parseOpen(node);
  14064. return true;
  14065. }
  14066. switch (node.name) {
  14067. case 'styleSheet':
  14068. this.initIndex();
  14069. return true;
  14070. default:
  14071. this.parser = this.map[node.name];
  14072. if (this.parser) {
  14073. this.parser.parseOpen(node);
  14074. }
  14075. return true;
  14076. }
  14077. }
  14078. parseText(text) {
  14079. if (this.parser) {
  14080. this.parser.parseText(text);
  14081. }
  14082. }
  14083. parseClose(name) {
  14084. if (this.parser) {
  14085. if (!this.parser.parseClose(name)) {
  14086. this.parser = undefined;
  14087. }
  14088. return true;
  14089. }
  14090. switch (name) {
  14091. case 'styleSheet':
  14092. {
  14093. this.model = {};
  14094. const add = (propName, xform) => {
  14095. if (xform.model && xform.model.length) {
  14096. this.model[propName] = xform.model;
  14097. }
  14098. };
  14099. add('numFmts', this.map.numFmts);
  14100. add('fonts', this.map.fonts);
  14101. add('fills', this.map.fills);
  14102. add('borders', this.map.borders);
  14103. add('styles', this.map.cellXfs);
  14104. add('dxfs', this.map.dxfs);
  14105. // index numFmts
  14106. this.index = {
  14107. model: [],
  14108. numFmt: []
  14109. };
  14110. if (this.model.numFmts) {
  14111. const numFmtIndex = this.index.numFmt;
  14112. this.model.numFmts.forEach(numFmt => {
  14113. numFmtIndex[numFmt.id] = numFmt.formatCode;
  14114. });
  14115. }
  14116. return false;
  14117. }
  14118. default:
  14119. // not quite sure how we get here!
  14120. return true;
  14121. }
  14122. }
  14123. // add a cell's style model to the collection
  14124. // each style property is processed and cross-referenced, etc.
  14125. // the styleId is returned. Note: cellType is used when numFmt not defined
  14126. addStyleModel(model, cellType) {
  14127. if (!model) {
  14128. return 0;
  14129. }
  14130. // if we have no default font, add it here now
  14131. if (!this.model.fonts.length) {
  14132. // default (zero) font
  14133. this._addFont({
  14134. size: 11,
  14135. color: {
  14136. theme: 1
  14137. },
  14138. name: 'Calibri',
  14139. family: 2,
  14140. scheme: 'minor'
  14141. });
  14142. }
  14143. // if we have seen this style object before, assume it has the same styleId
  14144. if (this.weakMap && this.weakMap.has(model)) {
  14145. return this.weakMap.get(model);
  14146. }
  14147. const style = {};
  14148. cellType = cellType || Enums.ValueType.Number;
  14149. if (model.numFmt) {
  14150. style.numFmtId = this._addNumFmtStr(model.numFmt);
  14151. } else {
  14152. switch (cellType) {
  14153. case Enums.ValueType.Number:
  14154. style.numFmtId = this._addNumFmtStr('General');
  14155. break;
  14156. case Enums.ValueType.Date:
  14157. style.numFmtId = this._addNumFmtStr('mm-dd-yy');
  14158. break;
  14159. default:
  14160. break;
  14161. }
  14162. }
  14163. if (model.font) {
  14164. style.fontId = this._addFont(model.font);
  14165. }
  14166. if (model.border) {
  14167. style.borderId = this._addBorder(model.border);
  14168. }
  14169. if (model.fill) {
  14170. style.fillId = this._addFill(model.fill);
  14171. }
  14172. if (model.alignment) {
  14173. style.alignment = model.alignment;
  14174. }
  14175. if (model.protection) {
  14176. style.protection = model.protection;
  14177. }
  14178. const styleId = this._addStyle(style);
  14179. if (this.weakMap) {
  14180. this.weakMap.set(model, styleId);
  14181. }
  14182. return styleId;
  14183. }
  14184. // given a styleId (i.e. s="n"), get the cell's style model
  14185. // objects are shared where possible.
  14186. getStyleModel(id) {
  14187. // if the style doesn't exist return null
  14188. const style = this.model.styles[id];
  14189. if (!style) return null;
  14190. // have we built this model before?
  14191. let model = this.index.model[id];
  14192. if (model) return model;
  14193. // build a new model
  14194. model = this.index.model[id] = {};
  14195. // -------------------------------------------------------
  14196. // number format
  14197. if (style.numFmtId) {
  14198. const numFmt = this.index.numFmt[style.numFmtId] || NumFmtXform.getDefaultFmtCode(style.numFmtId);
  14199. if (numFmt) {
  14200. model.numFmt = numFmt;
  14201. }
  14202. }
  14203. function addStyle(name, group, styleId) {
  14204. if (styleId || styleId === 0) {
  14205. const part = group[styleId];
  14206. if (part) {
  14207. model[name] = part;
  14208. }
  14209. }
  14210. }
  14211. addStyle('font', this.model.fonts, style.fontId);
  14212. addStyle('border', this.model.borders, style.borderId);
  14213. addStyle('fill', this.model.fills, style.fillId);
  14214. // -------------------------------------------------------
  14215. // alignment
  14216. if (style.alignment) {
  14217. model.alignment = style.alignment;
  14218. }
  14219. // -------------------------------------------------------
  14220. // protection
  14221. if (style.protection) {
  14222. model.protection = style.protection;
  14223. }
  14224. return model;
  14225. }
  14226. addDxfStyle(style) {
  14227. if (style.numFmt) {
  14228. // register numFmtId to use it during dxf-xform rendering
  14229. style.numFmtId = this._addNumFmtStr(style.numFmt);
  14230. }
  14231. this.model.dxfs.push(style);
  14232. return this.model.dxfs.length - 1;
  14233. }
  14234. getDxfStyle(id) {
  14235. return this.model.dxfs[id];
  14236. }
  14237. // =========================================================================
  14238. // Private Interface
  14239. _addStyle(style) {
  14240. const xml = this.map.style.toXml(style);
  14241. let index = this.index.style[xml];
  14242. if (index === undefined) {
  14243. index = this.index.style[xml] = this.model.styles.length;
  14244. this.model.styles.push(xml);
  14245. }
  14246. return index;
  14247. }
  14248. // =========================================================================
  14249. // Number Formats
  14250. _addNumFmtStr(formatCode) {
  14251. // check if default format
  14252. let index = NumFmtXform.getDefaultFmtId(formatCode);
  14253. if (index !== undefined) return index;
  14254. // check if already in
  14255. index = this.index.numFmt[formatCode];
  14256. if (index !== undefined) return index;
  14257. index = this.index.numFmt[formatCode] = NUMFMT_BASE + this.model.numFmts.length;
  14258. const xml = this.map.numFmt.toXml({
  14259. id: index,
  14260. formatCode
  14261. });
  14262. this.model.numFmts.push(xml);
  14263. return index;
  14264. }
  14265. // =========================================================================
  14266. // Fonts
  14267. _addFont(font) {
  14268. const xml = this.map.font.toXml(font);
  14269. let index = this.index.font[xml];
  14270. if (index === undefined) {
  14271. index = this.index.font[xml] = this.model.fonts.length;
  14272. this.model.fonts.push(xml);
  14273. }
  14274. return index;
  14275. }
  14276. // =========================================================================
  14277. // Borders
  14278. _addBorder(border) {
  14279. const xml = this.map.border.toXml(border);
  14280. let index = this.index.border[xml];
  14281. if (index === undefined) {
  14282. index = this.index.border[xml] = this.model.borders.length;
  14283. this.model.borders.push(xml);
  14284. }
  14285. return index;
  14286. }
  14287. // =========================================================================
  14288. // Fills
  14289. _addFill(fill) {
  14290. const xml = this.map.fill.toXml(fill);
  14291. let index = this.index.fill[xml];
  14292. if (index === undefined) {
  14293. index = this.index.fill[xml] = this.model.fills.length;
  14294. this.model.fills.push(xml);
  14295. }
  14296. return index;
  14297. }
  14298. // =========================================================================
  14299. }
  14300. StylesXform.STYLESHEET_ATTRIBUTES = {
  14301. xmlns: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  14302. 'xmlns:mc': 'http://schemas.openxmlformats.org/markup-compatibility/2006',
  14303. 'mc:Ignorable': 'x14ac x16r2',
  14304. 'xmlns:x14ac': 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac',
  14305. 'xmlns:x16r2': 'http://schemas.microsoft.com/office/spreadsheetml/2015/02/main'
  14306. };
  14307. StylesXform.STATIC_XFORMS = {
  14308. cellStyles: new StaticXform({
  14309. tag: 'cellStyles',
  14310. $: {
  14311. count: 1
  14312. },
  14313. c: [{
  14314. tag: 'cellStyle',
  14315. $: {
  14316. name: 'Normal',
  14317. xfId: 0,
  14318. builtinId: 0
  14319. }
  14320. }]
  14321. }),
  14322. dxfs: new StaticXform({
  14323. tag: 'dxfs',
  14324. $: {
  14325. count: 0
  14326. }
  14327. }),
  14328. tableStyles: new StaticXform({
  14329. tag: 'tableStyles',
  14330. $: {
  14331. count: 0,
  14332. defaultTableStyle: 'TableStyleMedium2',
  14333. defaultPivotStyle: 'PivotStyleLight16'
  14334. }
  14335. }),
  14336. extLst: new StaticXform({
  14337. tag: 'extLst',
  14338. c: [{
  14339. tag: 'ext',
  14340. $: {
  14341. uri: '{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}',
  14342. 'xmlns:x14': 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'
  14343. },
  14344. c: [{
  14345. tag: 'x14:slicerStyles',
  14346. $: {
  14347. defaultSlicerStyle: 'SlicerStyleLight1'
  14348. }
  14349. }]
  14350. }, {
  14351. tag: 'ext',
  14352. $: {
  14353. uri: '{9260A510-F301-46a8-8635-F512D64BE5F5}',
  14354. 'xmlns:x15': 'http://schemas.microsoft.com/office/spreadsheetml/2010/11/main'
  14355. },
  14356. c: [{
  14357. tag: 'x15:timelineStyles',
  14358. $: {
  14359. defaultTimelineStyle: 'TimeSlicerStyleLight1'
  14360. }
  14361. }]
  14362. }]
  14363. })
  14364. };
  14365. // the stylemanager mock acts like StyleManager except that it always returns 0 or {}
  14366. class StylesXformMock extends StylesXform {
  14367. constructor() {
  14368. super();
  14369. this.model = {
  14370. styles: [{
  14371. numFmtId: 0,
  14372. fontId: 0,
  14373. fillId: 0,
  14374. borderId: 0,
  14375. xfId: 0
  14376. }],
  14377. numFmts: [],
  14378. fonts: [{
  14379. size: 11,
  14380. color: {
  14381. theme: 1
  14382. },
  14383. name: 'Calibri',
  14384. family: 2,
  14385. scheme: 'minor'
  14386. }],
  14387. borders: [{}],
  14388. fills: [{
  14389. type: 'pattern',
  14390. pattern: 'none'
  14391. }, {
  14392. type: 'pattern',
  14393. pattern: 'gray125'
  14394. }]
  14395. };
  14396. }
  14397. // =========================================================================
  14398. // Style Manager Interface
  14399. // override normal behaviour - consume and dispose
  14400. parseStream(stream) {
  14401. stream.autodrain();
  14402. return Promise.resolve();
  14403. }
  14404. // add a cell's style model to the collection
  14405. // each style property is processed and cross-referenced, etc.
  14406. // the styleId is returned. Note: cellType is used when numFmt not defined
  14407. addStyleModel(model, cellType) {
  14408. switch (cellType) {
  14409. case Enums.ValueType.Date:
  14410. return this.dateStyleId;
  14411. default:
  14412. return 0;
  14413. }
  14414. }
  14415. get dateStyleId() {
  14416. if (!this._dateStyleId) {
  14417. const dateStyle = {
  14418. numFmtId: NumFmtXform.getDefaultFmtId('mm-dd-yy')
  14419. };
  14420. this._dateStyleId = this.model.styles.length;
  14421. this.model.styles.push(dateStyle);
  14422. }
  14423. return this._dateStyleId;
  14424. }
  14425. // given a styleId (i.e. s="n"), get the cell's style model
  14426. // objects are shared where possible.
  14427. getStyleModel( /* id */
  14428. ) {
  14429. return {};
  14430. }
  14431. }
  14432. StylesXform.Mock = StylesXformMock;
  14433. module.exports = StylesXform;
  14434. },{"../../../doc/enums":7,"../../../utils/xml-stream":28,"../base-xform":32,"../list-xform":71,"../static-xform":120,"./border-xform":127,"./dxf-xform":129,"./fill-xform":130,"./font-xform":131,"./numfmt-xform":132,"./style-xform":134}],136:[function(require,module,exports){
  14435. "use strict";
  14436. const BaseXform = require('../base-xform');
  14437. class UnderlineXform extends BaseXform {
  14438. constructor(model) {
  14439. super();
  14440. this.model = model;
  14441. }
  14442. get tag() {
  14443. return 'u';
  14444. }
  14445. render(xmlStream, model) {
  14446. model = model || this.model;
  14447. if (model === true) {
  14448. xmlStream.leafNode('u');
  14449. } else {
  14450. const attr = UnderlineXform.Attributes[model];
  14451. if (attr) {
  14452. xmlStream.leafNode('u', attr);
  14453. }
  14454. }
  14455. }
  14456. parseOpen(node) {
  14457. if (node.name === 'u') {
  14458. this.model = node.attributes.val || true;
  14459. }
  14460. }
  14461. parseText() {}
  14462. parseClose() {
  14463. return false;
  14464. }
  14465. }
  14466. UnderlineXform.Attributes = {
  14467. single: {},
  14468. double: {
  14469. val: 'double'
  14470. },
  14471. singleAccounting: {
  14472. val: 'singleAccounting'
  14473. },
  14474. doubleAccounting: {
  14475. val: 'doubleAccounting'
  14476. }
  14477. };
  14478. module.exports = UnderlineXform;
  14479. },{"../base-xform":32}],137:[function(require,module,exports){
  14480. "use strict";
  14481. const BaseXform = require('../base-xform');
  14482. const FilterColumnXform = require('./filter-column-xform');
  14483. class AutoFilterXform extends BaseXform {
  14484. constructor() {
  14485. super();
  14486. this.map = {
  14487. filterColumn: new FilterColumnXform()
  14488. };
  14489. }
  14490. get tag() {
  14491. return 'autoFilter';
  14492. }
  14493. prepare(model) {
  14494. model.columns.forEach((column, index) => {
  14495. this.map.filterColumn.prepare(column, {
  14496. index
  14497. });
  14498. });
  14499. }
  14500. render(xmlStream, model) {
  14501. xmlStream.openNode(this.tag, {
  14502. ref: model.autoFilterRef
  14503. });
  14504. model.columns.forEach(column => {
  14505. this.map.filterColumn.render(xmlStream, column);
  14506. });
  14507. xmlStream.closeNode();
  14508. return true;
  14509. }
  14510. parseOpen(node) {
  14511. if (this.parser) {
  14512. this.parser.parseOpen(node);
  14513. return true;
  14514. }
  14515. switch (node.name) {
  14516. case this.tag:
  14517. this.model = {
  14518. autoFilterRef: node.attributes.ref,
  14519. columns: []
  14520. };
  14521. return true;
  14522. default:
  14523. this.parser = this.map[node.name];
  14524. if (this.parser) {
  14525. this.parseOpen(node);
  14526. return true;
  14527. }
  14528. throw new Error(`Unexpected xml node in parseOpen: ${JSON.stringify(node)}`);
  14529. }
  14530. }
  14531. parseText(text) {
  14532. if (this.parser) {
  14533. this.parser.parseText(text);
  14534. }
  14535. }
  14536. parseClose(name) {
  14537. if (this.parser) {
  14538. if (!this.parser.parseClose(name)) {
  14539. this.model.columns.push(this.parser.model);
  14540. this.parser = undefined;
  14541. }
  14542. return true;
  14543. }
  14544. switch (name) {
  14545. case this.tag:
  14546. return false;
  14547. default:
  14548. throw new Error(`Unexpected xml node in parseClose: ${name}`);
  14549. }
  14550. }
  14551. }
  14552. module.exports = AutoFilterXform;
  14553. },{"../base-xform":32,"./filter-column-xform":139}],138:[function(require,module,exports){
  14554. "use strict";
  14555. const BaseXform = require('../base-xform');
  14556. class CustomFilterXform extends BaseXform {
  14557. get tag() {
  14558. return 'customFilter';
  14559. }
  14560. render(xmlStream, model) {
  14561. xmlStream.leafNode(this.tag, {
  14562. val: model.val,
  14563. operator: model.operator
  14564. });
  14565. }
  14566. parseOpen(node) {
  14567. if (node.name === this.tag) {
  14568. this.model = {
  14569. val: node.attributes.val,
  14570. operator: node.attributes.operator
  14571. };
  14572. return true;
  14573. }
  14574. return false;
  14575. }
  14576. parseText() {}
  14577. parseClose() {
  14578. return false;
  14579. }
  14580. }
  14581. module.exports = CustomFilterXform;
  14582. },{"../base-xform":32}],139:[function(require,module,exports){
  14583. "use strict";
  14584. const BaseXform = require('../base-xform');
  14585. const ListXform = require('../list-xform');
  14586. const CustomFilterXform = require('./custom-filter-xform');
  14587. const FilterXform = require('./filter-xform');
  14588. class FilterColumnXform extends BaseXform {
  14589. constructor() {
  14590. super();
  14591. this.map = {
  14592. customFilters: new ListXform({
  14593. tag: 'customFilters',
  14594. count: false,
  14595. empty: true,
  14596. childXform: new CustomFilterXform()
  14597. }),
  14598. filters: new ListXform({
  14599. tag: 'filters',
  14600. count: false,
  14601. empty: true,
  14602. childXform: new FilterXform()
  14603. })
  14604. };
  14605. }
  14606. get tag() {
  14607. return 'filterColumn';
  14608. }
  14609. prepare(model, options) {
  14610. model.colId = options.index.toString();
  14611. }
  14612. render(xmlStream, model) {
  14613. if (model.customFilters) {
  14614. xmlStream.openNode(this.tag, {
  14615. colId: model.colId,
  14616. hiddenButton: model.filterButton ? '0' : '1'
  14617. });
  14618. this.map.customFilters.render(xmlStream, model.customFilters);
  14619. xmlStream.closeNode();
  14620. return true;
  14621. }
  14622. xmlStream.leafNode(this.tag, {
  14623. colId: model.colId,
  14624. hiddenButton: model.filterButton ? '0' : '1'
  14625. });
  14626. return true;
  14627. }
  14628. parseOpen(node) {
  14629. if (this.parser) {
  14630. this.parser.parseOpen(node);
  14631. return true;
  14632. }
  14633. const {
  14634. attributes
  14635. } = node;
  14636. switch (node.name) {
  14637. case this.tag:
  14638. this.model = {
  14639. filterButton: attributes.hiddenButton === '0'
  14640. };
  14641. return true;
  14642. default:
  14643. this.parser = this.map[node.name];
  14644. if (this.parser) {
  14645. this.parseOpen(node);
  14646. return true;
  14647. }
  14648. throw new Error(`Unexpected xml node in parseOpen: ${JSON.stringify(node)}`);
  14649. }
  14650. }
  14651. parseText() {}
  14652. parseClose(name) {
  14653. if (this.parser) {
  14654. if (!this.parser.parseClose(name)) {
  14655. this.parser = undefined;
  14656. }
  14657. return true;
  14658. }
  14659. switch (name) {
  14660. case this.tag:
  14661. this.model.customFilters = this.map.customFilters.model;
  14662. return false;
  14663. default:
  14664. // could be some unrecognised tags
  14665. return true;
  14666. }
  14667. }
  14668. }
  14669. module.exports = FilterColumnXform;
  14670. },{"../base-xform":32,"../list-xform":71,"./custom-filter-xform":138,"./filter-xform":140}],140:[function(require,module,exports){
  14671. "use strict";
  14672. const BaseXform = require('../base-xform');
  14673. class FilterXform extends BaseXform {
  14674. get tag() {
  14675. return 'filter';
  14676. }
  14677. render(xmlStream, model) {
  14678. xmlStream.leafNode(this.tag, {
  14679. val: model.val
  14680. });
  14681. }
  14682. parseOpen(node) {
  14683. if (node.name === this.tag) {
  14684. this.model = {
  14685. val: node.attributes.val
  14686. };
  14687. return true;
  14688. }
  14689. return false;
  14690. }
  14691. parseText() {}
  14692. parseClose() {
  14693. return false;
  14694. }
  14695. }
  14696. module.exports = FilterXform;
  14697. },{"../base-xform":32}],141:[function(require,module,exports){
  14698. "use strict";
  14699. const BaseXform = require('../base-xform');
  14700. class TableColumnXform extends BaseXform {
  14701. get tag() {
  14702. return 'tableColumn';
  14703. }
  14704. prepare(model, options) {
  14705. model.id = options.index + 1;
  14706. }
  14707. render(xmlStream, model) {
  14708. xmlStream.leafNode(this.tag, {
  14709. id: model.id.toString(),
  14710. name: model.name,
  14711. totalsRowLabel: model.totalsRowLabel,
  14712. totalsRowFunction: model.totalsRowFunction,
  14713. dxfId: model.dxfId
  14714. });
  14715. return true;
  14716. }
  14717. parseOpen(node) {
  14718. if (node.name === this.tag) {
  14719. const {
  14720. attributes
  14721. } = node;
  14722. this.model = {
  14723. name: attributes.name,
  14724. totalsRowLabel: attributes.totalsRowLabel,
  14725. totalsRowFunction: attributes.totalsRowFunction,
  14726. dxfId: attributes.dxfId
  14727. };
  14728. return true;
  14729. }
  14730. return false;
  14731. }
  14732. parseText() {}
  14733. parseClose() {
  14734. return false;
  14735. }
  14736. }
  14737. module.exports = TableColumnXform;
  14738. },{"../base-xform":32}],142:[function(require,module,exports){
  14739. "use strict";
  14740. const BaseXform = require('../base-xform');
  14741. class TableStyleInfoXform extends BaseXform {
  14742. get tag() {
  14743. return 'tableStyleInfo';
  14744. }
  14745. render(xmlStream, model) {
  14746. xmlStream.leafNode(this.tag, {
  14747. name: model.theme ? model.theme : undefined,
  14748. showFirstColumn: model.showFirstColumn ? '1' : '0',
  14749. showLastColumn: model.showLastColumn ? '1' : '0',
  14750. showRowStripes: model.showRowStripes ? '1' : '0',
  14751. showColumnStripes: model.showColumnStripes ? '1' : '0'
  14752. });
  14753. return true;
  14754. }
  14755. parseOpen(node) {
  14756. if (node.name === this.tag) {
  14757. const {
  14758. attributes
  14759. } = node;
  14760. this.model = {
  14761. theme: attributes.name ? attributes.name : null,
  14762. showFirstColumn: attributes.showFirstColumn === '1',
  14763. showLastColumn: attributes.showLastColumn === '1',
  14764. showRowStripes: attributes.showRowStripes === '1',
  14765. showColumnStripes: attributes.showColumnStripes === '1'
  14766. };
  14767. return true;
  14768. }
  14769. return false;
  14770. }
  14771. parseText() {}
  14772. parseClose() {
  14773. return false;
  14774. }
  14775. }
  14776. module.exports = TableStyleInfoXform;
  14777. },{"../base-xform":32}],143:[function(require,module,exports){
  14778. "use strict";
  14779. const XmlStream = require('../../../utils/xml-stream');
  14780. const BaseXform = require('../base-xform');
  14781. const ListXform = require('../list-xform');
  14782. const AutoFilterXform = require('./auto-filter-xform');
  14783. const TableColumnXform = require('./table-column-xform');
  14784. const TableStyleInfoXform = require('./table-style-info-xform');
  14785. class TableXform extends BaseXform {
  14786. constructor() {
  14787. super();
  14788. this.map = {
  14789. autoFilter: new AutoFilterXform(),
  14790. tableColumns: new ListXform({
  14791. tag: 'tableColumns',
  14792. count: true,
  14793. empty: true,
  14794. childXform: new TableColumnXform()
  14795. }),
  14796. tableStyleInfo: new TableStyleInfoXform()
  14797. };
  14798. }
  14799. prepare(model, options) {
  14800. this.map.autoFilter.prepare(model);
  14801. this.map.tableColumns.prepare(model.columns, options);
  14802. }
  14803. get tag() {
  14804. return 'table';
  14805. }
  14806. render(xmlStream, model) {
  14807. xmlStream.openXml(XmlStream.StdDocAttributes);
  14808. xmlStream.openNode(this.tag, {
  14809. ...TableXform.TABLE_ATTRIBUTES,
  14810. id: model.id,
  14811. name: model.name,
  14812. displayName: model.displayName || model.name,
  14813. ref: model.tableRef,
  14814. totalsRowCount: model.totalsRow ? '1' : undefined,
  14815. totalsRowShown: model.totalsRow ? undefined : '1',
  14816. headerRowCount: model.headerRow ? '1' : '0'
  14817. });
  14818. this.map.autoFilter.render(xmlStream, model);
  14819. this.map.tableColumns.render(xmlStream, model.columns);
  14820. this.map.tableStyleInfo.render(xmlStream, model.style);
  14821. xmlStream.closeNode();
  14822. }
  14823. parseOpen(node) {
  14824. if (this.parser) {
  14825. this.parser.parseOpen(node);
  14826. return true;
  14827. }
  14828. const {
  14829. name,
  14830. attributes
  14831. } = node;
  14832. switch (name) {
  14833. case this.tag:
  14834. this.reset();
  14835. this.model = {
  14836. name: attributes.name,
  14837. displayName: attributes.displayName || attributes.name,
  14838. tableRef: attributes.ref,
  14839. totalsRow: attributes.totalsRowCount === '1',
  14840. headerRow: attributes.headerRowCount === '1'
  14841. };
  14842. break;
  14843. default:
  14844. this.parser = this.map[node.name];
  14845. if (this.parser) {
  14846. this.parser.parseOpen(node);
  14847. }
  14848. break;
  14849. }
  14850. return true;
  14851. }
  14852. parseText(text) {
  14853. if (this.parser) {
  14854. this.parser.parseText(text);
  14855. }
  14856. }
  14857. parseClose(name) {
  14858. if (this.parser) {
  14859. if (!this.parser.parseClose(name)) {
  14860. this.parser = undefined;
  14861. }
  14862. return true;
  14863. }
  14864. switch (name) {
  14865. case this.tag:
  14866. this.model.columns = this.map.tableColumns.model;
  14867. if (this.map.autoFilter.model) {
  14868. this.model.autoFilterRef = this.map.autoFilter.model.autoFilterRef;
  14869. this.map.autoFilter.model.columns.forEach((column, index) => {
  14870. this.model.columns[index].filterButton = column.filterButton;
  14871. });
  14872. }
  14873. this.model.style = this.map.tableStyleInfo.model;
  14874. return false;
  14875. default:
  14876. // could be some unrecognised tags
  14877. return true;
  14878. }
  14879. }
  14880. reconcile(model, options) {
  14881. // fetch the dfxs from styles
  14882. model.columns.forEach(column => {
  14883. if (column.dxfId !== undefined) {
  14884. column.style = options.styles.getDxfStyle(column.dxfId);
  14885. }
  14886. });
  14887. }
  14888. }
  14889. TableXform.TABLE_ATTRIBUTES = {
  14890. xmlns: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  14891. 'xmlns:mc': 'http://schemas.openxmlformats.org/markup-compatibility/2006',
  14892. 'mc:Ignorable': 'xr xr3',
  14893. 'xmlns:xr': 'http://schemas.microsoft.com/office/spreadsheetml/2014/revision',
  14894. 'xmlns:xr3': 'http://schemas.microsoft.com/office/spreadsheetml/2016/revision3'
  14895. // 'xr:uid': '{00000000-000C-0000-FFFF-FFFF00000000}',
  14896. };
  14897. module.exports = TableXform;
  14898. },{"../../../utils/xml-stream":28,"../base-xform":32,"../list-xform":71,"./auto-filter-xform":137,"./table-column-xform":141,"./table-style-info-xform":142}],144:[function(require,module,exports){
  14899. (function (process,Buffer){(function (){
  14900. "use strict";
  14901. const fs = require('fs');
  14902. const JSZip = require('jszip');
  14903. const {
  14904. PassThrough
  14905. } = require('readable-stream');
  14906. const ZipStream = require('../utils/zip-stream');
  14907. const StreamBuf = require('../utils/stream-buf');
  14908. const utils = require('../utils/utils');
  14909. const XmlStream = require('../utils/xml-stream');
  14910. const {
  14911. bufferToString
  14912. } = require('../utils/browser-buffer-decode');
  14913. const StylesXform = require('./xform/style/styles-xform');
  14914. const CoreXform = require('./xform/core/core-xform');
  14915. const SharedStringsXform = require('./xform/strings/shared-strings-xform');
  14916. const RelationshipsXform = require('./xform/core/relationships-xform');
  14917. const ContentTypesXform = require('./xform/core/content-types-xform');
  14918. const AppXform = require('./xform/core/app-xform');
  14919. const WorkbookXform = require('./xform/book/workbook-xform');
  14920. const WorksheetXform = require('./xform/sheet/worksheet-xform');
  14921. const DrawingXform = require('./xform/drawing/drawing-xform');
  14922. const TableXform = require('./xform/table/table-xform');
  14923. const CommentsXform = require('./xform/comment/comments-xform');
  14924. const VmlNotesXform = require('./xform/comment/vml-notes-xform');
  14925. const theme1Xml = require('./xml/theme1');
  14926. function fsReadFileAsync(filename, options) {
  14927. return new Promise((resolve, reject) => {
  14928. fs.readFile(filename, options, (error, data) => {
  14929. if (error) {
  14930. reject(error);
  14931. } else {
  14932. resolve(data);
  14933. }
  14934. });
  14935. });
  14936. }
  14937. class XLSX {
  14938. constructor(workbook) {
  14939. this.workbook = workbook;
  14940. }
  14941. // ===============================================================================
  14942. // Workbook
  14943. // =========================================================================
  14944. // Read
  14945. async readFile(filename, options) {
  14946. if (!(await utils.fs.exists(filename))) {
  14947. throw new Error(`File not found: ${filename}`);
  14948. }
  14949. const stream = fs.createReadStream(filename);
  14950. try {
  14951. const workbook = await this.read(stream, options);
  14952. stream.close();
  14953. return workbook;
  14954. } catch (error) {
  14955. stream.close();
  14956. throw error;
  14957. }
  14958. }
  14959. parseRels(stream) {
  14960. const xform = new RelationshipsXform();
  14961. return xform.parseStream(stream);
  14962. }
  14963. parseWorkbook(stream) {
  14964. const xform = new WorkbookXform();
  14965. return xform.parseStream(stream);
  14966. }
  14967. parseSharedStrings(stream) {
  14968. const xform = new SharedStringsXform();
  14969. return xform.parseStream(stream);
  14970. }
  14971. reconcile(model, options) {
  14972. const workbookXform = new WorkbookXform();
  14973. const worksheetXform = new WorksheetXform(options);
  14974. const drawingXform = new DrawingXform();
  14975. const tableXform = new TableXform();
  14976. workbookXform.reconcile(model);
  14977. // reconcile drawings with their rels
  14978. const drawingOptions = {
  14979. media: model.media,
  14980. mediaIndex: model.mediaIndex
  14981. };
  14982. Object.keys(model.drawings).forEach(name => {
  14983. const drawing = model.drawings[name];
  14984. const drawingRel = model.drawingRels[name];
  14985. if (drawingRel) {
  14986. drawingOptions.rels = drawingRel.reduce((o, rel) => {
  14987. o[rel.Id] = rel;
  14988. return o;
  14989. }, {});
  14990. (drawing.anchors || []).forEach(anchor => {
  14991. const hyperlinks = anchor.picture && anchor.picture.hyperlinks;
  14992. if (hyperlinks && drawingOptions.rels[hyperlinks.rId]) {
  14993. hyperlinks.hyperlink = drawingOptions.rels[hyperlinks.rId].Target;
  14994. delete hyperlinks.rId;
  14995. }
  14996. });
  14997. drawingXform.reconcile(drawing, drawingOptions);
  14998. }
  14999. });
  15000. // reconcile tables with the default styles
  15001. const tableOptions = {
  15002. styles: model.styles
  15003. };
  15004. Object.values(model.tables).forEach(table => {
  15005. tableXform.reconcile(table, tableOptions);
  15006. });
  15007. const sheetOptions = {
  15008. styles: model.styles,
  15009. sharedStrings: model.sharedStrings,
  15010. media: model.media,
  15011. mediaIndex: model.mediaIndex,
  15012. date1904: model.properties && model.properties.date1904,
  15013. drawings: model.drawings,
  15014. comments: model.comments,
  15015. tables: model.tables,
  15016. vmlDrawings: model.vmlDrawings
  15017. };
  15018. model.worksheets.forEach(worksheet => {
  15019. worksheet.relationships = model.worksheetRels[worksheet.sheetNo];
  15020. worksheetXform.reconcile(worksheet, sheetOptions);
  15021. });
  15022. // delete unnecessary parts
  15023. delete model.worksheetHash;
  15024. delete model.worksheetRels;
  15025. delete model.globalRels;
  15026. delete model.sharedStrings;
  15027. delete model.workbookRels;
  15028. delete model.sheetDefs;
  15029. delete model.styles;
  15030. delete model.mediaIndex;
  15031. delete model.drawings;
  15032. delete model.drawingRels;
  15033. delete model.vmlDrawings;
  15034. }
  15035. async _processWorksheetEntry(stream, model, sheetNo, options, path) {
  15036. const xform = new WorksheetXform(options);
  15037. const worksheet = await xform.parseStream(stream);
  15038. worksheet.sheetNo = sheetNo;
  15039. model.worksheetHash[path] = worksheet;
  15040. model.worksheets.push(worksheet);
  15041. }
  15042. async _processCommentEntry(stream, model, name) {
  15043. const xform = new CommentsXform();
  15044. const comments = await xform.parseStream(stream);
  15045. model.comments[`../${name}.xml`] = comments;
  15046. }
  15047. async _processTableEntry(stream, model, name) {
  15048. const xform = new TableXform();
  15049. const table = await xform.parseStream(stream);
  15050. model.tables[`../tables/${name}.xml`] = table;
  15051. }
  15052. async _processWorksheetRelsEntry(stream, model, sheetNo) {
  15053. const xform = new RelationshipsXform();
  15054. const relationships = await xform.parseStream(stream);
  15055. model.worksheetRels[sheetNo] = relationships;
  15056. }
  15057. async _processMediaEntry(entry, model, filename) {
  15058. const lastDot = filename.lastIndexOf('.');
  15059. // if we can't determine extension, ignore it
  15060. if (lastDot >= 1) {
  15061. const extension = filename.substr(lastDot + 1);
  15062. const name = filename.substr(0, lastDot);
  15063. await new Promise((resolve, reject) => {
  15064. const streamBuf = new StreamBuf();
  15065. streamBuf.on('finish', () => {
  15066. model.mediaIndex[filename] = model.media.length;
  15067. model.mediaIndex[name] = model.media.length;
  15068. const medium = {
  15069. type: 'image',
  15070. name,
  15071. extension,
  15072. buffer: streamBuf.toBuffer()
  15073. };
  15074. model.media.push(medium);
  15075. resolve();
  15076. });
  15077. entry.on('error', error => {
  15078. reject(error);
  15079. });
  15080. entry.pipe(streamBuf);
  15081. });
  15082. }
  15083. }
  15084. async _processDrawingEntry(entry, model, name) {
  15085. const xform = new DrawingXform();
  15086. const drawing = await xform.parseStream(entry);
  15087. model.drawings[name] = drawing;
  15088. }
  15089. async _processDrawingRelsEntry(entry, model, name) {
  15090. const xform = new RelationshipsXform();
  15091. const relationships = await xform.parseStream(entry);
  15092. model.drawingRels[name] = relationships;
  15093. }
  15094. async _processVmlDrawingEntry(entry, model, name) {
  15095. const xform = new VmlNotesXform();
  15096. const vmlDrawing = await xform.parseStream(entry);
  15097. model.vmlDrawings[`../drawings/${name}.vml`] = vmlDrawing;
  15098. }
  15099. async _processThemeEntry(entry, model, name) {
  15100. await new Promise((resolve, reject) => {
  15101. // TODO: stream entry into buffer and store the xml in the model.themes[]
  15102. const stream = new StreamBuf();
  15103. entry.on('error', reject);
  15104. stream.on('error', reject);
  15105. stream.on('finish', () => {
  15106. model.themes[name] = stream.read().toString();
  15107. resolve();
  15108. });
  15109. entry.pipe(stream);
  15110. });
  15111. }
  15112. /**
  15113. * @deprecated since version 4.0. You should use `#read` instead. Please follow upgrade instruction: https://github.com/exceljs/exceljs/blob/master/UPGRADE-4.0.md
  15114. */
  15115. createInputStream() {
  15116. throw new Error('`XLSX#createInputStream` is deprecated. You should use `XLSX#read` instead. This method will be removed in version 5.0. Please follow upgrade instruction: https://github.com/exceljs/exceljs/blob/master/UPGRADE-4.0.md');
  15117. }
  15118. async read(stream, options) {
  15119. // TODO: Remove once node v8 is deprecated
  15120. // Detect and upgrade old streams
  15121. if (!stream[Symbol.asyncIterator] && stream.pipe) {
  15122. stream = stream.pipe(new PassThrough());
  15123. }
  15124. const chunks = [];
  15125. for await (const chunk of stream) {
  15126. chunks.push(chunk);
  15127. }
  15128. return this.load(Buffer.concat(chunks), options);
  15129. }
  15130. async load(data, options) {
  15131. let buffer;
  15132. if (options && options.base64) {
  15133. buffer = Buffer.from(data.toString(), 'base64');
  15134. } else {
  15135. buffer = data;
  15136. }
  15137. const model = {
  15138. worksheets: [],
  15139. worksheetHash: {},
  15140. worksheetRels: [],
  15141. themes: {},
  15142. media: [],
  15143. mediaIndex: {},
  15144. drawings: {},
  15145. drawingRels: {},
  15146. comments: {},
  15147. tables: {},
  15148. vmlDrawings: {}
  15149. };
  15150. const zip = await JSZip.loadAsync(buffer);
  15151. for (const entry of Object.values(zip.files)) {
  15152. /* eslint-disable no-await-in-loop */
  15153. if (!entry.dir) {
  15154. let entryName = entry.name;
  15155. if (entryName[0] === '/') {
  15156. entryName = entryName.substr(1);
  15157. }
  15158. let stream;
  15159. if (entryName.match(/xl\/media\//) ||
  15160. // themes are not parsed as stream
  15161. entryName.match(/xl\/theme\/([a-zA-Z0-9]+)[.]xml/)) {
  15162. stream = new PassThrough();
  15163. stream.write(await entry.async('nodebuffer'));
  15164. } else {
  15165. // use object mode to avoid buffer-string convention
  15166. stream = new PassThrough({
  15167. writableObjectMode: true,
  15168. readableObjectMode: true
  15169. });
  15170. let content;
  15171. // https://www.npmjs.com/package/process
  15172. if (process.browser) {
  15173. // running in browser, use TextDecoder if possible
  15174. content = bufferToString(await entry.async('nodebuffer'));
  15175. } else {
  15176. // running in node.js
  15177. content = await entry.async('string');
  15178. }
  15179. const chunkSize = 16 * 1024;
  15180. for (let i = 0; i < content.length; i += chunkSize) {
  15181. stream.write(content.substring(i, i + chunkSize));
  15182. }
  15183. }
  15184. stream.end();
  15185. switch (entryName) {
  15186. case '_rels/.rels':
  15187. model.globalRels = await this.parseRels(stream);
  15188. break;
  15189. case 'xl/workbook.xml':
  15190. {
  15191. const workbook = await this.parseWorkbook(stream);
  15192. model.sheets = workbook.sheets;
  15193. model.definedNames = workbook.definedNames;
  15194. model.views = workbook.views;
  15195. model.properties = workbook.properties;
  15196. model.calcProperties = workbook.calcProperties;
  15197. break;
  15198. }
  15199. case 'xl/_rels/workbook.xml.rels':
  15200. model.workbookRels = await this.parseRels(stream);
  15201. break;
  15202. case 'xl/sharedStrings.xml':
  15203. model.sharedStrings = new SharedStringsXform();
  15204. await model.sharedStrings.parseStream(stream);
  15205. break;
  15206. case 'xl/styles.xml':
  15207. model.styles = new StylesXform();
  15208. await model.styles.parseStream(stream);
  15209. break;
  15210. case 'docProps/app.xml':
  15211. {
  15212. const appXform = new AppXform();
  15213. const appProperties = await appXform.parseStream(stream);
  15214. model.company = appProperties.company;
  15215. model.manager = appProperties.manager;
  15216. break;
  15217. }
  15218. case 'docProps/core.xml':
  15219. {
  15220. const coreXform = new CoreXform();
  15221. const coreProperties = await coreXform.parseStream(stream);
  15222. Object.assign(model, coreProperties);
  15223. break;
  15224. }
  15225. default:
  15226. {
  15227. let match = entryName.match(/xl\/worksheets\/sheet(\d+)[.]xml/);
  15228. if (match) {
  15229. await this._processWorksheetEntry(stream, model, match[1], options, entryName);
  15230. break;
  15231. }
  15232. match = entryName.match(/xl\/worksheets\/_rels\/sheet(\d+)[.]xml.rels/);
  15233. if (match) {
  15234. await this._processWorksheetRelsEntry(stream, model, match[1]);
  15235. break;
  15236. }
  15237. match = entryName.match(/xl\/theme\/([a-zA-Z0-9]+)[.]xml/);
  15238. if (match) {
  15239. await this._processThemeEntry(stream, model, match[1]);
  15240. break;
  15241. }
  15242. match = entryName.match(/xl\/media\/([a-zA-Z0-9]+[.][a-zA-Z0-9]{3,4})$/);
  15243. if (match) {
  15244. await this._processMediaEntry(stream, model, match[1]);
  15245. break;
  15246. }
  15247. match = entryName.match(/xl\/drawings\/([a-zA-Z0-9]+)[.]xml/);
  15248. if (match) {
  15249. await this._processDrawingEntry(stream, model, match[1]);
  15250. break;
  15251. }
  15252. match = entryName.match(/xl\/(comments\d+)[.]xml/);
  15253. if (match) {
  15254. await this._processCommentEntry(stream, model, match[1]);
  15255. break;
  15256. }
  15257. match = entryName.match(/xl\/tables\/(table\d+)[.]xml/);
  15258. if (match) {
  15259. await this._processTableEntry(stream, model, match[1]);
  15260. break;
  15261. }
  15262. match = entryName.match(/xl\/drawings\/_rels\/([a-zA-Z0-9]+)[.]xml[.]rels/);
  15263. if (match) {
  15264. await this._processDrawingRelsEntry(stream, model, match[1]);
  15265. break;
  15266. }
  15267. match = entryName.match(/xl\/drawings\/(vmlDrawing\d+)[.]vml/);
  15268. if (match) {
  15269. await this._processVmlDrawingEntry(stream, model, match[1]);
  15270. break;
  15271. }
  15272. }
  15273. }
  15274. }
  15275. }
  15276. this.reconcile(model, options);
  15277. // apply model
  15278. this.workbook.model = model;
  15279. return this.workbook;
  15280. }
  15281. // =========================================================================
  15282. // Write
  15283. async addMedia(zip, model) {
  15284. await Promise.all(model.media.map(async medium => {
  15285. if (medium.type === 'image') {
  15286. const filename = `xl/media/${medium.name}.${medium.extension}`;
  15287. if (medium.filename) {
  15288. const data = await fsReadFileAsync(medium.filename);
  15289. return zip.append(data, {
  15290. name: filename
  15291. });
  15292. }
  15293. if (medium.buffer) {
  15294. return zip.append(medium.buffer, {
  15295. name: filename
  15296. });
  15297. }
  15298. if (medium.base64) {
  15299. const dataimg64 = medium.base64;
  15300. const content = dataimg64.substring(dataimg64.indexOf(',') + 1);
  15301. return zip.append(content, {
  15302. name: filename,
  15303. base64: true
  15304. });
  15305. }
  15306. }
  15307. throw new Error('Unsupported media');
  15308. }));
  15309. }
  15310. addDrawings(zip, model) {
  15311. const drawingXform = new DrawingXform();
  15312. const relsXform = new RelationshipsXform();
  15313. model.worksheets.forEach(worksheet => {
  15314. const {
  15315. drawing
  15316. } = worksheet;
  15317. if (drawing) {
  15318. drawingXform.prepare(drawing, {});
  15319. let xml = drawingXform.toXml(drawing);
  15320. zip.append(xml, {
  15321. name: `xl/drawings/${drawing.name}.xml`
  15322. });
  15323. xml = relsXform.toXml(drawing.rels);
  15324. zip.append(xml, {
  15325. name: `xl/drawings/_rels/${drawing.name}.xml.rels`
  15326. });
  15327. }
  15328. });
  15329. }
  15330. addTables(zip, model) {
  15331. const tableXform = new TableXform();
  15332. model.worksheets.forEach(worksheet => {
  15333. const {
  15334. tables
  15335. } = worksheet;
  15336. tables.forEach(table => {
  15337. tableXform.prepare(table, {});
  15338. const tableXml = tableXform.toXml(table);
  15339. zip.append(tableXml, {
  15340. name: `xl/tables/${table.target}`
  15341. });
  15342. });
  15343. });
  15344. }
  15345. async addContentTypes(zip, model) {
  15346. const xform = new ContentTypesXform();
  15347. const xml = xform.toXml(model);
  15348. zip.append(xml, {
  15349. name: '[Content_Types].xml'
  15350. });
  15351. }
  15352. async addApp(zip, model) {
  15353. const xform = new AppXform();
  15354. const xml = xform.toXml(model);
  15355. zip.append(xml, {
  15356. name: 'docProps/app.xml'
  15357. });
  15358. }
  15359. async addCore(zip, model) {
  15360. const coreXform = new CoreXform();
  15361. zip.append(coreXform.toXml(model), {
  15362. name: 'docProps/core.xml'
  15363. });
  15364. }
  15365. async addThemes(zip, model) {
  15366. const themes = model.themes || {
  15367. theme1: theme1Xml
  15368. };
  15369. Object.keys(themes).forEach(name => {
  15370. const xml = themes[name];
  15371. const path = `xl/theme/${name}.xml`;
  15372. zip.append(xml, {
  15373. name: path
  15374. });
  15375. });
  15376. }
  15377. async addOfficeRels(zip) {
  15378. const xform = new RelationshipsXform();
  15379. const xml = xform.toXml([{
  15380. Id: 'rId1',
  15381. Type: XLSX.RelType.OfficeDocument,
  15382. Target: 'xl/workbook.xml'
  15383. }, {
  15384. Id: 'rId2',
  15385. Type: XLSX.RelType.CoreProperties,
  15386. Target: 'docProps/core.xml'
  15387. }, {
  15388. Id: 'rId3',
  15389. Type: XLSX.RelType.ExtenderProperties,
  15390. Target: 'docProps/app.xml'
  15391. }]);
  15392. zip.append(xml, {
  15393. name: '_rels/.rels'
  15394. });
  15395. }
  15396. async addWorkbookRels(zip, model) {
  15397. let count = 1;
  15398. const relationships = [{
  15399. Id: `rId${count++}`,
  15400. Type: XLSX.RelType.Styles,
  15401. Target: 'styles.xml'
  15402. }, {
  15403. Id: `rId${count++}`,
  15404. Type: XLSX.RelType.Theme,
  15405. Target: 'theme/theme1.xml'
  15406. }];
  15407. if (model.sharedStrings.count) {
  15408. relationships.push({
  15409. Id: `rId${count++}`,
  15410. Type: XLSX.RelType.SharedStrings,
  15411. Target: 'sharedStrings.xml'
  15412. });
  15413. }
  15414. model.worksheets.forEach(worksheet => {
  15415. worksheet.rId = `rId${count++}`;
  15416. relationships.push({
  15417. Id: worksheet.rId,
  15418. Type: XLSX.RelType.Worksheet,
  15419. Target: `worksheets/sheet${worksheet.id}.xml`
  15420. });
  15421. });
  15422. const xform = new RelationshipsXform();
  15423. const xml = xform.toXml(relationships);
  15424. zip.append(xml, {
  15425. name: 'xl/_rels/workbook.xml.rels'
  15426. });
  15427. }
  15428. async addSharedStrings(zip, model) {
  15429. if (model.sharedStrings && model.sharedStrings.count) {
  15430. zip.append(model.sharedStrings.xml, {
  15431. name: 'xl/sharedStrings.xml'
  15432. });
  15433. }
  15434. }
  15435. async addStyles(zip, model) {
  15436. const {
  15437. xml
  15438. } = model.styles;
  15439. if (xml) {
  15440. zip.append(xml, {
  15441. name: 'xl/styles.xml'
  15442. });
  15443. }
  15444. }
  15445. async addWorkbook(zip, model) {
  15446. const xform = new WorkbookXform();
  15447. zip.append(xform.toXml(model), {
  15448. name: 'xl/workbook.xml'
  15449. });
  15450. }
  15451. async addWorksheets(zip, model) {
  15452. // preparation phase
  15453. const worksheetXform = new WorksheetXform();
  15454. const relationshipsXform = new RelationshipsXform();
  15455. const commentsXform = new CommentsXform();
  15456. const vmlNotesXform = new VmlNotesXform();
  15457. // write sheets
  15458. model.worksheets.forEach(worksheet => {
  15459. let xmlStream = new XmlStream();
  15460. worksheetXform.render(xmlStream, worksheet);
  15461. zip.append(xmlStream.xml, {
  15462. name: `xl/worksheets/sheet${worksheet.id}.xml`
  15463. });
  15464. if (worksheet.rels && worksheet.rels.length) {
  15465. xmlStream = new XmlStream();
  15466. relationshipsXform.render(xmlStream, worksheet.rels);
  15467. zip.append(xmlStream.xml, {
  15468. name: `xl/worksheets/_rels/sheet${worksheet.id}.xml.rels`
  15469. });
  15470. }
  15471. if (worksheet.comments.length > 0) {
  15472. xmlStream = new XmlStream();
  15473. commentsXform.render(xmlStream, worksheet);
  15474. zip.append(xmlStream.xml, {
  15475. name: `xl/comments${worksheet.id}.xml`
  15476. });
  15477. xmlStream = new XmlStream();
  15478. vmlNotesXform.render(xmlStream, worksheet);
  15479. zip.append(xmlStream.xml, {
  15480. name: `xl/drawings/vmlDrawing${worksheet.id}.vml`
  15481. });
  15482. }
  15483. });
  15484. }
  15485. _finalize(zip) {
  15486. return new Promise((resolve, reject) => {
  15487. zip.on('finish', () => {
  15488. resolve(this);
  15489. });
  15490. zip.on('error', reject);
  15491. zip.finalize();
  15492. });
  15493. }
  15494. prepareModel(model, options) {
  15495. // ensure following properties have sane values
  15496. model.creator = model.creator || 'ExcelJS';
  15497. model.lastModifiedBy = model.lastModifiedBy || 'ExcelJS';
  15498. model.created = model.created || new Date();
  15499. model.modified = model.modified || new Date();
  15500. model.useSharedStrings = options.useSharedStrings !== undefined ? options.useSharedStrings : true;
  15501. model.useStyles = options.useStyles !== undefined ? options.useStyles : true;
  15502. // Manage the shared strings
  15503. model.sharedStrings = new SharedStringsXform();
  15504. // add a style manager to handle cell formats, fonts, etc.
  15505. model.styles = model.useStyles ? new StylesXform(true) : new StylesXform.Mock();
  15506. // prepare all of the things before the render
  15507. const workbookXform = new WorkbookXform();
  15508. const worksheetXform = new WorksheetXform();
  15509. workbookXform.prepare(model);
  15510. const worksheetOptions = {
  15511. sharedStrings: model.sharedStrings,
  15512. styles: model.styles,
  15513. date1904: model.properties.date1904,
  15514. drawingsCount: 0,
  15515. media: model.media
  15516. };
  15517. worksheetOptions.drawings = model.drawings = [];
  15518. worksheetOptions.commentRefs = model.commentRefs = [];
  15519. let tableCount = 0;
  15520. model.tables = [];
  15521. model.worksheets.forEach(worksheet => {
  15522. // assign unique filenames to tables
  15523. worksheet.tables.forEach(table => {
  15524. tableCount++;
  15525. table.target = `table${tableCount}.xml`;
  15526. table.id = tableCount;
  15527. model.tables.push(table);
  15528. });
  15529. worksheetXform.prepare(worksheet, worksheetOptions);
  15530. });
  15531. // TODO: workbook drawing list
  15532. }
  15533. async write(stream, options) {
  15534. options = options || {};
  15535. const {
  15536. model
  15537. } = this.workbook;
  15538. const zip = new ZipStream.ZipWriter(options.zip);
  15539. zip.pipe(stream);
  15540. this.prepareModel(model, options);
  15541. // render
  15542. await this.addContentTypes(zip, model);
  15543. await this.addOfficeRels(zip, model);
  15544. await this.addWorkbookRels(zip, model);
  15545. await this.addWorksheets(zip, model);
  15546. await this.addSharedStrings(zip, model); // always after worksheets
  15547. await this.addDrawings(zip, model);
  15548. await this.addTables(zip, model);
  15549. await Promise.all([this.addThemes(zip, model), this.addStyles(zip, model)]);
  15550. await this.addMedia(zip, model);
  15551. await Promise.all([this.addApp(zip, model), this.addCore(zip, model)]);
  15552. await this.addWorkbook(zip, model);
  15553. return this._finalize(zip);
  15554. }
  15555. writeFile(filename, options) {
  15556. const stream = fs.createWriteStream(filename);
  15557. return new Promise((resolve, reject) => {
  15558. stream.on('finish', () => {
  15559. resolve();
  15560. });
  15561. stream.on('error', error => {
  15562. reject(error);
  15563. });
  15564. this.write(stream, options).then(() => {
  15565. stream.end();
  15566. }).catch(err => {
  15567. reject(err);
  15568. });
  15569. });
  15570. }
  15571. async writeBuffer(options) {
  15572. const stream = new StreamBuf();
  15573. await this.write(stream, options);
  15574. return stream.read();
  15575. }
  15576. }
  15577. XLSX.RelType = require('./rel-type');
  15578. module.exports = XLSX;
  15579. }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
  15580. },{"../utils/browser-buffer-decode":16,"../utils/stream-buf":24,"../utils/utils":27,"../utils/xml-stream":28,"../utils/zip-stream":29,"./rel-type":31,"./xform/book/workbook-xform":38,"./xform/comment/comments-xform":40,"./xform/comment/vml-notes-xform":45,"./xform/core/app-xform":51,"./xform/core/content-types-xform":52,"./xform/core/core-xform":53,"./xform/core/relationships-xform":55,"./xform/drawing/drawing-xform":62,"./xform/sheet/worksheet-xform":115,"./xform/strings/shared-strings-xform":124,"./xform/style/styles-xform":135,"./xform/table/table-xform":143,"./xml/theme1":145,"_process":306,"buffer":220,"fs":216,"jszip":280,"readable-stream":330}],145:[function(require,module,exports){
  15581. "use strict";
  15582. /* eslint-disable */
  15583. module.exports = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"> <a:themeElements> <a:clrScheme name="Office"> <a:dk1> <a:sysClr val="windowText" lastClr="000000"/> </a:dk1> <a:lt1> <a:sysClr val="window" lastClr="FFFFFF"/> </a:lt1> <a:dk2> <a:srgbClr val="1F497D"/> </a:dk2> <a:lt2> <a:srgbClr val="EEECE1"/> </a:lt2> <a:accent1> <a:srgbClr val="4F81BD"/> </a:accent1> <a:accent2> <a:srgbClr val="C0504D"/> </a:accent2> <a:accent3> <a:srgbClr val="9BBB59"/> </a:accent3> <a:accent4> <a:srgbClr val="8064A2"/> </a:accent4> <a:accent5> <a:srgbClr val="4BACC6"/> </a:accent5> <a:accent6> <a:srgbClr val="F79646"/> </a:accent6> <a:hlink> <a:srgbClr val="0000FF"/> </a:hlink> <a:folHlink> <a:srgbClr val="800080"/> </a:folHlink> </a:clrScheme> <a:fontScheme name="Office"> <a:majorFont> <a:latin typeface="Cambria"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Times New Roman"/> <a:font script="Hebr" typeface="Times New Roman"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="MoolBoran"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Times New Roman"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:majorFont> <a:minorFont> <a:latin typeface="Calibri"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Arial"/> <a:font script="Hebr" typeface="Arial"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="DaunPenh"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Arial"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:minorFont> </a:fontScheme> <a:fmtScheme name="Office"> <a:fillStyleLst> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="35000"> <a:schemeClr val="phClr"> <a:tint val="37000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="15000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="1"/> </a:gradFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="100000"/> <a:shade val="100000"/> <a:satMod val="130000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:shade val="100000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="0"/> </a:gradFill> </a:fillStyleLst> <a:lnStyleLst> <a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"> <a:shade val="95000"/> <a:satMod val="105000"/> </a:schemeClr> </a:solidFill> <a:prstDash val="solid"/> </a:ln> <a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:prstDash val="solid"/> </a:ln> <a:ln w="38100" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:prstDash val="solid"/> </a:ln> </a:lnStyleLst> <a:effectStyleLst> <a:effectStyle> <a:effectLst> <a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0"> <a:srgbClr val="000000"> <a:alpha val="38000"/> </a:srgbClr> </a:outerShdw> </a:effectLst> </a:effectStyle> <a:effectStyle> <a:effectLst> <a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"> <a:srgbClr val="000000"> <a:alpha val="35000"/> </a:srgbClr> </a:outerShdw> </a:effectLst> </a:effectStyle> <a:effectStyle> <a:effectLst> <a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"> <a:srgbClr val="000000"> <a:alpha val="35000"/> </a:srgbClr> </a:outerShdw> </a:effectLst> <a:scene3d> <a:camera prst="orthographicFront"> <a:rot lat="0" lon="0" rev="0"/> </a:camera> <a:lightRig rig="threePt" dir="t"> <a:rot lat="0" lon="0" rev="1200000"/> </a:lightRig> </a:scene3d> <a:sp3d> <a:bevelT w="63500" h="25400"/> </a:sp3d> </a:effectStyle> </a:effectStyleLst> <a:bgFillStyleLst> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="40000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> <a:gs pos="40000"> <a:schemeClr val="phClr"> <a:tint val="45000"/> <a:shade val="99000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:shade val="20000"/> <a:satMod val="255000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:path path="circle"> <a:fillToRect l="50000" t="-80000" r="50000" b="180000"/> </a:path> </a:gradFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="80000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:shade val="30000"/> <a:satMod val="200000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:path path="circle"> <a:fillToRect l="50000" t="50000" r="50000" b="50000"/> </a:path> </a:gradFill> </a:bgFillStyleLst> </a:fmtScheme> </a:themeElements> <a:objectDefaults> <a:spDef> <a:spPr/> <a:bodyPr/> <a:lstStyle/> <a:style> <a:lnRef idx="1"> <a:schemeClr val="accent1"/> </a:lnRef> <a:fillRef idx="3"> <a:schemeClr val="accent1"/> </a:fillRef> <a:effectRef idx="2"> <a:schemeClr val="accent1"/> </a:effectRef> <a:fontRef idx="minor"> <a:schemeClr val="lt1"/> </a:fontRef> </a:style> </a:spDef> <a:lnDef> <a:spPr/> <a:bodyPr/> <a:lstStyle/> <a:style> <a:lnRef idx="2"> <a:schemeClr val="accent1"/> </a:lnRef> <a:fillRef idx="0"> <a:schemeClr val="accent1"/> </a:fillRef> <a:effectRef idx="1"> <a:schemeClr val="accent1"/> </a:effectRef> <a:fontRef idx="minor"> <a:schemeClr val="tx1"/> </a:fontRef> </a:style> </a:lnDef> </a:objectDefaults> <a:extraClrSchemeLst/> </a:theme>';
  15584. },{}],146:[function(require,module,exports){
  15585. (function (Buffer){(function (){
  15586. "use strict";
  15587. Object.defineProperty(exports, "__esModule", {
  15588. value: true
  15589. });
  15590. exports.CsvFormatterStream = void 0;
  15591. const stream_1 = require("stream");
  15592. const formatter_1 = require("./formatter");
  15593. class CsvFormatterStream extends stream_1.Transform {
  15594. constructor(formatterOptions) {
  15595. super({
  15596. writableObjectMode: formatterOptions.objectMode
  15597. });
  15598. this.hasWrittenBOM = false;
  15599. this.formatterOptions = formatterOptions;
  15600. this.rowFormatter = new formatter_1.RowFormatter(formatterOptions);
  15601. // if writeBOM is false then set to true
  15602. // if writeBOM is true then set to false by default so it is written out
  15603. this.hasWrittenBOM = !formatterOptions.writeBOM;
  15604. }
  15605. transform(transformFunction) {
  15606. this.rowFormatter.rowTransform = transformFunction;
  15607. return this;
  15608. }
  15609. _transform(row, encoding, cb) {
  15610. let cbCalled = false;
  15611. try {
  15612. if (!this.hasWrittenBOM) {
  15613. this.push(this.formatterOptions.BOM);
  15614. this.hasWrittenBOM = true;
  15615. }
  15616. this.rowFormatter.format(row, (err, rows) => {
  15617. if (err) {
  15618. cbCalled = true;
  15619. return cb(err);
  15620. }
  15621. if (rows) {
  15622. rows.forEach(r => {
  15623. this.push(Buffer.from(r, 'utf8'));
  15624. });
  15625. }
  15626. cbCalled = true;
  15627. return cb();
  15628. });
  15629. } catch (e) {
  15630. if (cbCalled) {
  15631. throw e;
  15632. }
  15633. cb(e);
  15634. }
  15635. }
  15636. _flush(cb) {
  15637. this.rowFormatter.finish((err, rows) => {
  15638. if (err) {
  15639. return cb(err);
  15640. }
  15641. if (rows) {
  15642. rows.forEach(r => {
  15643. this.push(Buffer.from(r, 'utf8'));
  15644. });
  15645. }
  15646. return cb();
  15647. });
  15648. }
  15649. }
  15650. exports.CsvFormatterStream = CsvFormatterStream;
  15651. }).call(this)}).call(this,require("buffer").Buffer)
  15652. },{"./formatter":150,"buffer":220,"stream":343}],147:[function(require,module,exports){
  15653. "use strict";
  15654. Object.defineProperty(exports, "__esModule", {
  15655. value: true
  15656. });
  15657. exports.FormatterOptions = void 0;
  15658. class FormatterOptions {
  15659. constructor() {
  15660. let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  15661. var _a;
  15662. this.objectMode = true;
  15663. this.delimiter = ',';
  15664. this.rowDelimiter = '\n';
  15665. this.quote = '"';
  15666. this.escape = this.quote;
  15667. this.quoteColumns = false;
  15668. this.quoteHeaders = this.quoteColumns;
  15669. this.headers = null;
  15670. this.includeEndRowDelimiter = false;
  15671. this.writeBOM = false;
  15672. this.BOM = '\ufeff';
  15673. this.alwaysWriteHeaders = false;
  15674. Object.assign(this, opts || {});
  15675. if (typeof (opts === null || opts === void 0 ? void 0 : opts.quoteHeaders) === 'undefined') {
  15676. this.quoteHeaders = this.quoteColumns;
  15677. }
  15678. if ((opts === null || opts === void 0 ? void 0 : opts.quote) === true) {
  15679. this.quote = '"';
  15680. } else if ((opts === null || opts === void 0 ? void 0 : opts.quote) === false) {
  15681. this.quote = '';
  15682. }
  15683. if (typeof (opts === null || opts === void 0 ? void 0 : opts.escape) !== 'string') {
  15684. this.escape = this.quote;
  15685. }
  15686. this.shouldWriteHeaders = !!this.headers && ((_a = opts.writeHeaders) !== null && _a !== void 0 ? _a : true);
  15687. this.headers = Array.isArray(this.headers) ? this.headers : null;
  15688. this.escapedQuote = `${this.escape}${this.quote}`;
  15689. }
  15690. }
  15691. exports.FormatterOptions = FormatterOptions;
  15692. },{}],148:[function(require,module,exports){
  15693. "use strict";
  15694. var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  15695. return mod && mod.__esModule ? mod : {
  15696. "default": mod
  15697. };
  15698. };
  15699. Object.defineProperty(exports, "__esModule", {
  15700. value: true
  15701. });
  15702. exports.FieldFormatter = void 0;
  15703. const lodash_isboolean_1 = __importDefault(require("lodash.isboolean"));
  15704. const lodash_isnil_1 = __importDefault(require("lodash.isnil"));
  15705. const lodash_escaperegexp_1 = __importDefault(require("lodash.escaperegexp"));
  15706. class FieldFormatter {
  15707. constructor(formatterOptions) {
  15708. this._headers = null;
  15709. this.formatterOptions = formatterOptions;
  15710. if (formatterOptions.headers !== null) {
  15711. this.headers = formatterOptions.headers;
  15712. }
  15713. this.REPLACE_REGEXP = new RegExp(formatterOptions.quote, 'g');
  15714. const escapePattern = `[${formatterOptions.delimiter}${lodash_escaperegexp_1.default(formatterOptions.rowDelimiter)}|\r|\n]`;
  15715. this.ESCAPE_REGEXP = new RegExp(escapePattern);
  15716. }
  15717. set headers(headers) {
  15718. this._headers = headers;
  15719. }
  15720. shouldQuote(fieldIndex, isHeader) {
  15721. const quoteConfig = isHeader ? this.formatterOptions.quoteHeaders : this.formatterOptions.quoteColumns;
  15722. if (lodash_isboolean_1.default(quoteConfig)) {
  15723. return quoteConfig;
  15724. }
  15725. if (Array.isArray(quoteConfig)) {
  15726. return quoteConfig[fieldIndex];
  15727. }
  15728. if (this._headers !== null) {
  15729. return quoteConfig[this._headers[fieldIndex]];
  15730. }
  15731. return false;
  15732. }
  15733. format(field, fieldIndex, isHeader) {
  15734. const preparedField = `${lodash_isnil_1.default(field) ? '' : field}`.replace(/\0/g, '');
  15735. const {
  15736. formatterOptions
  15737. } = this;
  15738. if (formatterOptions.quote !== '') {
  15739. const shouldEscape = preparedField.indexOf(formatterOptions.quote) !== -1;
  15740. if (shouldEscape) {
  15741. return this.quoteField(preparedField.replace(this.REPLACE_REGEXP, formatterOptions.escapedQuote));
  15742. }
  15743. }
  15744. const hasEscapeCharacters = preparedField.search(this.ESCAPE_REGEXP) !== -1;
  15745. if (hasEscapeCharacters || this.shouldQuote(fieldIndex, isHeader)) {
  15746. return this.quoteField(preparedField);
  15747. }
  15748. return preparedField;
  15749. }
  15750. quoteField(field) {
  15751. const {
  15752. quote
  15753. } = this.formatterOptions;
  15754. return `${quote}${field}${quote}`;
  15755. }
  15756. }
  15757. exports.FieldFormatter = FieldFormatter;
  15758. },{"lodash.escaperegexp":281,"lodash.isboolean":283,"lodash.isnil":286}],149:[function(require,module,exports){
  15759. "use strict";
  15760. var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  15761. return mod && mod.__esModule ? mod : {
  15762. "default": mod
  15763. };
  15764. };
  15765. Object.defineProperty(exports, "__esModule", {
  15766. value: true
  15767. });
  15768. exports.RowFormatter = void 0;
  15769. const lodash_isfunction_1 = __importDefault(require("lodash.isfunction"));
  15770. const lodash_isequal_1 = __importDefault(require("lodash.isequal"));
  15771. const FieldFormatter_1 = require("./FieldFormatter");
  15772. const types_1 = require("../types");
  15773. class RowFormatter {
  15774. constructor(formatterOptions) {
  15775. this.rowCount = 0;
  15776. this.formatterOptions = formatterOptions;
  15777. this.fieldFormatter = new FieldFormatter_1.FieldFormatter(formatterOptions);
  15778. this.headers = formatterOptions.headers;
  15779. this.shouldWriteHeaders = formatterOptions.shouldWriteHeaders;
  15780. this.hasWrittenHeaders = false;
  15781. if (this.headers !== null) {
  15782. this.fieldFormatter.headers = this.headers;
  15783. }
  15784. if (formatterOptions.transform) {
  15785. this.rowTransform = formatterOptions.transform;
  15786. }
  15787. }
  15788. static isRowHashArray(row) {
  15789. if (Array.isArray(row)) {
  15790. return Array.isArray(row[0]) && row[0].length === 2;
  15791. }
  15792. return false;
  15793. }
  15794. static isRowArray(row) {
  15795. return Array.isArray(row) && !this.isRowHashArray(row);
  15796. }
  15797. // get headers from a row item
  15798. static gatherHeaders(row) {
  15799. if (RowFormatter.isRowHashArray(row)) {
  15800. // lets assume a multi-dimesional array with item 0 being the header
  15801. return row.map(it => it[0]);
  15802. }
  15803. if (Array.isArray(row)) {
  15804. return row;
  15805. }
  15806. return Object.keys(row);
  15807. }
  15808. // eslint-disable-next-line @typescript-eslint/no-shadow
  15809. static createTransform(transformFunction) {
  15810. if (types_1.isSyncTransform(transformFunction)) {
  15811. return (row, cb) => {
  15812. let transformedRow = null;
  15813. try {
  15814. transformedRow = transformFunction(row);
  15815. } catch (e) {
  15816. return cb(e);
  15817. }
  15818. return cb(null, transformedRow);
  15819. };
  15820. }
  15821. return (row, cb) => {
  15822. transformFunction(row, cb);
  15823. };
  15824. }
  15825. set rowTransform(transformFunction) {
  15826. if (!lodash_isfunction_1.default(transformFunction)) {
  15827. throw new TypeError('The transform should be a function');
  15828. }
  15829. this._rowTransform = RowFormatter.createTransform(transformFunction);
  15830. }
  15831. format(row, cb) {
  15832. this.callTransformer(row, (err, transformedRow) => {
  15833. if (err) {
  15834. return cb(err);
  15835. }
  15836. if (!row) {
  15837. return cb(null);
  15838. }
  15839. const rows = [];
  15840. if (transformedRow) {
  15841. const {
  15842. shouldFormatColumns,
  15843. headers
  15844. } = this.checkHeaders(transformedRow);
  15845. if (this.shouldWriteHeaders && headers && !this.hasWrittenHeaders) {
  15846. rows.push(this.formatColumns(headers, true));
  15847. this.hasWrittenHeaders = true;
  15848. }
  15849. if (shouldFormatColumns) {
  15850. const columns = this.gatherColumns(transformedRow);
  15851. rows.push(this.formatColumns(columns, false));
  15852. }
  15853. }
  15854. return cb(null, rows);
  15855. });
  15856. }
  15857. finish(cb) {
  15858. const rows = [];
  15859. // check if we should write headers and we didnt get any rows
  15860. if (this.formatterOptions.alwaysWriteHeaders && this.rowCount === 0) {
  15861. if (!this.headers) {
  15862. return cb(new Error('`alwaysWriteHeaders` option is set to true but `headers` option not provided.'));
  15863. }
  15864. rows.push(this.formatColumns(this.headers, true));
  15865. }
  15866. if (this.formatterOptions.includeEndRowDelimiter) {
  15867. rows.push(this.formatterOptions.rowDelimiter);
  15868. }
  15869. return cb(null, rows);
  15870. }
  15871. // check if we need to write header return true if we should also write a row
  15872. // could be false if headers is true and the header row(first item) is passed in
  15873. checkHeaders(row) {
  15874. if (this.headers) {
  15875. // either the headers were provided by the user or we have already gathered them.
  15876. return {
  15877. shouldFormatColumns: true,
  15878. headers: this.headers
  15879. };
  15880. }
  15881. const headers = RowFormatter.gatherHeaders(row);
  15882. this.headers = headers;
  15883. this.fieldFormatter.headers = headers;
  15884. if (!this.shouldWriteHeaders) {
  15885. // if we are not supposed to write the headers then
  15886. // always format the columns
  15887. return {
  15888. shouldFormatColumns: true,
  15889. headers: null
  15890. };
  15891. }
  15892. // if the row is equal to headers dont format
  15893. return {
  15894. shouldFormatColumns: !lodash_isequal_1.default(headers, row),
  15895. headers
  15896. };
  15897. }
  15898. // todo change this method to unknown[]
  15899. gatherColumns(row) {
  15900. if (this.headers === null) {
  15901. throw new Error('Headers is currently null');
  15902. }
  15903. if (!Array.isArray(row)) {
  15904. return this.headers.map(header => row[header]);
  15905. }
  15906. if (RowFormatter.isRowHashArray(row)) {
  15907. return this.headers.map((header, i) => {
  15908. const col = row[i];
  15909. if (col) {
  15910. return col[1];
  15911. }
  15912. return '';
  15913. });
  15914. }
  15915. // if its a one dimensional array and headers were not provided
  15916. // then just return the row
  15917. if (RowFormatter.isRowArray(row) && !this.shouldWriteHeaders) {
  15918. return row;
  15919. }
  15920. return this.headers.map((header, i) => row[i]);
  15921. }
  15922. callTransformer(row, cb) {
  15923. if (!this._rowTransform) {
  15924. return cb(null, row);
  15925. }
  15926. return this._rowTransform(row, cb);
  15927. }
  15928. formatColumns(columns, isHeadersRow) {
  15929. const formattedCols = columns.map((field, i) => this.fieldFormatter.format(field, i, isHeadersRow)).join(this.formatterOptions.delimiter);
  15930. const {
  15931. rowCount
  15932. } = this;
  15933. this.rowCount += 1;
  15934. if (rowCount) {
  15935. return [this.formatterOptions.rowDelimiter, formattedCols].join('');
  15936. }
  15937. return formattedCols;
  15938. }
  15939. }
  15940. exports.RowFormatter = RowFormatter;
  15941. },{"../types":152,"./FieldFormatter":148,"lodash.isequal":284,"lodash.isfunction":285}],150:[function(require,module,exports){
  15942. "use strict";
  15943. Object.defineProperty(exports, "__esModule", {
  15944. value: true
  15945. });
  15946. exports.FieldFormatter = exports.RowFormatter = void 0;
  15947. var RowFormatter_1 = require("./RowFormatter");
  15948. Object.defineProperty(exports, "RowFormatter", {
  15949. enumerable: true,
  15950. get: function () {
  15951. return RowFormatter_1.RowFormatter;
  15952. }
  15953. });
  15954. var FieldFormatter_1 = require("./FieldFormatter");
  15955. Object.defineProperty(exports, "FieldFormatter", {
  15956. enumerable: true,
  15957. get: function () {
  15958. return FieldFormatter_1.FieldFormatter;
  15959. }
  15960. });
  15961. },{"./FieldFormatter":148,"./RowFormatter":149}],151:[function(require,module,exports){
  15962. (function (Buffer){(function (){
  15963. "use strict";
  15964. var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) {
  15965. if (k2 === undefined) k2 = k;
  15966. Object.defineProperty(o, k2, {
  15967. enumerable: true,
  15968. get: function () {
  15969. return m[k];
  15970. }
  15971. });
  15972. } : function (o, m, k, k2) {
  15973. if (k2 === undefined) k2 = k;
  15974. o[k2] = m[k];
  15975. });
  15976. var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) {
  15977. Object.defineProperty(o, "default", {
  15978. enumerable: true,
  15979. value: v
  15980. });
  15981. } : function (o, v) {
  15982. o["default"] = v;
  15983. });
  15984. var __importStar = void 0 && (void 0).__importStar || function (mod) {
  15985. if (mod && mod.__esModule) return mod;
  15986. var result = {};
  15987. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  15988. __setModuleDefault(result, mod);
  15989. return result;
  15990. };
  15991. var __exportStar = void 0 && (void 0).__exportStar || function (m, exports) {
  15992. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
  15993. };
  15994. Object.defineProperty(exports, "__esModule", {
  15995. value: true
  15996. });
  15997. exports.writeToPath = exports.writeToString = exports.writeToBuffer = exports.writeToStream = exports.write = exports.format = exports.FormatterOptions = exports.CsvFormatterStream = void 0;
  15998. const util_1 = require("util");
  15999. const stream_1 = require("stream");
  16000. const fs = __importStar(require("fs"));
  16001. const FormatterOptions_1 = require("./FormatterOptions");
  16002. const CsvFormatterStream_1 = require("./CsvFormatterStream");
  16003. __exportStar(require("./types"), exports);
  16004. var CsvFormatterStream_2 = require("./CsvFormatterStream");
  16005. Object.defineProperty(exports, "CsvFormatterStream", {
  16006. enumerable: true,
  16007. get: function () {
  16008. return CsvFormatterStream_2.CsvFormatterStream;
  16009. }
  16010. });
  16011. var FormatterOptions_2 = require("./FormatterOptions");
  16012. Object.defineProperty(exports, "FormatterOptions", {
  16013. enumerable: true,
  16014. get: function () {
  16015. return FormatterOptions_2.FormatterOptions;
  16016. }
  16017. });
  16018. exports.format = options => new CsvFormatterStream_1.CsvFormatterStream(new FormatterOptions_1.FormatterOptions(options));
  16019. exports.write = (rows, options) => {
  16020. const csvStream = exports.format(options);
  16021. const promiseWrite = util_1.promisify((row, cb) => {
  16022. csvStream.write(row, undefined, cb);
  16023. });
  16024. rows.reduce((prev, row) => prev.then(() => promiseWrite(row)), Promise.resolve()).then(() => csvStream.end()).catch(err => {
  16025. csvStream.emit('error', err);
  16026. });
  16027. return csvStream;
  16028. };
  16029. exports.writeToStream = (ws, rows, options) => exports.write(rows, options).pipe(ws);
  16030. exports.writeToBuffer = function (rows) {
  16031. let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  16032. const buffers = [];
  16033. const ws = new stream_1.Writable({
  16034. write(data, enc, writeCb) {
  16035. buffers.push(data);
  16036. writeCb();
  16037. }
  16038. });
  16039. return new Promise((res, rej) => {
  16040. ws.on('error', rej).on('finish', () => res(Buffer.concat(buffers)));
  16041. exports.write(rows, opts).pipe(ws);
  16042. });
  16043. };
  16044. exports.writeToString = (rows, options) => exports.writeToBuffer(rows, options).then(buffer => buffer.toString());
  16045. exports.writeToPath = (path, rows, options) => {
  16046. const stream = fs.createWriteStream(path, {
  16047. encoding: 'utf8'
  16048. });
  16049. return exports.write(rows, options).pipe(stream);
  16050. };
  16051. }).call(this)}).call(this,require("buffer").Buffer)
  16052. },{"./CsvFormatterStream":146,"./FormatterOptions":147,"./types":152,"buffer":220,"fs":216,"stream":343,"util":365}],152:[function(require,module,exports){
  16053. "use strict";
  16054. /* eslint-disable @typescript-eslint/no-explicit-any */
  16055. Object.defineProperty(exports, "__esModule", {
  16056. value: true
  16057. });
  16058. exports.isSyncTransform = void 0;
  16059. exports.isSyncTransform = transform => transform.length === 1;
  16060. },{}],153:[function(require,module,exports){
  16061. (function (setImmediate){(function (){
  16062. "use strict";
  16063. Object.defineProperty(exports, "__esModule", {
  16064. value: true
  16065. });
  16066. exports.CsvParserStream = void 0;
  16067. const string_decoder_1 = require("string_decoder");
  16068. const stream_1 = require("stream");
  16069. const transforms_1 = require("./transforms");
  16070. const parser_1 = require("./parser");
  16071. class CsvParserStream extends stream_1.Transform {
  16072. constructor(parserOptions) {
  16073. super({
  16074. objectMode: parserOptions.objectMode
  16075. });
  16076. this.lines = '';
  16077. this.rowCount = 0;
  16078. this.parsedRowCount = 0;
  16079. this.parsedLineCount = 0;
  16080. this.endEmitted = false;
  16081. this.headersEmitted = false;
  16082. this.parserOptions = parserOptions;
  16083. this.parser = new parser_1.Parser(parserOptions);
  16084. this.headerTransformer = new transforms_1.HeaderTransformer(parserOptions);
  16085. this.decoder = new string_decoder_1.StringDecoder(parserOptions.encoding);
  16086. this.rowTransformerValidator = new transforms_1.RowTransformerValidator();
  16087. }
  16088. get hasHitRowLimit() {
  16089. return this.parserOptions.limitRows && this.rowCount >= this.parserOptions.maxRows;
  16090. }
  16091. get shouldEmitRows() {
  16092. return this.parsedRowCount > this.parserOptions.skipRows;
  16093. }
  16094. get shouldSkipLine() {
  16095. return this.parsedLineCount <= this.parserOptions.skipLines;
  16096. }
  16097. transform(transformFunction) {
  16098. this.rowTransformerValidator.rowTransform = transformFunction;
  16099. return this;
  16100. }
  16101. validate(validateFunction) {
  16102. this.rowTransformerValidator.rowValidator = validateFunction;
  16103. return this;
  16104. }
  16105. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16106. emit(event) {
  16107. if (event === 'end') {
  16108. if (!this.endEmitted) {
  16109. this.endEmitted = true;
  16110. super.emit('end', this.rowCount);
  16111. }
  16112. return false;
  16113. }
  16114. for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  16115. rest[_key - 1] = arguments[_key];
  16116. }
  16117. return super.emit(event, ...rest);
  16118. }
  16119. _transform(data, encoding, done) {
  16120. // if we have hit our maxRows parsing limit then skip parsing
  16121. if (this.hasHitRowLimit) {
  16122. return done();
  16123. }
  16124. const wrappedCallback = CsvParserStream.wrapDoneCallback(done);
  16125. try {
  16126. const {
  16127. lines
  16128. } = this;
  16129. const newLine = lines + this.decoder.write(data);
  16130. const rows = this.parse(newLine, true);
  16131. return this.processRows(rows, wrappedCallback);
  16132. } catch (e) {
  16133. return wrappedCallback(e);
  16134. }
  16135. }
  16136. _flush(done) {
  16137. const wrappedCallback = CsvParserStream.wrapDoneCallback(done);
  16138. // if we have hit our maxRows parsing limit then skip parsing
  16139. if (this.hasHitRowLimit) {
  16140. return wrappedCallback();
  16141. }
  16142. try {
  16143. const newLine = this.lines + this.decoder.end();
  16144. const rows = this.parse(newLine, false);
  16145. return this.processRows(rows, wrappedCallback);
  16146. } catch (e) {
  16147. return wrappedCallback(e);
  16148. }
  16149. }
  16150. parse(data, hasMoreData) {
  16151. if (!data) {
  16152. return [];
  16153. }
  16154. const {
  16155. line,
  16156. rows
  16157. } = this.parser.parse(data, hasMoreData);
  16158. this.lines = line;
  16159. return rows;
  16160. }
  16161. processRows(rows, cb) {
  16162. const rowsLength = rows.length;
  16163. const iterate = i => {
  16164. const callNext = err => {
  16165. if (err) {
  16166. return cb(err);
  16167. }
  16168. if (i % 100 === 0) {
  16169. // incase the transform are sync insert a next tick to prevent stack overflow
  16170. setImmediate(() => iterate(i + 1));
  16171. return undefined;
  16172. }
  16173. return iterate(i + 1);
  16174. };
  16175. this.checkAndEmitHeaders();
  16176. // if we have emitted all rows or we have hit the maxRows limit option
  16177. // then end
  16178. if (i >= rowsLength || this.hasHitRowLimit) {
  16179. return cb();
  16180. }
  16181. this.parsedLineCount += 1;
  16182. if (this.shouldSkipLine) {
  16183. return callNext();
  16184. }
  16185. const row = rows[i];
  16186. this.rowCount += 1;
  16187. this.parsedRowCount += 1;
  16188. const nextRowCount = this.rowCount;
  16189. return this.transformRow(row, (err, transformResult) => {
  16190. if (err) {
  16191. this.rowCount -= 1;
  16192. return callNext(err);
  16193. }
  16194. if (!transformResult) {
  16195. return callNext(new Error('expected transform result'));
  16196. }
  16197. if (!transformResult.isValid) {
  16198. this.emit('data-invalid', transformResult.row, nextRowCount, transformResult.reason);
  16199. } else if (transformResult.row) {
  16200. return this.pushRow(transformResult.row, callNext);
  16201. }
  16202. return callNext();
  16203. });
  16204. };
  16205. iterate(0);
  16206. }
  16207. transformRow(parsedRow, cb) {
  16208. try {
  16209. this.headerTransformer.transform(parsedRow, (err, withHeaders) => {
  16210. if (err) {
  16211. return cb(err);
  16212. }
  16213. if (!withHeaders) {
  16214. return cb(new Error('Expected result from header transform'));
  16215. }
  16216. if (!withHeaders.isValid) {
  16217. if (this.shouldEmitRows) {
  16218. return cb(null, {
  16219. isValid: false,
  16220. row: parsedRow
  16221. });
  16222. }
  16223. // skipped because of skipRows option remove from total row count
  16224. return this.skipRow(cb);
  16225. }
  16226. if (withHeaders.row) {
  16227. if (this.shouldEmitRows) {
  16228. return this.rowTransformerValidator.transformAndValidate(withHeaders.row, cb);
  16229. }
  16230. // skipped because of skipRows option remove from total row count
  16231. return this.skipRow(cb);
  16232. }
  16233. // this is a header row dont include in the rowCount or parsedRowCount
  16234. this.rowCount -= 1;
  16235. this.parsedRowCount -= 1;
  16236. return cb(null, {
  16237. row: null,
  16238. isValid: true
  16239. });
  16240. });
  16241. } catch (e) {
  16242. cb(e);
  16243. }
  16244. }
  16245. checkAndEmitHeaders() {
  16246. if (!this.headersEmitted && this.headerTransformer.headers) {
  16247. this.headersEmitted = true;
  16248. this.emit('headers', this.headerTransformer.headers);
  16249. }
  16250. }
  16251. skipRow(cb) {
  16252. // skipped because of skipRows option remove from total row count
  16253. this.rowCount -= 1;
  16254. return cb(null, {
  16255. row: null,
  16256. isValid: true
  16257. });
  16258. }
  16259. pushRow(row, cb) {
  16260. try {
  16261. if (!this.parserOptions.objectMode) {
  16262. this.push(JSON.stringify(row));
  16263. } else {
  16264. this.push(row);
  16265. }
  16266. cb();
  16267. } catch (e) {
  16268. cb(e);
  16269. }
  16270. }
  16271. static wrapDoneCallback(done) {
  16272. let errorCalled = false;
  16273. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16274. return function (err) {
  16275. if (err) {
  16276. if (errorCalled) {
  16277. throw err;
  16278. }
  16279. errorCalled = true;
  16280. done(err);
  16281. return;
  16282. }
  16283. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  16284. args[_key2 - 1] = arguments[_key2];
  16285. }
  16286. done(...args);
  16287. };
  16288. }
  16289. }
  16290. exports.CsvParserStream = CsvParserStream;
  16291. }).call(this)}).call(this,require("timers").setImmediate)
  16292. },{"./parser":165,"./transforms":168,"stream":343,"string_decoder":218,"timers":361}],154:[function(require,module,exports){
  16293. "use strict";
  16294. var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  16295. return mod && mod.__esModule ? mod : {
  16296. "default": mod
  16297. };
  16298. };
  16299. Object.defineProperty(exports, "__esModule", {
  16300. value: true
  16301. });
  16302. exports.ParserOptions = void 0;
  16303. const lodash_escaperegexp_1 = __importDefault(require("lodash.escaperegexp"));
  16304. const lodash_isnil_1 = __importDefault(require("lodash.isnil"));
  16305. class ParserOptions {
  16306. constructor(opts) {
  16307. var _a;
  16308. this.objectMode = true;
  16309. this.delimiter = ',';
  16310. this.ignoreEmpty = false;
  16311. this.quote = '"';
  16312. this.escape = null;
  16313. this.escapeChar = this.quote;
  16314. this.comment = null;
  16315. this.supportsComments = false;
  16316. this.ltrim = false;
  16317. this.rtrim = false;
  16318. this.trim = false;
  16319. this.headers = null;
  16320. this.renameHeaders = false;
  16321. this.strictColumnHandling = false;
  16322. this.discardUnmappedColumns = false;
  16323. this.carriageReturn = '\r';
  16324. this.encoding = 'utf8';
  16325. this.limitRows = false;
  16326. this.maxRows = 0;
  16327. this.skipLines = 0;
  16328. this.skipRows = 0;
  16329. Object.assign(this, opts || {});
  16330. if (this.delimiter.length > 1) {
  16331. throw new Error('delimiter option must be one character long');
  16332. }
  16333. this.escapedDelimiter = lodash_escaperegexp_1.default(this.delimiter);
  16334. this.escapeChar = (_a = this.escape) !== null && _a !== void 0 ? _a : this.quote;
  16335. this.supportsComments = !lodash_isnil_1.default(this.comment);
  16336. this.NEXT_TOKEN_REGEXP = new RegExp(`([^\\s]|\\r\\n|\\n|\\r|${this.escapedDelimiter})`);
  16337. if (this.maxRows > 0) {
  16338. this.limitRows = true;
  16339. }
  16340. }
  16341. }
  16342. exports.ParserOptions = ParserOptions;
  16343. },{"lodash.escaperegexp":281,"lodash.isnil":286}],155:[function(require,module,exports){
  16344. "use strict";
  16345. var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) {
  16346. if (k2 === undefined) k2 = k;
  16347. Object.defineProperty(o, k2, {
  16348. enumerable: true,
  16349. get: function () {
  16350. return m[k];
  16351. }
  16352. });
  16353. } : function (o, m, k, k2) {
  16354. if (k2 === undefined) k2 = k;
  16355. o[k2] = m[k];
  16356. });
  16357. var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) {
  16358. Object.defineProperty(o, "default", {
  16359. enumerable: true,
  16360. value: v
  16361. });
  16362. } : function (o, v) {
  16363. o["default"] = v;
  16364. });
  16365. var __importStar = void 0 && (void 0).__importStar || function (mod) {
  16366. if (mod && mod.__esModule) return mod;
  16367. var result = {};
  16368. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  16369. __setModuleDefault(result, mod);
  16370. return result;
  16371. };
  16372. var __exportStar = void 0 && (void 0).__exportStar || function (m, exports) {
  16373. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
  16374. };
  16375. Object.defineProperty(exports, "__esModule", {
  16376. value: true
  16377. });
  16378. exports.parseString = exports.parseFile = exports.parseStream = exports.parse = exports.ParserOptions = exports.CsvParserStream = void 0;
  16379. const fs = __importStar(require("fs"));
  16380. const stream_1 = require("stream");
  16381. const ParserOptions_1 = require("./ParserOptions");
  16382. const CsvParserStream_1 = require("./CsvParserStream");
  16383. __exportStar(require("./types"), exports);
  16384. var CsvParserStream_2 = require("./CsvParserStream");
  16385. Object.defineProperty(exports, "CsvParserStream", {
  16386. enumerable: true,
  16387. get: function () {
  16388. return CsvParserStream_2.CsvParserStream;
  16389. }
  16390. });
  16391. var ParserOptions_2 = require("./ParserOptions");
  16392. Object.defineProperty(exports, "ParserOptions", {
  16393. enumerable: true,
  16394. get: function () {
  16395. return ParserOptions_2.ParserOptions;
  16396. }
  16397. });
  16398. exports.parse = args => new CsvParserStream_1.CsvParserStream(new ParserOptions_1.ParserOptions(args));
  16399. exports.parseStream = (stream, options) => stream.pipe(new CsvParserStream_1.CsvParserStream(new ParserOptions_1.ParserOptions(options)));
  16400. exports.parseFile = function (location) {
  16401. let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  16402. return fs.createReadStream(location).pipe(new CsvParserStream_1.CsvParserStream(new ParserOptions_1.ParserOptions(options)));
  16403. };
  16404. exports.parseString = (string, options) => {
  16405. const rs = new stream_1.Readable();
  16406. rs.push(string);
  16407. rs.push(null);
  16408. return rs.pipe(new CsvParserStream_1.CsvParserStream(new ParserOptions_1.ParserOptions(options)));
  16409. };
  16410. },{"./CsvParserStream":153,"./ParserOptions":154,"./types":169,"fs":216,"stream":343}],156:[function(require,module,exports){
  16411. "use strict";
  16412. Object.defineProperty(exports, "__esModule", {
  16413. value: true
  16414. });
  16415. exports.Parser = void 0;
  16416. const Scanner_1 = require("./Scanner");
  16417. const RowParser_1 = require("./RowParser");
  16418. const Token_1 = require("./Token");
  16419. class Parser {
  16420. constructor(parserOptions) {
  16421. this.parserOptions = parserOptions;
  16422. this.rowParser = new RowParser_1.RowParser(this.parserOptions);
  16423. }
  16424. static removeBOM(line) {
  16425. // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
  16426. // conversion translates it to FEFF (UTF-16 BOM)
  16427. if (line && line.charCodeAt(0) === 0xfeff) {
  16428. return line.slice(1);
  16429. }
  16430. return line;
  16431. }
  16432. parse(line, hasMoreData) {
  16433. const scanner = new Scanner_1.Scanner({
  16434. line: Parser.removeBOM(line),
  16435. parserOptions: this.parserOptions,
  16436. hasMoreData
  16437. });
  16438. if (this.parserOptions.supportsComments) {
  16439. return this.parseWithComments(scanner);
  16440. }
  16441. return this.parseWithoutComments(scanner);
  16442. }
  16443. parseWithoutComments(scanner) {
  16444. const rows = [];
  16445. let shouldContinue = true;
  16446. while (shouldContinue) {
  16447. shouldContinue = this.parseRow(scanner, rows);
  16448. }
  16449. return {
  16450. line: scanner.line,
  16451. rows
  16452. };
  16453. }
  16454. parseWithComments(scanner) {
  16455. const {
  16456. parserOptions
  16457. } = this;
  16458. const rows = [];
  16459. for (let nextToken = scanner.nextCharacterToken; nextToken !== null; nextToken = scanner.nextCharacterToken) {
  16460. if (Token_1.Token.isTokenComment(nextToken, parserOptions)) {
  16461. const cursor = scanner.advancePastLine();
  16462. if (cursor === null) {
  16463. return {
  16464. line: scanner.lineFromCursor,
  16465. rows
  16466. };
  16467. }
  16468. if (!scanner.hasMoreCharacters) {
  16469. return {
  16470. line: scanner.lineFromCursor,
  16471. rows
  16472. };
  16473. }
  16474. scanner.truncateToCursor();
  16475. } else if (!this.parseRow(scanner, rows)) {
  16476. break;
  16477. }
  16478. }
  16479. return {
  16480. line: scanner.line,
  16481. rows
  16482. };
  16483. }
  16484. parseRow(scanner, rows) {
  16485. const nextToken = scanner.nextNonSpaceToken;
  16486. if (!nextToken) {
  16487. return false;
  16488. }
  16489. const row = this.rowParser.parse(scanner);
  16490. if (row === null) {
  16491. return false;
  16492. }
  16493. if (this.parserOptions.ignoreEmpty && RowParser_1.RowParser.isEmptyRow(row)) {
  16494. return true;
  16495. }
  16496. rows.push(row);
  16497. return true;
  16498. }
  16499. }
  16500. exports.Parser = Parser;
  16501. },{"./RowParser":157,"./Scanner":158,"./Token":159}],157:[function(require,module,exports){
  16502. "use strict";
  16503. Object.defineProperty(exports, "__esModule", {
  16504. value: true
  16505. });
  16506. exports.RowParser = void 0;
  16507. const column_1 = require("./column");
  16508. const Token_1 = require("./Token");
  16509. const EMPTY_STRING = '';
  16510. class RowParser {
  16511. constructor(parserOptions) {
  16512. this.parserOptions = parserOptions;
  16513. this.columnParser = new column_1.ColumnParser(parserOptions);
  16514. }
  16515. static isEmptyRow(row) {
  16516. return row.join(EMPTY_STRING).replace(/\s+/g, EMPTY_STRING) === EMPTY_STRING;
  16517. }
  16518. parse(scanner) {
  16519. const {
  16520. parserOptions
  16521. } = this;
  16522. const {
  16523. hasMoreData
  16524. } = scanner;
  16525. const currentScanner = scanner;
  16526. const columns = [];
  16527. let currentToken = this.getStartToken(currentScanner, columns);
  16528. while (currentToken) {
  16529. if (Token_1.Token.isTokenRowDelimiter(currentToken)) {
  16530. currentScanner.advancePastToken(currentToken);
  16531. // if ends with CR and there is more data, keep unparsed due to possible
  16532. // coming LF in CRLF
  16533. if (!currentScanner.hasMoreCharacters && Token_1.Token.isTokenCarriageReturn(currentToken, parserOptions) && hasMoreData) {
  16534. return null;
  16535. }
  16536. currentScanner.truncateToCursor();
  16537. return columns;
  16538. }
  16539. if (!this.shouldSkipColumnParse(currentScanner, currentToken, columns)) {
  16540. const item = this.columnParser.parse(currentScanner);
  16541. if (item === null) {
  16542. return null;
  16543. }
  16544. columns.push(item);
  16545. }
  16546. currentToken = currentScanner.nextNonSpaceToken;
  16547. }
  16548. if (!hasMoreData) {
  16549. currentScanner.truncateToCursor();
  16550. return columns;
  16551. }
  16552. return null;
  16553. }
  16554. getStartToken(scanner, columns) {
  16555. const currentToken = scanner.nextNonSpaceToken;
  16556. if (currentToken !== null && Token_1.Token.isTokenDelimiter(currentToken, this.parserOptions)) {
  16557. columns.push('');
  16558. return scanner.nextNonSpaceToken;
  16559. }
  16560. return currentToken;
  16561. }
  16562. shouldSkipColumnParse(scanner, currentToken, columns) {
  16563. const {
  16564. parserOptions
  16565. } = this;
  16566. if (Token_1.Token.isTokenDelimiter(currentToken, parserOptions)) {
  16567. scanner.advancePastToken(currentToken);
  16568. // if the delimiter is at the end of a line
  16569. const nextToken = scanner.nextCharacterToken;
  16570. if (!scanner.hasMoreCharacters || nextToken !== null && Token_1.Token.isTokenRowDelimiter(nextToken)) {
  16571. columns.push('');
  16572. return true;
  16573. }
  16574. if (nextToken !== null && Token_1.Token.isTokenDelimiter(nextToken, parserOptions)) {
  16575. columns.push('');
  16576. return true;
  16577. }
  16578. }
  16579. return false;
  16580. }
  16581. }
  16582. exports.RowParser = RowParser;
  16583. },{"./Token":159,"./column":164}],158:[function(require,module,exports){
  16584. "use strict";
  16585. Object.defineProperty(exports, "__esModule", {
  16586. value: true
  16587. });
  16588. exports.Scanner = void 0;
  16589. const Token_1 = require("./Token");
  16590. const ROW_DELIMITER = /((?:\r\n)|\n|\r)/;
  16591. class Scanner {
  16592. constructor(args) {
  16593. this.cursor = 0;
  16594. this.line = args.line;
  16595. this.lineLength = this.line.length;
  16596. this.parserOptions = args.parserOptions;
  16597. this.hasMoreData = args.hasMoreData;
  16598. this.cursor = args.cursor || 0;
  16599. }
  16600. get hasMoreCharacters() {
  16601. return this.lineLength > this.cursor;
  16602. }
  16603. get nextNonSpaceToken() {
  16604. const {
  16605. lineFromCursor
  16606. } = this;
  16607. const regex = this.parserOptions.NEXT_TOKEN_REGEXP;
  16608. if (lineFromCursor.search(regex) === -1) {
  16609. return null;
  16610. }
  16611. const match = regex.exec(lineFromCursor);
  16612. if (match == null) {
  16613. return null;
  16614. }
  16615. const token = match[1];
  16616. const startCursor = this.cursor + (match.index || 0);
  16617. return new Token_1.Token({
  16618. token,
  16619. startCursor,
  16620. endCursor: startCursor + token.length - 1
  16621. });
  16622. }
  16623. get nextCharacterToken() {
  16624. const {
  16625. cursor,
  16626. lineLength
  16627. } = this;
  16628. if (lineLength <= cursor) {
  16629. return null;
  16630. }
  16631. return new Token_1.Token({
  16632. token: this.line[cursor],
  16633. startCursor: cursor,
  16634. endCursor: cursor
  16635. });
  16636. }
  16637. get lineFromCursor() {
  16638. return this.line.substr(this.cursor);
  16639. }
  16640. advancePastLine() {
  16641. const match = ROW_DELIMITER.exec(this.lineFromCursor);
  16642. if (!match) {
  16643. if (this.hasMoreData) {
  16644. return null;
  16645. }
  16646. this.cursor = this.lineLength;
  16647. return this;
  16648. }
  16649. this.cursor += (match.index || 0) + match[0].length;
  16650. return this;
  16651. }
  16652. advanceTo(cursor) {
  16653. this.cursor = cursor;
  16654. return this;
  16655. }
  16656. advanceToToken(token) {
  16657. this.cursor = token.startCursor;
  16658. return this;
  16659. }
  16660. advancePastToken(token) {
  16661. this.cursor = token.endCursor + 1;
  16662. return this;
  16663. }
  16664. truncateToCursor() {
  16665. this.line = this.lineFromCursor;
  16666. this.lineLength = this.line.length;
  16667. this.cursor = 0;
  16668. return this;
  16669. }
  16670. }
  16671. exports.Scanner = Scanner;
  16672. },{"./Token":159}],159:[function(require,module,exports){
  16673. "use strict";
  16674. Object.defineProperty(exports, "__esModule", {
  16675. value: true
  16676. });
  16677. exports.Token = void 0;
  16678. class Token {
  16679. constructor(tokenArgs) {
  16680. this.token = tokenArgs.token;
  16681. this.startCursor = tokenArgs.startCursor;
  16682. this.endCursor = tokenArgs.endCursor;
  16683. }
  16684. static isTokenRowDelimiter(token) {
  16685. const content = token.token;
  16686. return content === '\r' || content === '\n' || content === '\r\n';
  16687. }
  16688. static isTokenCarriageReturn(token, parserOptions) {
  16689. return token.token === parserOptions.carriageReturn;
  16690. }
  16691. static isTokenComment(token, parserOptions) {
  16692. return parserOptions.supportsComments && !!token && token.token === parserOptions.comment;
  16693. }
  16694. static isTokenEscapeCharacter(token, parserOptions) {
  16695. return token.token === parserOptions.escapeChar;
  16696. }
  16697. static isTokenQuote(token, parserOptions) {
  16698. return token.token === parserOptions.quote;
  16699. }
  16700. static isTokenDelimiter(token, parserOptions) {
  16701. return token.token === parserOptions.delimiter;
  16702. }
  16703. }
  16704. exports.Token = Token;
  16705. },{}],160:[function(require,module,exports){
  16706. "use strict";
  16707. Object.defineProperty(exports, "__esModule", {
  16708. value: true
  16709. });
  16710. exports.ColumnFormatter = void 0;
  16711. class ColumnFormatter {
  16712. constructor(parserOptions) {
  16713. if (parserOptions.trim) {
  16714. this.format = col => col.trim();
  16715. } else if (parserOptions.ltrim) {
  16716. this.format = col => col.trimLeft();
  16717. } else if (parserOptions.rtrim) {
  16718. this.format = col => col.trimRight();
  16719. } else {
  16720. this.format = col => col;
  16721. }
  16722. }
  16723. }
  16724. exports.ColumnFormatter = ColumnFormatter;
  16725. },{}],161:[function(require,module,exports){
  16726. "use strict";
  16727. Object.defineProperty(exports, "__esModule", {
  16728. value: true
  16729. });
  16730. exports.ColumnParser = void 0;
  16731. const NonQuotedColumnParser_1 = require("./NonQuotedColumnParser");
  16732. const QuotedColumnParser_1 = require("./QuotedColumnParser");
  16733. const Token_1 = require("../Token");
  16734. class ColumnParser {
  16735. constructor(parserOptions) {
  16736. this.parserOptions = parserOptions;
  16737. this.quotedColumnParser = new QuotedColumnParser_1.QuotedColumnParser(parserOptions);
  16738. this.nonQuotedColumnParser = new NonQuotedColumnParser_1.NonQuotedColumnParser(parserOptions);
  16739. }
  16740. parse(scanner) {
  16741. const {
  16742. nextNonSpaceToken
  16743. } = scanner;
  16744. if (nextNonSpaceToken !== null && Token_1.Token.isTokenQuote(nextNonSpaceToken, this.parserOptions)) {
  16745. scanner.advanceToToken(nextNonSpaceToken);
  16746. return this.quotedColumnParser.parse(scanner);
  16747. }
  16748. return this.nonQuotedColumnParser.parse(scanner);
  16749. }
  16750. }
  16751. exports.ColumnParser = ColumnParser;
  16752. },{"../Token":159,"./NonQuotedColumnParser":162,"./QuotedColumnParser":163}],162:[function(require,module,exports){
  16753. "use strict";
  16754. Object.defineProperty(exports, "__esModule", {
  16755. value: true
  16756. });
  16757. exports.NonQuotedColumnParser = void 0;
  16758. const ColumnFormatter_1 = require("./ColumnFormatter");
  16759. const Token_1 = require("../Token");
  16760. class NonQuotedColumnParser {
  16761. constructor(parserOptions) {
  16762. this.parserOptions = parserOptions;
  16763. this.columnFormatter = new ColumnFormatter_1.ColumnFormatter(parserOptions);
  16764. }
  16765. parse(scanner) {
  16766. if (!scanner.hasMoreCharacters) {
  16767. return null;
  16768. }
  16769. const {
  16770. parserOptions
  16771. } = this;
  16772. const characters = [];
  16773. let nextToken = scanner.nextCharacterToken;
  16774. for (; nextToken; nextToken = scanner.nextCharacterToken) {
  16775. if (Token_1.Token.isTokenDelimiter(nextToken, parserOptions) || Token_1.Token.isTokenRowDelimiter(nextToken)) {
  16776. break;
  16777. }
  16778. characters.push(nextToken.token);
  16779. scanner.advancePastToken(nextToken);
  16780. }
  16781. return this.columnFormatter.format(characters.join(''));
  16782. }
  16783. }
  16784. exports.NonQuotedColumnParser = NonQuotedColumnParser;
  16785. },{"../Token":159,"./ColumnFormatter":160}],163:[function(require,module,exports){
  16786. "use strict";
  16787. Object.defineProperty(exports, "__esModule", {
  16788. value: true
  16789. });
  16790. exports.QuotedColumnParser = void 0;
  16791. const ColumnFormatter_1 = require("./ColumnFormatter");
  16792. const Token_1 = require("../Token");
  16793. class QuotedColumnParser {
  16794. constructor(parserOptions) {
  16795. this.parserOptions = parserOptions;
  16796. this.columnFormatter = new ColumnFormatter_1.ColumnFormatter(parserOptions);
  16797. }
  16798. parse(scanner) {
  16799. if (!scanner.hasMoreCharacters) {
  16800. return null;
  16801. }
  16802. const originalCursor = scanner.cursor;
  16803. const {
  16804. foundClosingQuote,
  16805. col
  16806. } = this.gatherDataBetweenQuotes(scanner);
  16807. if (!foundClosingQuote) {
  16808. // reset the cursor to the original
  16809. scanner.advanceTo(originalCursor);
  16810. // if we didnt find a closing quote but we potentially have more data then skip the parsing
  16811. // and return the original scanner.
  16812. if (!scanner.hasMoreData) {
  16813. throw new Error(`Parse Error: missing closing: '${this.parserOptions.quote || ''}' in line: at '${scanner.lineFromCursor.replace(/[\r\n]/g, "\\n'")}'`);
  16814. }
  16815. return null;
  16816. }
  16817. this.checkForMalformedColumn(scanner);
  16818. return col;
  16819. }
  16820. gatherDataBetweenQuotes(scanner) {
  16821. const {
  16822. parserOptions
  16823. } = this;
  16824. let foundStartingQuote = false;
  16825. let foundClosingQuote = false;
  16826. const characters = [];
  16827. let nextToken = scanner.nextCharacterToken;
  16828. for (; !foundClosingQuote && nextToken !== null; nextToken = scanner.nextCharacterToken) {
  16829. const isQuote = Token_1.Token.isTokenQuote(nextToken, parserOptions);
  16830. // ignore first quote
  16831. if (!foundStartingQuote && isQuote) {
  16832. foundStartingQuote = true;
  16833. } else if (foundStartingQuote) {
  16834. if (Token_1.Token.isTokenEscapeCharacter(nextToken, parserOptions)) {
  16835. // advance past the escape character so we can get the next one in line
  16836. scanner.advancePastToken(nextToken);
  16837. const tokenFollowingEscape = scanner.nextCharacterToken;
  16838. // if the character following the escape is a quote character then just add
  16839. // the quote and advance to that character
  16840. if (tokenFollowingEscape !== null && (Token_1.Token.isTokenQuote(tokenFollowingEscape, parserOptions) || Token_1.Token.isTokenEscapeCharacter(tokenFollowingEscape, parserOptions))) {
  16841. characters.push(tokenFollowingEscape.token);
  16842. nextToken = tokenFollowingEscape;
  16843. } else if (isQuote) {
  16844. // if the escape is also a quote then we found our closing quote and finish early
  16845. foundClosingQuote = true;
  16846. } else {
  16847. // other wise add the escape token to the characters since it wast escaping anything
  16848. characters.push(nextToken.token);
  16849. }
  16850. } else if (isQuote) {
  16851. // we found our closing quote!
  16852. foundClosingQuote = true;
  16853. } else {
  16854. // add the token to the characters
  16855. characters.push(nextToken.token);
  16856. }
  16857. }
  16858. scanner.advancePastToken(nextToken);
  16859. }
  16860. return {
  16861. col: this.columnFormatter.format(characters.join('')),
  16862. foundClosingQuote
  16863. };
  16864. }
  16865. checkForMalformedColumn(scanner) {
  16866. const {
  16867. parserOptions
  16868. } = this;
  16869. const {
  16870. nextNonSpaceToken
  16871. } = scanner;
  16872. if (nextNonSpaceToken) {
  16873. const isNextTokenADelimiter = Token_1.Token.isTokenDelimiter(nextNonSpaceToken, parserOptions);
  16874. const isNextTokenARowDelimiter = Token_1.Token.isTokenRowDelimiter(nextNonSpaceToken);
  16875. if (!(isNextTokenADelimiter || isNextTokenARowDelimiter)) {
  16876. // if the final quote was NOT followed by a column (,) or row(\n) delimiter then its a bad column
  16877. // tldr: only part of the column was quoted
  16878. const linePreview = scanner.lineFromCursor.substr(0, 10).replace(/[\r\n]/g, "\\n'");
  16879. throw new Error(`Parse Error: expected: '${parserOptions.escapedDelimiter}' OR new line got: '${nextNonSpaceToken.token}'. at '${linePreview}`);
  16880. }
  16881. scanner.advanceToToken(nextNonSpaceToken);
  16882. } else if (!scanner.hasMoreData) {
  16883. scanner.advancePastLine();
  16884. }
  16885. }
  16886. }
  16887. exports.QuotedColumnParser = QuotedColumnParser;
  16888. },{"../Token":159,"./ColumnFormatter":160}],164:[function(require,module,exports){
  16889. "use strict";
  16890. Object.defineProperty(exports, "__esModule", {
  16891. value: true
  16892. });
  16893. exports.ColumnFormatter = exports.QuotedColumnParser = exports.NonQuotedColumnParser = exports.ColumnParser = void 0;
  16894. var ColumnParser_1 = require("./ColumnParser");
  16895. Object.defineProperty(exports, "ColumnParser", {
  16896. enumerable: true,
  16897. get: function () {
  16898. return ColumnParser_1.ColumnParser;
  16899. }
  16900. });
  16901. var NonQuotedColumnParser_1 = require("./NonQuotedColumnParser");
  16902. Object.defineProperty(exports, "NonQuotedColumnParser", {
  16903. enumerable: true,
  16904. get: function () {
  16905. return NonQuotedColumnParser_1.NonQuotedColumnParser;
  16906. }
  16907. });
  16908. var QuotedColumnParser_1 = require("./QuotedColumnParser");
  16909. Object.defineProperty(exports, "QuotedColumnParser", {
  16910. enumerable: true,
  16911. get: function () {
  16912. return QuotedColumnParser_1.QuotedColumnParser;
  16913. }
  16914. });
  16915. var ColumnFormatter_1 = require("./ColumnFormatter");
  16916. Object.defineProperty(exports, "ColumnFormatter", {
  16917. enumerable: true,
  16918. get: function () {
  16919. return ColumnFormatter_1.ColumnFormatter;
  16920. }
  16921. });
  16922. },{"./ColumnFormatter":160,"./ColumnParser":161,"./NonQuotedColumnParser":162,"./QuotedColumnParser":163}],165:[function(require,module,exports){
  16923. "use strict";
  16924. Object.defineProperty(exports, "__esModule", {
  16925. value: true
  16926. });
  16927. exports.QuotedColumnParser = exports.NonQuotedColumnParser = exports.ColumnParser = exports.Token = exports.Scanner = exports.RowParser = exports.Parser = void 0;
  16928. var Parser_1 = require("./Parser");
  16929. Object.defineProperty(exports, "Parser", {
  16930. enumerable: true,
  16931. get: function () {
  16932. return Parser_1.Parser;
  16933. }
  16934. });
  16935. var RowParser_1 = require("./RowParser");
  16936. Object.defineProperty(exports, "RowParser", {
  16937. enumerable: true,
  16938. get: function () {
  16939. return RowParser_1.RowParser;
  16940. }
  16941. });
  16942. var Scanner_1 = require("./Scanner");
  16943. Object.defineProperty(exports, "Scanner", {
  16944. enumerable: true,
  16945. get: function () {
  16946. return Scanner_1.Scanner;
  16947. }
  16948. });
  16949. var Token_1 = require("./Token");
  16950. Object.defineProperty(exports, "Token", {
  16951. enumerable: true,
  16952. get: function () {
  16953. return Token_1.Token;
  16954. }
  16955. });
  16956. var column_1 = require("./column");
  16957. Object.defineProperty(exports, "ColumnParser", {
  16958. enumerable: true,
  16959. get: function () {
  16960. return column_1.ColumnParser;
  16961. }
  16962. });
  16963. Object.defineProperty(exports, "NonQuotedColumnParser", {
  16964. enumerable: true,
  16965. get: function () {
  16966. return column_1.NonQuotedColumnParser;
  16967. }
  16968. });
  16969. Object.defineProperty(exports, "QuotedColumnParser", {
  16970. enumerable: true,
  16971. get: function () {
  16972. return column_1.QuotedColumnParser;
  16973. }
  16974. });
  16975. },{"./Parser":156,"./RowParser":157,"./Scanner":158,"./Token":159,"./column":164}],166:[function(require,module,exports){
  16976. "use strict";
  16977. var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  16978. return mod && mod.__esModule ? mod : {
  16979. "default": mod
  16980. };
  16981. };
  16982. Object.defineProperty(exports, "__esModule", {
  16983. value: true
  16984. });
  16985. exports.HeaderTransformer = void 0;
  16986. const lodash_isundefined_1 = __importDefault(require("lodash.isundefined"));
  16987. const lodash_isfunction_1 = __importDefault(require("lodash.isfunction"));
  16988. const lodash_uniq_1 = __importDefault(require("lodash.uniq"));
  16989. const lodash_groupby_1 = __importDefault(require("lodash.groupby"));
  16990. class HeaderTransformer {
  16991. constructor(parserOptions) {
  16992. this.headers = null;
  16993. this.receivedHeaders = false;
  16994. this.shouldUseFirstRow = false;
  16995. this.processedFirstRow = false;
  16996. this.headersLength = 0;
  16997. this.parserOptions = parserOptions;
  16998. if (parserOptions.headers === true) {
  16999. this.shouldUseFirstRow = true;
  17000. } else if (Array.isArray(parserOptions.headers)) {
  17001. this.setHeaders(parserOptions.headers);
  17002. } else if (lodash_isfunction_1.default(parserOptions.headers)) {
  17003. this.headersTransform = parserOptions.headers;
  17004. }
  17005. }
  17006. transform(row, cb) {
  17007. if (!this.shouldMapRow(row)) {
  17008. return cb(null, {
  17009. row: null,
  17010. isValid: true
  17011. });
  17012. }
  17013. return cb(null, this.processRow(row));
  17014. }
  17015. shouldMapRow(row) {
  17016. const {
  17017. parserOptions
  17018. } = this;
  17019. if (!this.headersTransform && parserOptions.renameHeaders && !this.processedFirstRow) {
  17020. if (!this.receivedHeaders) {
  17021. throw new Error('Error renaming headers: new headers must be provided in an array');
  17022. }
  17023. this.processedFirstRow = true;
  17024. return false;
  17025. }
  17026. if (!this.receivedHeaders && Array.isArray(row)) {
  17027. if (this.headersTransform) {
  17028. this.setHeaders(this.headersTransform(row));
  17029. } else if (this.shouldUseFirstRow) {
  17030. this.setHeaders(row);
  17031. } else {
  17032. // dont do anything with the headers if we didnt receive a transform or shouldnt use the first row.
  17033. return true;
  17034. }
  17035. return false;
  17036. }
  17037. return true;
  17038. }
  17039. processRow(row) {
  17040. if (!this.headers) {
  17041. return {
  17042. row: row,
  17043. isValid: true
  17044. };
  17045. }
  17046. const {
  17047. parserOptions
  17048. } = this;
  17049. if (!parserOptions.discardUnmappedColumns && row.length > this.headersLength) {
  17050. if (!parserOptions.strictColumnHandling) {
  17051. throw new Error(`Unexpected Error: column header mismatch expected: ${this.headersLength} columns got: ${row.length}`);
  17052. }
  17053. return {
  17054. row: row,
  17055. isValid: false,
  17056. reason: `Column header mismatch expected: ${this.headersLength} columns got: ${row.length}`
  17057. };
  17058. }
  17059. if (parserOptions.strictColumnHandling && row.length < this.headersLength) {
  17060. return {
  17061. row: row,
  17062. isValid: false,
  17063. reason: `Column header mismatch expected: ${this.headersLength} columns got: ${row.length}`
  17064. };
  17065. }
  17066. return {
  17067. row: this.mapHeaders(row),
  17068. isValid: true
  17069. };
  17070. }
  17071. mapHeaders(row) {
  17072. const rowMap = {};
  17073. const {
  17074. headers,
  17075. headersLength
  17076. } = this;
  17077. for (let i = 0; i < headersLength; i += 1) {
  17078. const header = headers[i];
  17079. if (!lodash_isundefined_1.default(header)) {
  17080. const val = row[i];
  17081. // eslint-disable-next-line no-param-reassign
  17082. if (lodash_isundefined_1.default(val)) {
  17083. rowMap[header] = '';
  17084. } else {
  17085. rowMap[header] = val;
  17086. }
  17087. }
  17088. }
  17089. return rowMap;
  17090. }
  17091. setHeaders(headers) {
  17092. var _a;
  17093. const filteredHeaders = headers.filter(h => !!h);
  17094. if (lodash_uniq_1.default(filteredHeaders).length !== filteredHeaders.length) {
  17095. const grouped = lodash_groupby_1.default(filteredHeaders);
  17096. const duplicates = Object.keys(grouped).filter(dup => grouped[dup].length > 1);
  17097. throw new Error(`Duplicate headers found ${JSON.stringify(duplicates)}`);
  17098. }
  17099. this.headers = headers;
  17100. this.receivedHeaders = true;
  17101. this.headersLength = ((_a = this.headers) === null || _a === void 0 ? void 0 : _a.length) || 0;
  17102. }
  17103. }
  17104. exports.HeaderTransformer = HeaderTransformer;
  17105. },{"lodash.groupby":282,"lodash.isfunction":285,"lodash.isundefined":287,"lodash.uniq":288}],167:[function(require,module,exports){
  17106. "use strict";
  17107. var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  17108. return mod && mod.__esModule ? mod : {
  17109. "default": mod
  17110. };
  17111. };
  17112. Object.defineProperty(exports, "__esModule", {
  17113. value: true
  17114. });
  17115. exports.RowTransformerValidator = void 0;
  17116. const lodash_isfunction_1 = __importDefault(require("lodash.isfunction"));
  17117. const types_1 = require("../types");
  17118. class RowTransformerValidator {
  17119. constructor() {
  17120. this._rowTransform = null;
  17121. this._rowValidator = null;
  17122. }
  17123. // eslint-disable-next-line @typescript-eslint/no-shadow
  17124. static createTransform(transformFunction) {
  17125. if (types_1.isSyncTransform(transformFunction)) {
  17126. return (row, cb) => {
  17127. let transformed = null;
  17128. try {
  17129. transformed = transformFunction(row);
  17130. } catch (e) {
  17131. return cb(e);
  17132. }
  17133. return cb(null, transformed);
  17134. };
  17135. }
  17136. return transformFunction;
  17137. }
  17138. static createValidator(validateFunction) {
  17139. if (types_1.isSyncValidate(validateFunction)) {
  17140. return (row, cb) => {
  17141. cb(null, {
  17142. row,
  17143. isValid: validateFunction(row)
  17144. });
  17145. };
  17146. }
  17147. return (row, cb) => {
  17148. validateFunction(row, (err, isValid, reason) => {
  17149. if (err) {
  17150. return cb(err);
  17151. }
  17152. if (isValid) {
  17153. return cb(null, {
  17154. row,
  17155. isValid,
  17156. reason
  17157. });
  17158. }
  17159. return cb(null, {
  17160. row,
  17161. isValid: false,
  17162. reason
  17163. });
  17164. });
  17165. };
  17166. }
  17167. set rowTransform(transformFunction) {
  17168. if (!lodash_isfunction_1.default(transformFunction)) {
  17169. throw new TypeError('The transform should be a function');
  17170. }
  17171. this._rowTransform = RowTransformerValidator.createTransform(transformFunction);
  17172. }
  17173. set rowValidator(validateFunction) {
  17174. if (!lodash_isfunction_1.default(validateFunction)) {
  17175. throw new TypeError('The validate should be a function');
  17176. }
  17177. this._rowValidator = RowTransformerValidator.createValidator(validateFunction);
  17178. }
  17179. transformAndValidate(row, cb) {
  17180. return this.callTransformer(row, (transformErr, transformedRow) => {
  17181. if (transformErr) {
  17182. return cb(transformErr);
  17183. }
  17184. if (!transformedRow) {
  17185. return cb(null, {
  17186. row: null,
  17187. isValid: true
  17188. });
  17189. }
  17190. return this.callValidator(transformedRow, (validateErr, validationResult) => {
  17191. if (validateErr) {
  17192. return cb(validateErr);
  17193. }
  17194. if (validationResult && !validationResult.isValid) {
  17195. return cb(null, {
  17196. row: transformedRow,
  17197. isValid: false,
  17198. reason: validationResult.reason
  17199. });
  17200. }
  17201. return cb(null, {
  17202. row: transformedRow,
  17203. isValid: true
  17204. });
  17205. });
  17206. });
  17207. }
  17208. callTransformer(row, cb) {
  17209. if (!this._rowTransform) {
  17210. return cb(null, row);
  17211. }
  17212. return this._rowTransform(row, cb);
  17213. }
  17214. callValidator(row, cb) {
  17215. if (!this._rowValidator) {
  17216. return cb(null, {
  17217. row,
  17218. isValid: true
  17219. });
  17220. }
  17221. return this._rowValidator(row, cb);
  17222. }
  17223. }
  17224. exports.RowTransformerValidator = RowTransformerValidator;
  17225. },{"../types":169,"lodash.isfunction":285}],168:[function(require,module,exports){
  17226. "use strict";
  17227. Object.defineProperty(exports, "__esModule", {
  17228. value: true
  17229. });
  17230. exports.HeaderTransformer = exports.RowTransformerValidator = void 0;
  17231. var RowTransformerValidator_1 = require("./RowTransformerValidator");
  17232. Object.defineProperty(exports, "RowTransformerValidator", {
  17233. enumerable: true,
  17234. get: function () {
  17235. return RowTransformerValidator_1.RowTransformerValidator;
  17236. }
  17237. });
  17238. var HeaderTransformer_1 = require("./HeaderTransformer");
  17239. Object.defineProperty(exports, "HeaderTransformer", {
  17240. enumerable: true,
  17241. get: function () {
  17242. return HeaderTransformer_1.HeaderTransformer;
  17243. }
  17244. });
  17245. },{"./HeaderTransformer":166,"./RowTransformerValidator":167}],169:[function(require,module,exports){
  17246. "use strict";
  17247. Object.defineProperty(exports, "__esModule", {
  17248. value: true
  17249. });
  17250. exports.isSyncValidate = exports.isSyncTransform = void 0;
  17251. exports.isSyncTransform = transform => transform.length === 1;
  17252. exports.isSyncValidate = validate => validate.length === 1;
  17253. },{}],170:[function(require,module,exports){
  17254. 'use strict';
  17255. const asn1 = exports;
  17256. asn1.bignum = require('bn.js');
  17257. asn1.define = require('./asn1/api').define;
  17258. asn1.base = require('./asn1/base');
  17259. asn1.constants = require('./asn1/constants');
  17260. asn1.decoders = require('./asn1/decoders');
  17261. asn1.encoders = require('./asn1/encoders');
  17262. },{"./asn1/api":171,"./asn1/base":173,"./asn1/constants":177,"./asn1/decoders":179,"./asn1/encoders":182,"bn.js":184}],171:[function(require,module,exports){
  17263. 'use strict';
  17264. const encoders = require('./encoders');
  17265. const decoders = require('./decoders');
  17266. const inherits = require('inherits');
  17267. const api = exports;
  17268. api.define = function define(name, body) {
  17269. return new Entity(name, body);
  17270. };
  17271. function Entity(name, body) {
  17272. this.name = name;
  17273. this.body = body;
  17274. this.decoders = {};
  17275. this.encoders = {};
  17276. }
  17277. Entity.prototype._createNamed = function createNamed(Base) {
  17278. const name = this.name;
  17279. function Generated(entity) {
  17280. this._initNamed(entity, name);
  17281. }
  17282. inherits(Generated, Base);
  17283. Generated.prototype._initNamed = function _initNamed(entity, name) {
  17284. Base.call(this, entity, name);
  17285. };
  17286. return new Generated(this);
  17287. };
  17288. Entity.prototype._getDecoder = function _getDecoder(enc) {
  17289. enc = enc || 'der';
  17290. // Lazily create decoder
  17291. if (!this.decoders.hasOwnProperty(enc)) this.decoders[enc] = this._createNamed(decoders[enc]);
  17292. return this.decoders[enc];
  17293. };
  17294. Entity.prototype.decode = function decode(data, enc, options) {
  17295. return this._getDecoder(enc).decode(data, options);
  17296. };
  17297. Entity.prototype._getEncoder = function _getEncoder(enc) {
  17298. enc = enc || 'der';
  17299. // Lazily create encoder
  17300. if (!this.encoders.hasOwnProperty(enc)) this.encoders[enc] = this._createNamed(encoders[enc]);
  17301. return this.encoders[enc];
  17302. };
  17303. Entity.prototype.encode = function encode(data, enc, /* internal */reporter) {
  17304. return this._getEncoder(enc).encode(data, reporter);
  17305. };
  17306. },{"./decoders":179,"./encoders":182,"inherits":279}],172:[function(require,module,exports){
  17307. 'use strict';
  17308. const inherits = require('inherits');
  17309. const Reporter = require('../base/reporter').Reporter;
  17310. const Buffer = require('safer-buffer').Buffer;
  17311. function DecoderBuffer(base, options) {
  17312. Reporter.call(this, options);
  17313. if (!Buffer.isBuffer(base)) {
  17314. this.error('Input not Buffer');
  17315. return;
  17316. }
  17317. this.base = base;
  17318. this.offset = 0;
  17319. this.length = base.length;
  17320. }
  17321. inherits(DecoderBuffer, Reporter);
  17322. exports.DecoderBuffer = DecoderBuffer;
  17323. DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) {
  17324. if (data instanceof DecoderBuffer) {
  17325. return true;
  17326. }
  17327. // Or accept compatible API
  17328. const isCompatible = typeof data === 'object' && Buffer.isBuffer(data.base) && data.constructor.name === 'DecoderBuffer' && typeof data.offset === 'number' && typeof data.length === 'number' && typeof data.save === 'function' && typeof data.restore === 'function' && typeof data.isEmpty === 'function' && typeof data.readUInt8 === 'function' && typeof data.skip === 'function' && typeof data.raw === 'function';
  17329. return isCompatible;
  17330. };
  17331. DecoderBuffer.prototype.save = function save() {
  17332. return {
  17333. offset: this.offset,
  17334. reporter: Reporter.prototype.save.call(this)
  17335. };
  17336. };
  17337. DecoderBuffer.prototype.restore = function restore(save) {
  17338. // Return skipped data
  17339. const res = new DecoderBuffer(this.base);
  17340. res.offset = save.offset;
  17341. res.length = this.offset;
  17342. this.offset = save.offset;
  17343. Reporter.prototype.restore.call(this, save.reporter);
  17344. return res;
  17345. };
  17346. DecoderBuffer.prototype.isEmpty = function isEmpty() {
  17347. return this.offset === this.length;
  17348. };
  17349. DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
  17350. if (this.offset + 1 <= this.length) return this.base.readUInt8(this.offset++, true);else return this.error(fail || 'DecoderBuffer overrun');
  17351. };
  17352. DecoderBuffer.prototype.skip = function skip(bytes, fail) {
  17353. if (!(this.offset + bytes <= this.length)) return this.error(fail || 'DecoderBuffer overrun');
  17354. const res = new DecoderBuffer(this.base);
  17355. // Share reporter state
  17356. res._reporterState = this._reporterState;
  17357. res.offset = this.offset;
  17358. res.length = this.offset + bytes;
  17359. this.offset += bytes;
  17360. return res;
  17361. };
  17362. DecoderBuffer.prototype.raw = function raw(save) {
  17363. return this.base.slice(save ? save.offset : this.offset, this.length);
  17364. };
  17365. function EncoderBuffer(value, reporter) {
  17366. if (Array.isArray(value)) {
  17367. this.length = 0;
  17368. this.value = value.map(function (item) {
  17369. if (!EncoderBuffer.isEncoderBuffer(item)) item = new EncoderBuffer(item, reporter);
  17370. this.length += item.length;
  17371. return item;
  17372. }, this);
  17373. } else if (typeof value === 'number') {
  17374. if (!(0 <= value && value <= 0xff)) return reporter.error('non-byte EncoderBuffer value');
  17375. this.value = value;
  17376. this.length = 1;
  17377. } else if (typeof value === 'string') {
  17378. this.value = value;
  17379. this.length = Buffer.byteLength(value);
  17380. } else if (Buffer.isBuffer(value)) {
  17381. this.value = value;
  17382. this.length = value.length;
  17383. } else {
  17384. return reporter.error('Unsupported type: ' + typeof value);
  17385. }
  17386. }
  17387. exports.EncoderBuffer = EncoderBuffer;
  17388. EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) {
  17389. if (data instanceof EncoderBuffer) {
  17390. return true;
  17391. }
  17392. // Or accept compatible API
  17393. const isCompatible = typeof data === 'object' && data.constructor.name === 'EncoderBuffer' && typeof data.length === 'number' && typeof data.join === 'function';
  17394. return isCompatible;
  17395. };
  17396. EncoderBuffer.prototype.join = function join(out, offset) {
  17397. if (!out) out = Buffer.alloc(this.length);
  17398. if (!offset) offset = 0;
  17399. if (this.length === 0) return out;
  17400. if (Array.isArray(this.value)) {
  17401. this.value.forEach(function (item) {
  17402. item.join(out, offset);
  17403. offset += item.length;
  17404. });
  17405. } else {
  17406. if (typeof this.value === 'number') out[offset] = this.value;else if (typeof this.value === 'string') out.write(this.value, offset);else if (Buffer.isBuffer(this.value)) this.value.copy(out, offset);
  17407. offset += this.length;
  17408. }
  17409. return out;
  17410. };
  17411. },{"../base/reporter":175,"inherits":279,"safer-buffer":333}],173:[function(require,module,exports){
  17412. 'use strict';
  17413. const base = exports;
  17414. base.Reporter = require('./reporter').Reporter;
  17415. base.DecoderBuffer = require('./buffer').DecoderBuffer;
  17416. base.EncoderBuffer = require('./buffer').EncoderBuffer;
  17417. base.Node = require('./node');
  17418. },{"./buffer":172,"./node":174,"./reporter":175}],174:[function(require,module,exports){
  17419. 'use strict';
  17420. const Reporter = require('../base/reporter').Reporter;
  17421. const EncoderBuffer = require('../base/buffer').EncoderBuffer;
  17422. const DecoderBuffer = require('../base/buffer').DecoderBuffer;
  17423. const assert = require('minimalistic-assert');
  17424. // Supported tags
  17425. const tags = ['seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'];
  17426. // Public methods list
  17427. const methods = ['key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains'].concat(tags);
  17428. // Overrided methods list
  17429. const overrided = ['_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool'];
  17430. function Node(enc, parent, name) {
  17431. const state = {};
  17432. this._baseState = state;
  17433. state.name = name;
  17434. state.enc = enc;
  17435. state.parent = parent || null;
  17436. state.children = null;
  17437. // State
  17438. state.tag = null;
  17439. state.args = null;
  17440. state.reverseArgs = null;
  17441. state.choice = null;
  17442. state.optional = false;
  17443. state.any = false;
  17444. state.obj = false;
  17445. state.use = null;
  17446. state.useDecoder = null;
  17447. state.key = null;
  17448. state['default'] = null;
  17449. state.explicit = null;
  17450. state.implicit = null;
  17451. state.contains = null;
  17452. // Should create new instance on each method
  17453. if (!state.parent) {
  17454. state.children = [];
  17455. this._wrap();
  17456. }
  17457. }
  17458. module.exports = Node;
  17459. const stateProps = ['enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains'];
  17460. Node.prototype.clone = function clone() {
  17461. const state = this._baseState;
  17462. const cstate = {};
  17463. stateProps.forEach(function (prop) {
  17464. cstate[prop] = state[prop];
  17465. });
  17466. const res = new this.constructor(cstate.parent);
  17467. res._baseState = cstate;
  17468. return res;
  17469. };
  17470. Node.prototype._wrap = function wrap() {
  17471. const state = this._baseState;
  17472. methods.forEach(function (method) {
  17473. this[method] = function _wrappedMethod() {
  17474. const clone = new this.constructor(this);
  17475. state.children.push(clone);
  17476. return clone[method].apply(clone, arguments);
  17477. };
  17478. }, this);
  17479. };
  17480. Node.prototype._init = function init(body) {
  17481. const state = this._baseState;
  17482. assert(state.parent === null);
  17483. body.call(this);
  17484. // Filter children
  17485. state.children = state.children.filter(function (child) {
  17486. return child._baseState.parent === this;
  17487. }, this);
  17488. assert.equal(state.children.length, 1, 'Root node can have only one child');
  17489. };
  17490. Node.prototype._useArgs = function useArgs(args) {
  17491. const state = this._baseState;
  17492. // Filter children and args
  17493. const children = args.filter(function (arg) {
  17494. return arg instanceof this.constructor;
  17495. }, this);
  17496. args = args.filter(function (arg) {
  17497. return !(arg instanceof this.constructor);
  17498. }, this);
  17499. if (children.length !== 0) {
  17500. assert(state.children === null);
  17501. state.children = children;
  17502. // Replace parent to maintain backward link
  17503. children.forEach(function (child) {
  17504. child._baseState.parent = this;
  17505. }, this);
  17506. }
  17507. if (args.length !== 0) {
  17508. assert(state.args === null);
  17509. state.args = args;
  17510. state.reverseArgs = args.map(function (arg) {
  17511. if (typeof arg !== 'object' || arg.constructor !== Object) return arg;
  17512. const res = {};
  17513. Object.keys(arg).forEach(function (key) {
  17514. if (key == (key | 0)) key |= 0;
  17515. const value = arg[key];
  17516. res[value] = key;
  17517. });
  17518. return res;
  17519. });
  17520. }
  17521. };
  17522. //
  17523. // Overrided methods
  17524. //
  17525. overrided.forEach(function (method) {
  17526. Node.prototype[method] = function _overrided() {
  17527. const state = this._baseState;
  17528. throw new Error(method + ' not implemented for encoding: ' + state.enc);
  17529. };
  17530. });
  17531. //
  17532. // Public methods
  17533. //
  17534. tags.forEach(function (tag) {
  17535. Node.prototype[tag] = function _tagMethod() {
  17536. const state = this._baseState;
  17537. const args = Array.prototype.slice.call(arguments);
  17538. assert(state.tag === null);
  17539. state.tag = tag;
  17540. this._useArgs(args);
  17541. return this;
  17542. };
  17543. });
  17544. Node.prototype.use = function use(item) {
  17545. assert(item);
  17546. const state = this._baseState;
  17547. assert(state.use === null);
  17548. state.use = item;
  17549. return this;
  17550. };
  17551. Node.prototype.optional = function optional() {
  17552. const state = this._baseState;
  17553. state.optional = true;
  17554. return this;
  17555. };
  17556. Node.prototype.def = function def(val) {
  17557. const state = this._baseState;
  17558. assert(state['default'] === null);
  17559. state['default'] = val;
  17560. state.optional = true;
  17561. return this;
  17562. };
  17563. Node.prototype.explicit = function explicit(num) {
  17564. const state = this._baseState;
  17565. assert(state.explicit === null && state.implicit === null);
  17566. state.explicit = num;
  17567. return this;
  17568. };
  17569. Node.prototype.implicit = function implicit(num) {
  17570. const state = this._baseState;
  17571. assert(state.explicit === null && state.implicit === null);
  17572. state.implicit = num;
  17573. return this;
  17574. };
  17575. Node.prototype.obj = function obj() {
  17576. const state = this._baseState;
  17577. const args = Array.prototype.slice.call(arguments);
  17578. state.obj = true;
  17579. if (args.length !== 0) this._useArgs(args);
  17580. return this;
  17581. };
  17582. Node.prototype.key = function key(newKey) {
  17583. const state = this._baseState;
  17584. assert(state.key === null);
  17585. state.key = newKey;
  17586. return this;
  17587. };
  17588. Node.prototype.any = function any() {
  17589. const state = this._baseState;
  17590. state.any = true;
  17591. return this;
  17592. };
  17593. Node.prototype.choice = function choice(obj) {
  17594. const state = this._baseState;
  17595. assert(state.choice === null);
  17596. state.choice = obj;
  17597. this._useArgs(Object.keys(obj).map(function (key) {
  17598. return obj[key];
  17599. }));
  17600. return this;
  17601. };
  17602. Node.prototype.contains = function contains(item) {
  17603. const state = this._baseState;
  17604. assert(state.use === null);
  17605. state.contains = item;
  17606. return this;
  17607. };
  17608. //
  17609. // Decoding
  17610. //
  17611. Node.prototype._decode = function decode(input, options) {
  17612. const state = this._baseState;
  17613. // Decode root node
  17614. if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options));
  17615. let result = state['default'];
  17616. let present = true;
  17617. let prevKey = null;
  17618. if (state.key !== null) prevKey = input.enterKey(state.key);
  17619. // Check if tag is there
  17620. if (state.optional) {
  17621. let tag = null;
  17622. if (state.explicit !== null) tag = state.explicit;else if (state.implicit !== null) tag = state.implicit;else if (state.tag !== null) tag = state.tag;
  17623. if (tag === null && !state.any) {
  17624. // Trial and Error
  17625. const save = input.save();
  17626. try {
  17627. if (state.choice === null) this._decodeGeneric(state.tag, input, options);else this._decodeChoice(input, options);
  17628. present = true;
  17629. } catch (e) {
  17630. present = false;
  17631. }
  17632. input.restore(save);
  17633. } else {
  17634. present = this._peekTag(input, tag, state.any);
  17635. if (input.isError(present)) return present;
  17636. }
  17637. }
  17638. // Push object on stack
  17639. let prevObj;
  17640. if (state.obj && present) prevObj = input.enterObject();
  17641. if (present) {
  17642. // Unwrap explicit values
  17643. if (state.explicit !== null) {
  17644. const explicit = this._decodeTag(input, state.explicit);
  17645. if (input.isError(explicit)) return explicit;
  17646. input = explicit;
  17647. }
  17648. const start = input.offset;
  17649. // Unwrap implicit and normal values
  17650. if (state.use === null && state.choice === null) {
  17651. let save;
  17652. if (state.any) save = input.save();
  17653. const body = this._decodeTag(input, state.implicit !== null ? state.implicit : state.tag, state.any);
  17654. if (input.isError(body)) return body;
  17655. if (state.any) result = input.raw(save);else input = body;
  17656. }
  17657. if (options && options.track && state.tag !== null) options.track(input.path(), start, input.length, 'tagged');
  17658. if (options && options.track && state.tag !== null) options.track(input.path(), input.offset, input.length, 'content');
  17659. // Select proper method for tag
  17660. if (state.any) {
  17661. // no-op
  17662. } else if (state.choice === null) {
  17663. result = this._decodeGeneric(state.tag, input, options);
  17664. } else {
  17665. result = this._decodeChoice(input, options);
  17666. }
  17667. if (input.isError(result)) return result;
  17668. // Decode children
  17669. if (!state.any && state.choice === null && state.children !== null) {
  17670. state.children.forEach(function decodeChildren(child) {
  17671. // NOTE: We are ignoring errors here, to let parser continue with other
  17672. // parts of encoded data
  17673. child._decode(input, options);
  17674. });
  17675. }
  17676. // Decode contained/encoded by schema, only in bit or octet strings
  17677. if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
  17678. const data = new DecoderBuffer(result);
  17679. result = this._getUse(state.contains, input._reporterState.obj)._decode(data, options);
  17680. }
  17681. }
  17682. // Pop object
  17683. if (state.obj && present) result = input.leaveObject(prevObj);
  17684. // Set key
  17685. if (state.key !== null && (result !== null || present === true)) input.leaveKey(prevKey, state.key, result);else if (prevKey !== null) input.exitKey(prevKey);
  17686. return result;
  17687. };
  17688. Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
  17689. const state = this._baseState;
  17690. if (tag === 'seq' || tag === 'set') return null;
  17691. if (tag === 'seqof' || tag === 'setof') return this._decodeList(input, tag, state.args[0], options);else if (/str$/.test(tag)) return this._decodeStr(input, tag, options);else if (tag === 'objid' && state.args) return this._decodeObjid(input, state.args[0], state.args[1], options);else if (tag === 'objid') return this._decodeObjid(input, null, null, options);else if (tag === 'gentime' || tag === 'utctime') return this._decodeTime(input, tag, options);else if (tag === 'null_') return this._decodeNull(input, options);else if (tag === 'bool') return this._decodeBool(input, options);else if (tag === 'objDesc') return this._decodeStr(input, tag, options);else if (tag === 'int' || tag === 'enum') return this._decodeInt(input, state.args && state.args[0], options);
  17692. if (state.use !== null) {
  17693. return this._getUse(state.use, input._reporterState.obj)._decode(input, options);
  17694. } else {
  17695. return input.error('unknown tag: ' + tag);
  17696. }
  17697. };
  17698. Node.prototype._getUse = function _getUse(entity, obj) {
  17699. const state = this._baseState;
  17700. // Create altered use decoder if implicit is set
  17701. state.useDecoder = this._use(entity, obj);
  17702. assert(state.useDecoder._baseState.parent === null);
  17703. state.useDecoder = state.useDecoder._baseState.children[0];
  17704. if (state.implicit !== state.useDecoder._baseState.implicit) {
  17705. state.useDecoder = state.useDecoder.clone();
  17706. state.useDecoder._baseState.implicit = state.implicit;
  17707. }
  17708. return state.useDecoder;
  17709. };
  17710. Node.prototype._decodeChoice = function decodeChoice(input, options) {
  17711. const state = this._baseState;
  17712. let result = null;
  17713. let match = false;
  17714. Object.keys(state.choice).some(function (key) {
  17715. const save = input.save();
  17716. const node = state.choice[key];
  17717. try {
  17718. const value = node._decode(input, options);
  17719. if (input.isError(value)) return false;
  17720. result = {
  17721. type: key,
  17722. value: value
  17723. };
  17724. match = true;
  17725. } catch (e) {
  17726. input.restore(save);
  17727. return false;
  17728. }
  17729. return true;
  17730. }, this);
  17731. if (!match) return input.error('Choice not matched');
  17732. return result;
  17733. };
  17734. //
  17735. // Encoding
  17736. //
  17737. Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
  17738. return new EncoderBuffer(data, this.reporter);
  17739. };
  17740. Node.prototype._encode = function encode(data, reporter, parent) {
  17741. const state = this._baseState;
  17742. if (state['default'] !== null && state['default'] === data) return;
  17743. const result = this._encodeValue(data, reporter, parent);
  17744. if (result === undefined) return;
  17745. if (this._skipDefault(result, reporter, parent)) return;
  17746. return result;
  17747. };
  17748. Node.prototype._encodeValue = function encode(data, reporter, parent) {
  17749. const state = this._baseState;
  17750. // Decode root node
  17751. if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter());
  17752. let result = null;
  17753. // Set reporter to share it with a child class
  17754. this.reporter = reporter;
  17755. // Check if data is there
  17756. if (state.optional && data === undefined) {
  17757. if (state['default'] !== null) data = state['default'];else return;
  17758. }
  17759. // Encode children first
  17760. let content = null;
  17761. let primitive = false;
  17762. if (state.any) {
  17763. // Anything that was given is translated to buffer
  17764. result = this._createEncoderBuffer(data);
  17765. } else if (state.choice) {
  17766. result = this._encodeChoice(data, reporter);
  17767. } else if (state.contains) {
  17768. content = this._getUse(state.contains, parent)._encode(data, reporter);
  17769. primitive = true;
  17770. } else if (state.children) {
  17771. content = state.children.map(function (child) {
  17772. if (child._baseState.tag === 'null_') return child._encode(null, reporter, data);
  17773. if (child._baseState.key === null) return reporter.error('Child should have a key');
  17774. const prevKey = reporter.enterKey(child._baseState.key);
  17775. if (typeof data !== 'object') return reporter.error('Child expected, but input is not object');
  17776. const res = child._encode(data[child._baseState.key], reporter, data);
  17777. reporter.leaveKey(prevKey);
  17778. return res;
  17779. }, this).filter(function (child) {
  17780. return child;
  17781. });
  17782. content = this._createEncoderBuffer(content);
  17783. } else {
  17784. if (state.tag === 'seqof' || state.tag === 'setof') {
  17785. // TODO(indutny): this should be thrown on DSL level
  17786. if (!(state.args && state.args.length === 1)) return reporter.error('Too many args for : ' + state.tag);
  17787. if (!Array.isArray(data)) return reporter.error('seqof/setof, but data is not Array');
  17788. const child = this.clone();
  17789. child._baseState.implicit = null;
  17790. content = this._createEncoderBuffer(data.map(function (item) {
  17791. const state = this._baseState;
  17792. return this._getUse(state.args[0], data)._encode(item, reporter);
  17793. }, child));
  17794. } else if (state.use !== null) {
  17795. result = this._getUse(state.use, parent)._encode(data, reporter);
  17796. } else {
  17797. content = this._encodePrimitive(state.tag, data);
  17798. primitive = true;
  17799. }
  17800. }
  17801. // Encode data itself
  17802. if (!state.any && state.choice === null) {
  17803. const tag = state.implicit !== null ? state.implicit : state.tag;
  17804. const cls = state.implicit === null ? 'universal' : 'context';
  17805. if (tag === null) {
  17806. if (state.use === null) reporter.error('Tag could be omitted only for .use()');
  17807. } else {
  17808. if (state.use === null) result = this._encodeComposite(tag, primitive, cls, content);
  17809. }
  17810. }
  17811. // Wrap in explicit
  17812. if (state.explicit !== null) result = this._encodeComposite(state.explicit, false, 'context', result);
  17813. return result;
  17814. };
  17815. Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
  17816. const state = this._baseState;
  17817. const node = state.choice[data.type];
  17818. if (!node) {
  17819. assert(false, data.type + ' not found in ' + JSON.stringify(Object.keys(state.choice)));
  17820. }
  17821. return node._encode(data.value, reporter);
  17822. };
  17823. Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
  17824. const state = this._baseState;
  17825. if (/str$/.test(tag)) return this._encodeStr(data, tag);else if (tag === 'objid' && state.args) return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);else if (tag === 'objid') return this._encodeObjid(data, null, null);else if (tag === 'gentime' || tag === 'utctime') return this._encodeTime(data, tag);else if (tag === 'null_') return this._encodeNull();else if (tag === 'int' || tag === 'enum') return this._encodeInt(data, state.args && state.reverseArgs[0]);else if (tag === 'bool') return this._encodeBool(data);else if (tag === 'objDesc') return this._encodeStr(data, tag);else throw new Error('Unsupported tag: ' + tag);
  17826. };
  17827. Node.prototype._isNumstr = function isNumstr(str) {
  17828. return /^[0-9 ]*$/.test(str);
  17829. };
  17830. Node.prototype._isPrintstr = function isPrintstr(str) {
  17831. return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str);
  17832. };
  17833. },{"../base/buffer":172,"../base/reporter":175,"minimalistic-assert":292}],175:[function(require,module,exports){
  17834. 'use strict';
  17835. const inherits = require('inherits');
  17836. function Reporter(options) {
  17837. this._reporterState = {
  17838. obj: null,
  17839. path: [],
  17840. options: options || {},
  17841. errors: []
  17842. };
  17843. }
  17844. exports.Reporter = Reporter;
  17845. Reporter.prototype.isError = function isError(obj) {
  17846. return obj instanceof ReporterError;
  17847. };
  17848. Reporter.prototype.save = function save() {
  17849. const state = this._reporterState;
  17850. return {
  17851. obj: state.obj,
  17852. pathLen: state.path.length
  17853. };
  17854. };
  17855. Reporter.prototype.restore = function restore(data) {
  17856. const state = this._reporterState;
  17857. state.obj = data.obj;
  17858. state.path = state.path.slice(0, data.pathLen);
  17859. };
  17860. Reporter.prototype.enterKey = function enterKey(key) {
  17861. return this._reporterState.path.push(key);
  17862. };
  17863. Reporter.prototype.exitKey = function exitKey(index) {
  17864. const state = this._reporterState;
  17865. state.path = state.path.slice(0, index - 1);
  17866. };
  17867. Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
  17868. const state = this._reporterState;
  17869. this.exitKey(index);
  17870. if (state.obj !== null) state.obj[key] = value;
  17871. };
  17872. Reporter.prototype.path = function path() {
  17873. return this._reporterState.path.join('/');
  17874. };
  17875. Reporter.prototype.enterObject = function enterObject() {
  17876. const state = this._reporterState;
  17877. const prev = state.obj;
  17878. state.obj = {};
  17879. return prev;
  17880. };
  17881. Reporter.prototype.leaveObject = function leaveObject(prev) {
  17882. const state = this._reporterState;
  17883. const now = state.obj;
  17884. state.obj = prev;
  17885. return now;
  17886. };
  17887. Reporter.prototype.error = function error(msg) {
  17888. let err;
  17889. const state = this._reporterState;
  17890. const inherited = msg instanceof ReporterError;
  17891. if (inherited) {
  17892. err = msg;
  17893. } else {
  17894. err = new ReporterError(state.path.map(function (elem) {
  17895. return '[' + JSON.stringify(elem) + ']';
  17896. }).join(''), msg.message || msg, msg.stack);
  17897. }
  17898. if (!state.options.partial) throw err;
  17899. if (!inherited) state.errors.push(err);
  17900. return err;
  17901. };
  17902. Reporter.prototype.wrapResult = function wrapResult(result) {
  17903. const state = this._reporterState;
  17904. if (!state.options.partial) return result;
  17905. return {
  17906. result: this.isError(result) ? null : result,
  17907. errors: state.errors
  17908. };
  17909. };
  17910. function ReporterError(path, msg) {
  17911. this.path = path;
  17912. this.rethrow(msg);
  17913. }
  17914. inherits(ReporterError, Error);
  17915. ReporterError.prototype.rethrow = function rethrow(msg) {
  17916. this.message = msg + ' at: ' + (this.path || '(shallow)');
  17917. if (Error.captureStackTrace) Error.captureStackTrace(this, ReporterError);
  17918. if (!this.stack) {
  17919. try {
  17920. // IE only adds stack when thrown
  17921. throw new Error(this.message);
  17922. } catch (e) {
  17923. this.stack = e.stack;
  17924. }
  17925. }
  17926. return this;
  17927. };
  17928. },{"inherits":279}],176:[function(require,module,exports){
  17929. 'use strict';
  17930. // Helper
  17931. function reverse(map) {
  17932. const res = {};
  17933. Object.keys(map).forEach(function (key) {
  17934. // Convert key to integer if it is stringified
  17935. if ((key | 0) == key) key = key | 0;
  17936. const value = map[key];
  17937. res[value] = key;
  17938. });
  17939. return res;
  17940. }
  17941. exports.tagClass = {
  17942. 0: 'universal',
  17943. 1: 'application',
  17944. 2: 'context',
  17945. 3: 'private'
  17946. };
  17947. exports.tagClassByName = reverse(exports.tagClass);
  17948. exports.tag = {
  17949. 0x00: 'end',
  17950. 0x01: 'bool',
  17951. 0x02: 'int',
  17952. 0x03: 'bitstr',
  17953. 0x04: 'octstr',
  17954. 0x05: 'null_',
  17955. 0x06: 'objid',
  17956. 0x07: 'objDesc',
  17957. 0x08: 'external',
  17958. 0x09: 'real',
  17959. 0x0a: 'enum',
  17960. 0x0b: 'embed',
  17961. 0x0c: 'utf8str',
  17962. 0x0d: 'relativeOid',
  17963. 0x10: 'seq',
  17964. 0x11: 'set',
  17965. 0x12: 'numstr',
  17966. 0x13: 'printstr',
  17967. 0x14: 't61str',
  17968. 0x15: 'videostr',
  17969. 0x16: 'ia5str',
  17970. 0x17: 'utctime',
  17971. 0x18: 'gentime',
  17972. 0x19: 'graphstr',
  17973. 0x1a: 'iso646str',
  17974. 0x1b: 'genstr',
  17975. 0x1c: 'unistr',
  17976. 0x1d: 'charstr',
  17977. 0x1e: 'bmpstr'
  17978. };
  17979. exports.tagByName = reverse(exports.tag);
  17980. },{}],177:[function(require,module,exports){
  17981. 'use strict';
  17982. const constants = exports;
  17983. // Helper
  17984. constants._reverse = function reverse(map) {
  17985. const res = {};
  17986. Object.keys(map).forEach(function (key) {
  17987. // Convert key to integer if it is stringified
  17988. if ((key | 0) == key) key = key | 0;
  17989. const value = map[key];
  17990. res[value] = key;
  17991. });
  17992. return res;
  17993. };
  17994. constants.der = require('./der');
  17995. },{"./der":176}],178:[function(require,module,exports){
  17996. 'use strict';
  17997. const inherits = require('inherits');
  17998. const bignum = require('bn.js');
  17999. const DecoderBuffer = require('../base/buffer').DecoderBuffer;
  18000. const Node = require('../base/node');
  18001. // Import DER constants
  18002. const der = require('../constants/der');
  18003. function DERDecoder(entity) {
  18004. this.enc = 'der';
  18005. this.name = entity.name;
  18006. this.entity = entity;
  18007. // Construct base tree
  18008. this.tree = new DERNode();
  18009. this.tree._init(entity.body);
  18010. }
  18011. module.exports = DERDecoder;
  18012. DERDecoder.prototype.decode = function decode(data, options) {
  18013. if (!DecoderBuffer.isDecoderBuffer(data)) {
  18014. data = new DecoderBuffer(data, options);
  18015. }
  18016. return this.tree._decode(data, options);
  18017. };
  18018. // Tree methods
  18019. function DERNode(parent) {
  18020. Node.call(this, 'der', parent);
  18021. }
  18022. inherits(DERNode, Node);
  18023. DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
  18024. if (buffer.isEmpty()) return false;
  18025. const state = buffer.save();
  18026. const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
  18027. if (buffer.isError(decodedTag)) return decodedTag;
  18028. buffer.restore(state);
  18029. return decodedTag.tag === tag || decodedTag.tagStr === tag || decodedTag.tagStr + 'of' === tag || any;
  18030. };
  18031. DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
  18032. const decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"');
  18033. if (buffer.isError(decodedTag)) return decodedTag;
  18034. let len = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"');
  18035. // Failure
  18036. if (buffer.isError(len)) return len;
  18037. if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + 'of' !== tag) {
  18038. return buffer.error('Failed to match tag: "' + tag + '"');
  18039. }
  18040. if (decodedTag.primitive || len !== null) return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
  18041. // Indefinite length... find END tag
  18042. const state = buffer.save();
  18043. const res = this._skipUntilEnd(buffer, 'Failed to skip indefinite length body: "' + this.tag + '"');
  18044. if (buffer.isError(res)) return res;
  18045. len = buffer.offset - state.offset;
  18046. buffer.restore(state);
  18047. return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
  18048. };
  18049. DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
  18050. for (;;) {
  18051. const tag = derDecodeTag(buffer, fail);
  18052. if (buffer.isError(tag)) return tag;
  18053. const len = derDecodeLen(buffer, tag.primitive, fail);
  18054. if (buffer.isError(len)) return len;
  18055. let res;
  18056. if (tag.primitive || len !== null) res = buffer.skip(len);else res = this._skipUntilEnd(buffer, fail);
  18057. // Failure
  18058. if (buffer.isError(res)) return res;
  18059. if (tag.tagStr === 'end') break;
  18060. }
  18061. };
  18062. DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, options) {
  18063. const result = [];
  18064. while (!buffer.isEmpty()) {
  18065. const possibleEnd = this._peekTag(buffer, 'end');
  18066. if (buffer.isError(possibleEnd)) return possibleEnd;
  18067. const res = decoder.decode(buffer, 'der', options);
  18068. if (buffer.isError(res) && possibleEnd) break;
  18069. result.push(res);
  18070. }
  18071. return result;
  18072. };
  18073. DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
  18074. if (tag === 'bitstr') {
  18075. const unused = buffer.readUInt8();
  18076. if (buffer.isError(unused)) return unused;
  18077. return {
  18078. unused: unused,
  18079. data: buffer.raw()
  18080. };
  18081. } else if (tag === 'bmpstr') {
  18082. const raw = buffer.raw();
  18083. if (raw.length % 2 === 1) return buffer.error('Decoding of string type: bmpstr length mismatch');
  18084. let str = '';
  18085. for (let i = 0; i < raw.length / 2; i++) {
  18086. str += String.fromCharCode(raw.readUInt16BE(i * 2));
  18087. }
  18088. return str;
  18089. } else if (tag === 'numstr') {
  18090. const numstr = buffer.raw().toString('ascii');
  18091. if (!this._isNumstr(numstr)) {
  18092. return buffer.error('Decoding of string type: ' + 'numstr unsupported characters');
  18093. }
  18094. return numstr;
  18095. } else if (tag === 'octstr') {
  18096. return buffer.raw();
  18097. } else if (tag === 'objDesc') {
  18098. return buffer.raw();
  18099. } else if (tag === 'printstr') {
  18100. const printstr = buffer.raw().toString('ascii');
  18101. if (!this._isPrintstr(printstr)) {
  18102. return buffer.error('Decoding of string type: ' + 'printstr unsupported characters');
  18103. }
  18104. return printstr;
  18105. } else if (/str$/.test(tag)) {
  18106. return buffer.raw().toString();
  18107. } else {
  18108. return buffer.error('Decoding of string type: ' + tag + ' unsupported');
  18109. }
  18110. };
  18111. DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
  18112. let result;
  18113. const identifiers = [];
  18114. let ident = 0;
  18115. let subident = 0;
  18116. while (!buffer.isEmpty()) {
  18117. subident = buffer.readUInt8();
  18118. ident <<= 7;
  18119. ident |= subident & 0x7f;
  18120. if ((subident & 0x80) === 0) {
  18121. identifiers.push(ident);
  18122. ident = 0;
  18123. }
  18124. }
  18125. if (subident & 0x80) identifiers.push(ident);
  18126. const first = identifiers[0] / 40 | 0;
  18127. const second = identifiers[0] % 40;
  18128. if (relative) result = identifiers;else result = [first, second].concat(identifiers.slice(1));
  18129. if (values) {
  18130. let tmp = values[result.join(' ')];
  18131. if (tmp === undefined) tmp = values[result.join('.')];
  18132. if (tmp !== undefined) result = tmp;
  18133. }
  18134. return result;
  18135. };
  18136. DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
  18137. const str = buffer.raw().toString();
  18138. let year;
  18139. let mon;
  18140. let day;
  18141. let hour;
  18142. let min;
  18143. let sec;
  18144. if (tag === 'gentime') {
  18145. year = str.slice(0, 4) | 0;
  18146. mon = str.slice(4, 6) | 0;
  18147. day = str.slice(6, 8) | 0;
  18148. hour = str.slice(8, 10) | 0;
  18149. min = str.slice(10, 12) | 0;
  18150. sec = str.slice(12, 14) | 0;
  18151. } else if (tag === 'utctime') {
  18152. year = str.slice(0, 2) | 0;
  18153. mon = str.slice(2, 4) | 0;
  18154. day = str.slice(4, 6) | 0;
  18155. hour = str.slice(6, 8) | 0;
  18156. min = str.slice(8, 10) | 0;
  18157. sec = str.slice(10, 12) | 0;
  18158. if (year < 70) year = 2000 + year;else year = 1900 + year;
  18159. } else {
  18160. return buffer.error('Decoding ' + tag + ' time is not supported yet');
  18161. }
  18162. return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
  18163. };
  18164. DERNode.prototype._decodeNull = function decodeNull() {
  18165. return null;
  18166. };
  18167. DERNode.prototype._decodeBool = function decodeBool(buffer) {
  18168. const res = buffer.readUInt8();
  18169. if (buffer.isError(res)) return res;else return res !== 0;
  18170. };
  18171. DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
  18172. // Bigint, return as it is (assume big endian)
  18173. const raw = buffer.raw();
  18174. let res = new bignum(raw);
  18175. if (values) res = values[res.toString(10)] || res;
  18176. return res;
  18177. };
  18178. DERNode.prototype._use = function use(entity, obj) {
  18179. if (typeof entity === 'function') entity = entity(obj);
  18180. return entity._getDecoder('der').tree;
  18181. };
  18182. // Utility methods
  18183. function derDecodeTag(buf, fail) {
  18184. let tag = buf.readUInt8(fail);
  18185. if (buf.isError(tag)) return tag;
  18186. const cls = der.tagClass[tag >> 6];
  18187. const primitive = (tag & 0x20) === 0;
  18188. // Multi-octet tag - load
  18189. if ((tag & 0x1f) === 0x1f) {
  18190. let oct = tag;
  18191. tag = 0;
  18192. while ((oct & 0x80) === 0x80) {
  18193. oct = buf.readUInt8(fail);
  18194. if (buf.isError(oct)) return oct;
  18195. tag <<= 7;
  18196. tag |= oct & 0x7f;
  18197. }
  18198. } else {
  18199. tag &= 0x1f;
  18200. }
  18201. const tagStr = der.tag[tag];
  18202. return {
  18203. cls: cls,
  18204. primitive: primitive,
  18205. tag: tag,
  18206. tagStr: tagStr
  18207. };
  18208. }
  18209. function derDecodeLen(buf, primitive, fail) {
  18210. let len = buf.readUInt8(fail);
  18211. if (buf.isError(len)) return len;
  18212. // Indefinite form
  18213. if (!primitive && len === 0x80) return null;
  18214. // Definite form
  18215. if ((len & 0x80) === 0) {
  18216. // Short form
  18217. return len;
  18218. }
  18219. // Long form
  18220. const num = len & 0x7f;
  18221. if (num > 4) return buf.error('length octect is too long');
  18222. len = 0;
  18223. for (let i = 0; i < num; i++) {
  18224. len <<= 8;
  18225. const j = buf.readUInt8(fail);
  18226. if (buf.isError(j)) return j;
  18227. len |= j;
  18228. }
  18229. return len;
  18230. }
  18231. },{"../base/buffer":172,"../base/node":174,"../constants/der":176,"bn.js":184,"inherits":279}],179:[function(require,module,exports){
  18232. 'use strict';
  18233. const decoders = exports;
  18234. decoders.der = require('./der');
  18235. decoders.pem = require('./pem');
  18236. },{"./der":178,"./pem":180}],180:[function(require,module,exports){
  18237. 'use strict';
  18238. const inherits = require('inherits');
  18239. const Buffer = require('safer-buffer').Buffer;
  18240. const DERDecoder = require('./der');
  18241. function PEMDecoder(entity) {
  18242. DERDecoder.call(this, entity);
  18243. this.enc = 'pem';
  18244. }
  18245. inherits(PEMDecoder, DERDecoder);
  18246. module.exports = PEMDecoder;
  18247. PEMDecoder.prototype.decode = function decode(data, options) {
  18248. const lines = data.toString().split(/[\r\n]+/g);
  18249. const label = options.label.toUpperCase();
  18250. const re = /^-----(BEGIN|END) ([^-]+)-----$/;
  18251. let start = -1;
  18252. let end = -1;
  18253. for (let i = 0; i < lines.length; i++) {
  18254. const match = lines[i].match(re);
  18255. if (match === null) continue;
  18256. if (match[2] !== label) continue;
  18257. if (start === -1) {
  18258. if (match[1] !== 'BEGIN') break;
  18259. start = i;
  18260. } else {
  18261. if (match[1] !== 'END') break;
  18262. end = i;
  18263. break;
  18264. }
  18265. }
  18266. if (start === -1 || end === -1) throw new Error('PEM section not found for: ' + label);
  18267. const base64 = lines.slice(start + 1, end).join('');
  18268. // Remove excessive symbols
  18269. base64.replace(/[^a-z0-9+/=]+/gi, '');
  18270. const input = Buffer.from(base64, 'base64');
  18271. return DERDecoder.prototype.decode.call(this, input, options);
  18272. };
  18273. },{"./der":178,"inherits":279,"safer-buffer":333}],181:[function(require,module,exports){
  18274. 'use strict';
  18275. const inherits = require('inherits');
  18276. const Buffer = require('safer-buffer').Buffer;
  18277. const Node = require('../base/node');
  18278. // Import DER constants
  18279. const der = require('../constants/der');
  18280. function DEREncoder(entity) {
  18281. this.enc = 'der';
  18282. this.name = entity.name;
  18283. this.entity = entity;
  18284. // Construct base tree
  18285. this.tree = new DERNode();
  18286. this.tree._init(entity.body);
  18287. }
  18288. module.exports = DEREncoder;
  18289. DEREncoder.prototype.encode = function encode(data, reporter) {
  18290. return this.tree._encode(data, reporter).join();
  18291. };
  18292. // Tree methods
  18293. function DERNode(parent) {
  18294. Node.call(this, 'der', parent);
  18295. }
  18296. inherits(DERNode, Node);
  18297. DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) {
  18298. const encodedTag = encodeTag(tag, primitive, cls, this.reporter);
  18299. // Short form
  18300. if (content.length < 0x80) {
  18301. const header = Buffer.alloc(2);
  18302. header[0] = encodedTag;
  18303. header[1] = content.length;
  18304. return this._createEncoderBuffer([header, content]);
  18305. }
  18306. // Long form
  18307. // Count octets required to store length
  18308. let lenOctets = 1;
  18309. for (let i = content.length; i >= 0x100; i >>= 8) lenOctets++;
  18310. const header = Buffer.alloc(1 + 1 + lenOctets);
  18311. header[0] = encodedTag;
  18312. header[1] = 0x80 | lenOctets;
  18313. for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) header[i] = j & 0xff;
  18314. return this._createEncoderBuffer([header, content]);
  18315. };
  18316. DERNode.prototype._encodeStr = function encodeStr(str, tag) {
  18317. if (tag === 'bitstr') {
  18318. return this._createEncoderBuffer([str.unused | 0, str.data]);
  18319. } else if (tag === 'bmpstr') {
  18320. const buf = Buffer.alloc(str.length * 2);
  18321. for (let i = 0; i < str.length; i++) {
  18322. buf.writeUInt16BE(str.charCodeAt(i), i * 2);
  18323. }
  18324. return this._createEncoderBuffer(buf);
  18325. } else if (tag === 'numstr') {
  18326. if (!this._isNumstr(str)) {
  18327. return this.reporter.error('Encoding of string type: numstr supports ' + 'only digits and space');
  18328. }
  18329. return this._createEncoderBuffer(str);
  18330. } else if (tag === 'printstr') {
  18331. if (!this._isPrintstr(str)) {
  18332. return this.reporter.error('Encoding of string type: printstr supports ' + 'only latin upper and lower case letters, ' + 'digits, space, apostrophe, left and rigth ' + 'parenthesis, plus sign, comma, hyphen, ' + 'dot, slash, colon, equal sign, ' + 'question mark');
  18333. }
  18334. return this._createEncoderBuffer(str);
  18335. } else if (/str$/.test(tag)) {
  18336. return this._createEncoderBuffer(str);
  18337. } else if (tag === 'objDesc') {
  18338. return this._createEncoderBuffer(str);
  18339. } else {
  18340. return this.reporter.error('Encoding of string type: ' + tag + ' unsupported');
  18341. }
  18342. };
  18343. DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
  18344. if (typeof id === 'string') {
  18345. if (!values) return this.reporter.error('string objid given, but no values map found');
  18346. if (!values.hasOwnProperty(id)) return this.reporter.error('objid not found in values map');
  18347. id = values[id].split(/[\s.]+/g);
  18348. for (let i = 0; i < id.length; i++) id[i] |= 0;
  18349. } else if (Array.isArray(id)) {
  18350. id = id.slice();
  18351. for (let i = 0; i < id.length; i++) id[i] |= 0;
  18352. }
  18353. if (!Array.isArray(id)) {
  18354. return this.reporter.error('objid() should be either array or string, ' + 'got: ' + JSON.stringify(id));
  18355. }
  18356. if (!relative) {
  18357. if (id[1] >= 40) return this.reporter.error('Second objid identifier OOB');
  18358. id.splice(0, 2, id[0] * 40 + id[1]);
  18359. }
  18360. // Count number of octets
  18361. let size = 0;
  18362. for (let i = 0; i < id.length; i++) {
  18363. let ident = id[i];
  18364. for (size++; ident >= 0x80; ident >>= 7) size++;
  18365. }
  18366. const objid = Buffer.alloc(size);
  18367. let offset = objid.length - 1;
  18368. for (let i = id.length - 1; i >= 0; i--) {
  18369. let ident = id[i];
  18370. objid[offset--] = ident & 0x7f;
  18371. while ((ident >>= 7) > 0) objid[offset--] = 0x80 | ident & 0x7f;
  18372. }
  18373. return this._createEncoderBuffer(objid);
  18374. };
  18375. function two(num) {
  18376. if (num < 10) return '0' + num;else return num;
  18377. }
  18378. DERNode.prototype._encodeTime = function encodeTime(time, tag) {
  18379. let str;
  18380. const date = new Date(time);
  18381. if (tag === 'gentime') {
  18382. str = [two(date.getUTCFullYear()), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z'].join('');
  18383. } else if (tag === 'utctime') {
  18384. str = [two(date.getUTCFullYear() % 100), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z'].join('');
  18385. } else {
  18386. this.reporter.error('Encoding ' + tag + ' time is not supported yet');
  18387. }
  18388. return this._encodeStr(str, 'octstr');
  18389. };
  18390. DERNode.prototype._encodeNull = function encodeNull() {
  18391. return this._createEncoderBuffer('');
  18392. };
  18393. DERNode.prototype._encodeInt = function encodeInt(num, values) {
  18394. if (typeof num === 'string') {
  18395. if (!values) return this.reporter.error('String int or enum given, but no values map');
  18396. if (!values.hasOwnProperty(num)) {
  18397. return this.reporter.error('Values map doesn\'t contain: ' + JSON.stringify(num));
  18398. }
  18399. num = values[num];
  18400. }
  18401. // Bignum, assume big endian
  18402. if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
  18403. const numArray = num.toArray();
  18404. if (!num.sign && numArray[0] & 0x80) {
  18405. numArray.unshift(0);
  18406. }
  18407. num = Buffer.from(numArray);
  18408. }
  18409. if (Buffer.isBuffer(num)) {
  18410. let size = num.length;
  18411. if (num.length === 0) size++;
  18412. const out = Buffer.alloc(size);
  18413. num.copy(out);
  18414. if (num.length === 0) out[0] = 0;
  18415. return this._createEncoderBuffer(out);
  18416. }
  18417. if (num < 0x80) return this._createEncoderBuffer(num);
  18418. if (num < 0x100) return this._createEncoderBuffer([0, num]);
  18419. let size = 1;
  18420. for (let i = num; i >= 0x100; i >>= 8) size++;
  18421. const out = new Array(size);
  18422. for (let i = out.length - 1; i >= 0; i--) {
  18423. out[i] = num & 0xff;
  18424. num >>= 8;
  18425. }
  18426. if (out[0] & 0x80) {
  18427. out.unshift(0);
  18428. }
  18429. return this._createEncoderBuffer(Buffer.from(out));
  18430. };
  18431. DERNode.prototype._encodeBool = function encodeBool(value) {
  18432. return this._createEncoderBuffer(value ? 0xff : 0);
  18433. };
  18434. DERNode.prototype._use = function use(entity, obj) {
  18435. if (typeof entity === 'function') entity = entity(obj);
  18436. return entity._getEncoder('der').tree;
  18437. };
  18438. DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
  18439. const state = this._baseState;
  18440. let i;
  18441. if (state['default'] === null) return false;
  18442. const data = dataBuffer.join();
  18443. if (state.defaultBuffer === undefined) state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
  18444. if (data.length !== state.defaultBuffer.length) return false;
  18445. for (i = 0; i < data.length; i++) if (data[i] !== state.defaultBuffer[i]) return false;
  18446. return true;
  18447. };
  18448. // Utility methods
  18449. function encodeTag(tag, primitive, cls, reporter) {
  18450. let res;
  18451. if (tag === 'seqof') tag = 'seq';else if (tag === 'setof') tag = 'set';
  18452. if (der.tagByName.hasOwnProperty(tag)) res = der.tagByName[tag];else if (typeof tag === 'number' && (tag | 0) === tag) res = tag;else return reporter.error('Unknown tag: ' + tag);
  18453. if (res >= 0x1f) return reporter.error('Multi-octet tag encoding unsupported');
  18454. if (!primitive) res |= 0x20;
  18455. res |= der.tagClassByName[cls || 'universal'] << 6;
  18456. return res;
  18457. }
  18458. },{"../base/node":174,"../constants/der":176,"inherits":279,"safer-buffer":333}],182:[function(require,module,exports){
  18459. 'use strict';
  18460. const encoders = exports;
  18461. encoders.der = require('./der');
  18462. encoders.pem = require('./pem');
  18463. },{"./der":181,"./pem":183}],183:[function(require,module,exports){
  18464. 'use strict';
  18465. const inherits = require('inherits');
  18466. const DEREncoder = require('./der');
  18467. function PEMEncoder(entity) {
  18468. DEREncoder.call(this, entity);
  18469. this.enc = 'pem';
  18470. }
  18471. inherits(PEMEncoder, DEREncoder);
  18472. module.exports = PEMEncoder;
  18473. PEMEncoder.prototype.encode = function encode(data, options) {
  18474. const buf = DEREncoder.prototype.encode.call(this, data);
  18475. const p = buf.toString('base64');
  18476. const out = ['-----BEGIN ' + options.label + '-----'];
  18477. for (let i = 0; i < p.length; i += 64) out.push(p.slice(i, i + 64));
  18478. out.push('-----END ' + options.label + '-----');
  18479. return out.join('\n');
  18480. };
  18481. },{"./der":181,"inherits":279}],184:[function(require,module,exports){
  18482. "use strict";
  18483. (function (module, exports) {
  18484. 'use strict';
  18485. // Utils
  18486. function assert(val, msg) {
  18487. if (!val) throw new Error(msg || 'Assertion failed');
  18488. }
  18489. // Could use `inherits` module, but don't want to move from single file
  18490. // architecture yet.
  18491. function inherits(ctor, superCtor) {
  18492. ctor.super_ = superCtor;
  18493. var TempCtor = function () {};
  18494. TempCtor.prototype = superCtor.prototype;
  18495. ctor.prototype = new TempCtor();
  18496. ctor.prototype.constructor = ctor;
  18497. }
  18498. // BN
  18499. function BN(number, base, endian) {
  18500. if (BN.isBN(number)) {
  18501. return number;
  18502. }
  18503. this.negative = 0;
  18504. this.words = null;
  18505. this.length = 0;
  18506. // Reduction context
  18507. this.red = null;
  18508. if (number !== null) {
  18509. if (base === 'le' || base === 'be') {
  18510. endian = base;
  18511. base = 10;
  18512. }
  18513. this._init(number || 0, base || 10, endian || 'be');
  18514. }
  18515. }
  18516. if (typeof module === 'object') {
  18517. module.exports = BN;
  18518. } else {
  18519. exports.BN = BN;
  18520. }
  18521. BN.BN = BN;
  18522. BN.wordSize = 26;
  18523. var Buffer;
  18524. try {
  18525. if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
  18526. Buffer = window.Buffer;
  18527. } else {
  18528. Buffer = require('buffer').Buffer;
  18529. }
  18530. } catch (e) {}
  18531. BN.isBN = function isBN(num) {
  18532. if (num instanceof BN) {
  18533. return true;
  18534. }
  18535. return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  18536. };
  18537. BN.max = function max(left, right) {
  18538. if (left.cmp(right) > 0) return left;
  18539. return right;
  18540. };
  18541. BN.min = function min(left, right) {
  18542. if (left.cmp(right) < 0) return left;
  18543. return right;
  18544. };
  18545. BN.prototype._init = function init(number, base, endian) {
  18546. if (typeof number === 'number') {
  18547. return this._initNumber(number, base, endian);
  18548. }
  18549. if (typeof number === 'object') {
  18550. return this._initArray(number, base, endian);
  18551. }
  18552. if (base === 'hex') {
  18553. base = 16;
  18554. }
  18555. assert(base === (base | 0) && base >= 2 && base <= 36);
  18556. number = number.toString().replace(/\s+/g, '');
  18557. var start = 0;
  18558. if (number[0] === '-') {
  18559. start++;
  18560. this.negative = 1;
  18561. }
  18562. if (start < number.length) {
  18563. if (base === 16) {
  18564. this._parseHex(number, start, endian);
  18565. } else {
  18566. this._parseBase(number, base, start);
  18567. if (endian === 'le') {
  18568. this._initArray(this.toArray(), base, endian);
  18569. }
  18570. }
  18571. }
  18572. };
  18573. BN.prototype._initNumber = function _initNumber(number, base, endian) {
  18574. if (number < 0) {
  18575. this.negative = 1;
  18576. number = -number;
  18577. }
  18578. if (number < 0x4000000) {
  18579. this.words = [number & 0x3ffffff];
  18580. this.length = 1;
  18581. } else if (number < 0x10000000000000) {
  18582. this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff];
  18583. this.length = 2;
  18584. } else {
  18585. assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
  18586. this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff, 1];
  18587. this.length = 3;
  18588. }
  18589. if (endian !== 'le') return;
  18590. // Reverse the bytes
  18591. this._initArray(this.toArray(), base, endian);
  18592. };
  18593. BN.prototype._initArray = function _initArray(number, base, endian) {
  18594. // Perhaps a Uint8Array
  18595. assert(typeof number.length === 'number');
  18596. if (number.length <= 0) {
  18597. this.words = [0];
  18598. this.length = 1;
  18599. return this;
  18600. }
  18601. this.length = Math.ceil(number.length / 3);
  18602. this.words = new Array(this.length);
  18603. for (var i = 0; i < this.length; i++) {
  18604. this.words[i] = 0;
  18605. }
  18606. var j, w;
  18607. var off = 0;
  18608. if (endian === 'be') {
  18609. for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
  18610. w = number[i] | number[i - 1] << 8 | number[i - 2] << 16;
  18611. this.words[j] |= w << off & 0x3ffffff;
  18612. this.words[j + 1] = w >>> 26 - off & 0x3ffffff;
  18613. off += 24;
  18614. if (off >= 26) {
  18615. off -= 26;
  18616. j++;
  18617. }
  18618. }
  18619. } else if (endian === 'le') {
  18620. for (i = 0, j = 0; i < number.length; i += 3) {
  18621. w = number[i] | number[i + 1] << 8 | number[i + 2] << 16;
  18622. this.words[j] |= w << off & 0x3ffffff;
  18623. this.words[j + 1] = w >>> 26 - off & 0x3ffffff;
  18624. off += 24;
  18625. if (off >= 26) {
  18626. off -= 26;
  18627. j++;
  18628. }
  18629. }
  18630. }
  18631. return this.strip();
  18632. };
  18633. function parseHex4Bits(string, index) {
  18634. var c = string.charCodeAt(index);
  18635. // 'A' - 'F'
  18636. if (c >= 65 && c <= 70) {
  18637. return c - 55;
  18638. // 'a' - 'f'
  18639. } else if (c >= 97 && c <= 102) {
  18640. return c - 87;
  18641. // '0' - '9'
  18642. } else {
  18643. return c - 48 & 0xf;
  18644. }
  18645. }
  18646. function parseHexByte(string, lowerBound, index) {
  18647. var r = parseHex4Bits(string, index);
  18648. if (index - 1 >= lowerBound) {
  18649. r |= parseHex4Bits(string, index - 1) << 4;
  18650. }
  18651. return r;
  18652. }
  18653. BN.prototype._parseHex = function _parseHex(number, start, endian) {
  18654. // Create possibly bigger array to ensure that it fits the number
  18655. this.length = Math.ceil((number.length - start) / 6);
  18656. this.words = new Array(this.length);
  18657. for (var i = 0; i < this.length; i++) {
  18658. this.words[i] = 0;
  18659. }
  18660. // 24-bits chunks
  18661. var off = 0;
  18662. var j = 0;
  18663. var w;
  18664. if (endian === 'be') {
  18665. for (i = number.length - 1; i >= start; i -= 2) {
  18666. w = parseHexByte(number, start, i) << off;
  18667. this.words[j] |= w & 0x3ffffff;
  18668. if (off >= 18) {
  18669. off -= 18;
  18670. j += 1;
  18671. this.words[j] |= w >>> 26;
  18672. } else {
  18673. off += 8;
  18674. }
  18675. }
  18676. } else {
  18677. var parseLength = number.length - start;
  18678. for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {
  18679. w = parseHexByte(number, start, i) << off;
  18680. this.words[j] |= w & 0x3ffffff;
  18681. if (off >= 18) {
  18682. off -= 18;
  18683. j += 1;
  18684. this.words[j] |= w >>> 26;
  18685. } else {
  18686. off += 8;
  18687. }
  18688. }
  18689. }
  18690. this.strip();
  18691. };
  18692. function parseBase(str, start, end, mul) {
  18693. var r = 0;
  18694. var len = Math.min(str.length, end);
  18695. for (var i = start; i < len; i++) {
  18696. var c = str.charCodeAt(i) - 48;
  18697. r *= mul;
  18698. // 'a'
  18699. if (c >= 49) {
  18700. r += c - 49 + 0xa;
  18701. // 'A'
  18702. } else if (c >= 17) {
  18703. r += c - 17 + 0xa;
  18704. // '0' - '9'
  18705. } else {
  18706. r += c;
  18707. }
  18708. }
  18709. return r;
  18710. }
  18711. BN.prototype._parseBase = function _parseBase(number, base, start) {
  18712. // Initialize as zero
  18713. this.words = [0];
  18714. this.length = 1;
  18715. // Find length of limb in base
  18716. for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
  18717. limbLen++;
  18718. }
  18719. limbLen--;
  18720. limbPow = limbPow / base | 0;
  18721. var total = number.length - start;
  18722. var mod = total % limbLen;
  18723. var end = Math.min(total, total - mod) + start;
  18724. var word = 0;
  18725. for (var i = start; i < end; i += limbLen) {
  18726. word = parseBase(number, i, i + limbLen, base);
  18727. this.imuln(limbPow);
  18728. if (this.words[0] + word < 0x4000000) {
  18729. this.words[0] += word;
  18730. } else {
  18731. this._iaddn(word);
  18732. }
  18733. }
  18734. if (mod !== 0) {
  18735. var pow = 1;
  18736. word = parseBase(number, i, number.length, base);
  18737. for (i = 0; i < mod; i++) {
  18738. pow *= base;
  18739. }
  18740. this.imuln(pow);
  18741. if (this.words[0] + word < 0x4000000) {
  18742. this.words[0] += word;
  18743. } else {
  18744. this._iaddn(word);
  18745. }
  18746. }
  18747. this.strip();
  18748. };
  18749. BN.prototype.copy = function copy(dest) {
  18750. dest.words = new Array(this.length);
  18751. for (var i = 0; i < this.length; i++) {
  18752. dest.words[i] = this.words[i];
  18753. }
  18754. dest.length = this.length;
  18755. dest.negative = this.negative;
  18756. dest.red = this.red;
  18757. };
  18758. BN.prototype.clone = function clone() {
  18759. var r = new BN(null);
  18760. this.copy(r);
  18761. return r;
  18762. };
  18763. BN.prototype._expand = function _expand(size) {
  18764. while (this.length < size) {
  18765. this.words[this.length++] = 0;
  18766. }
  18767. return this;
  18768. };
  18769. // Remove leading `0` from `this`
  18770. BN.prototype.strip = function strip() {
  18771. while (this.length > 1 && this.words[this.length - 1] === 0) {
  18772. this.length--;
  18773. }
  18774. return this._normSign();
  18775. };
  18776. BN.prototype._normSign = function _normSign() {
  18777. // -0 = 0
  18778. if (this.length === 1 && this.words[0] === 0) {
  18779. this.negative = 0;
  18780. }
  18781. return this;
  18782. };
  18783. BN.prototype.inspect = function inspect() {
  18784. return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  18785. };
  18786. /*
  18787. var zeros = [];
  18788. var groupSizes = [];
  18789. var groupBases = [];
  18790. var s = '';
  18791. var i = -1;
  18792. while (++i < BN.wordSize) {
  18793. zeros[i] = s;
  18794. s += '0';
  18795. }
  18796. groupSizes[0] = 0;
  18797. groupSizes[1] = 0;
  18798. groupBases[0] = 0;
  18799. groupBases[1] = 0;
  18800. var base = 2 - 1;
  18801. while (++base < 36 + 1) {
  18802. var groupSize = 0;
  18803. var groupBase = 1;
  18804. while (groupBase < (1 << BN.wordSize) / base) {
  18805. groupBase *= base;
  18806. groupSize += 1;
  18807. }
  18808. groupSizes[base] = groupSize;
  18809. groupBases[base] = groupBase;
  18810. }
  18811. */
  18812. var zeros = ['', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000'];
  18813. var groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5];
  18814. var groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176];
  18815. BN.prototype.toString = function toString(base, padding) {
  18816. base = base || 10;
  18817. padding = padding | 0 || 1;
  18818. var out;
  18819. if (base === 16 || base === 'hex') {
  18820. out = '';
  18821. var off = 0;
  18822. var carry = 0;
  18823. for (var i = 0; i < this.length; i++) {
  18824. var w = this.words[i];
  18825. var word = ((w << off | carry) & 0xffffff).toString(16);
  18826. carry = w >>> 24 - off & 0xffffff;
  18827. if (carry !== 0 || i !== this.length - 1) {
  18828. out = zeros[6 - word.length] + word + out;
  18829. } else {
  18830. out = word + out;
  18831. }
  18832. off += 2;
  18833. if (off >= 26) {
  18834. off -= 26;
  18835. i--;
  18836. }
  18837. }
  18838. if (carry !== 0) {
  18839. out = carry.toString(16) + out;
  18840. }
  18841. while (out.length % padding !== 0) {
  18842. out = '0' + out;
  18843. }
  18844. if (this.negative !== 0) {
  18845. out = '-' + out;
  18846. }
  18847. return out;
  18848. }
  18849. if (base === (base | 0) && base >= 2 && base <= 36) {
  18850. // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
  18851. var groupSize = groupSizes[base];
  18852. // var groupBase = Math.pow(base, groupSize);
  18853. var groupBase = groupBases[base];
  18854. out = '';
  18855. var c = this.clone();
  18856. c.negative = 0;
  18857. while (!c.isZero()) {
  18858. var r = c.modn(groupBase).toString(base);
  18859. c = c.idivn(groupBase);
  18860. if (!c.isZero()) {
  18861. out = zeros[groupSize - r.length] + r + out;
  18862. } else {
  18863. out = r + out;
  18864. }
  18865. }
  18866. if (this.isZero()) {
  18867. out = '0' + out;
  18868. }
  18869. while (out.length % padding !== 0) {
  18870. out = '0' + out;
  18871. }
  18872. if (this.negative !== 0) {
  18873. out = '-' + out;
  18874. }
  18875. return out;
  18876. }
  18877. assert(false, 'Base should be between 2 and 36');
  18878. };
  18879. BN.prototype.toNumber = function toNumber() {
  18880. var ret = this.words[0];
  18881. if (this.length === 2) {
  18882. ret += this.words[1] * 0x4000000;
  18883. } else if (this.length === 3 && this.words[2] === 0x01) {
  18884. // NOTE: at this stage it is known that the top bit is set
  18885. ret += 0x10000000000000 + this.words[1] * 0x4000000;
  18886. } else if (this.length > 2) {
  18887. assert(false, 'Number can only safely store up to 53 bits');
  18888. }
  18889. return this.negative !== 0 ? -ret : ret;
  18890. };
  18891. BN.prototype.toJSON = function toJSON() {
  18892. return this.toString(16);
  18893. };
  18894. BN.prototype.toBuffer = function toBuffer(endian, length) {
  18895. assert(typeof Buffer !== 'undefined');
  18896. return this.toArrayLike(Buffer, endian, length);
  18897. };
  18898. BN.prototype.toArray = function toArray(endian, length) {
  18899. return this.toArrayLike(Array, endian, length);
  18900. };
  18901. BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) {
  18902. var byteLength = this.byteLength();
  18903. var reqLength = length || Math.max(1, byteLength);
  18904. assert(byteLength <= reqLength, 'byte array longer than desired length');
  18905. assert(reqLength > 0, 'Requested array length <= 0');
  18906. this.strip();
  18907. var littleEndian = endian === 'le';
  18908. var res = new ArrayType(reqLength);
  18909. var b, i;
  18910. var q = this.clone();
  18911. if (!littleEndian) {
  18912. // Assume big-endian
  18913. for (i = 0; i < reqLength - byteLength; i++) {
  18914. res[i] = 0;
  18915. }
  18916. for (i = 0; !q.isZero(); i++) {
  18917. b = q.andln(0xff);
  18918. q.iushrn(8);
  18919. res[reqLength - i - 1] = b;
  18920. }
  18921. } else {
  18922. for (i = 0; !q.isZero(); i++) {
  18923. b = q.andln(0xff);
  18924. q.iushrn(8);
  18925. res[i] = b;
  18926. }
  18927. for (; i < reqLength; i++) {
  18928. res[i] = 0;
  18929. }
  18930. }
  18931. return res;
  18932. };
  18933. if (Math.clz32) {
  18934. BN.prototype._countBits = function _countBits(w) {
  18935. return 32 - Math.clz32(w);
  18936. };
  18937. } else {
  18938. BN.prototype._countBits = function _countBits(w) {
  18939. var t = w;
  18940. var r = 0;
  18941. if (t >= 0x1000) {
  18942. r += 13;
  18943. t >>>= 13;
  18944. }
  18945. if (t >= 0x40) {
  18946. r += 7;
  18947. t >>>= 7;
  18948. }
  18949. if (t >= 0x8) {
  18950. r += 4;
  18951. t >>>= 4;
  18952. }
  18953. if (t >= 0x02) {
  18954. r += 2;
  18955. t >>>= 2;
  18956. }
  18957. return r + t;
  18958. };
  18959. }
  18960. BN.prototype._zeroBits = function _zeroBits(w) {
  18961. // Short-cut
  18962. if (w === 0) return 26;
  18963. var t = w;
  18964. var r = 0;
  18965. if ((t & 0x1fff) === 0) {
  18966. r += 13;
  18967. t >>>= 13;
  18968. }
  18969. if ((t & 0x7f) === 0) {
  18970. r += 7;
  18971. t >>>= 7;
  18972. }
  18973. if ((t & 0xf) === 0) {
  18974. r += 4;
  18975. t >>>= 4;
  18976. }
  18977. if ((t & 0x3) === 0) {
  18978. r += 2;
  18979. t >>>= 2;
  18980. }
  18981. if ((t & 0x1) === 0) {
  18982. r++;
  18983. }
  18984. return r;
  18985. };
  18986. // Return number of used bits in a BN
  18987. BN.prototype.bitLength = function bitLength() {
  18988. var w = this.words[this.length - 1];
  18989. var hi = this._countBits(w);
  18990. return (this.length - 1) * 26 + hi;
  18991. };
  18992. function toBitArray(num) {
  18993. var w = new Array(num.bitLength());
  18994. for (var bit = 0; bit < w.length; bit++) {
  18995. var off = bit / 26 | 0;
  18996. var wbit = bit % 26;
  18997. w[bit] = (num.words[off] & 1 << wbit) >>> wbit;
  18998. }
  18999. return w;
  19000. }
  19001. // Number of trailing zero bits
  19002. BN.prototype.zeroBits = function zeroBits() {
  19003. if (this.isZero()) return 0;
  19004. var r = 0;
  19005. for (var i = 0; i < this.length; i++) {
  19006. var b = this._zeroBits(this.words[i]);
  19007. r += b;
  19008. if (b !== 26) break;
  19009. }
  19010. return r;
  19011. };
  19012. BN.prototype.byteLength = function byteLength() {
  19013. return Math.ceil(this.bitLength() / 8);
  19014. };
  19015. BN.prototype.toTwos = function toTwos(width) {
  19016. if (this.negative !== 0) {
  19017. return this.abs().inotn(width).iaddn(1);
  19018. }
  19019. return this.clone();
  19020. };
  19021. BN.prototype.fromTwos = function fromTwos(width) {
  19022. if (this.testn(width - 1)) {
  19023. return this.notn(width).iaddn(1).ineg();
  19024. }
  19025. return this.clone();
  19026. };
  19027. BN.prototype.isNeg = function isNeg() {
  19028. return this.negative !== 0;
  19029. };
  19030. // Return negative clone of `this`
  19031. BN.prototype.neg = function neg() {
  19032. return this.clone().ineg();
  19033. };
  19034. BN.prototype.ineg = function ineg() {
  19035. if (!this.isZero()) {
  19036. this.negative ^= 1;
  19037. }
  19038. return this;
  19039. };
  19040. // Or `num` with `this` in-place
  19041. BN.prototype.iuor = function iuor(num) {
  19042. while (this.length < num.length) {
  19043. this.words[this.length++] = 0;
  19044. }
  19045. for (var i = 0; i < num.length; i++) {
  19046. this.words[i] = this.words[i] | num.words[i];
  19047. }
  19048. return this.strip();
  19049. };
  19050. BN.prototype.ior = function ior(num) {
  19051. assert((this.negative | num.negative) === 0);
  19052. return this.iuor(num);
  19053. };
  19054. // Or `num` with `this`
  19055. BN.prototype.or = function or(num) {
  19056. if (this.length > num.length) return this.clone().ior(num);
  19057. return num.clone().ior(this);
  19058. };
  19059. BN.prototype.uor = function uor(num) {
  19060. if (this.length > num.length) return this.clone().iuor(num);
  19061. return num.clone().iuor(this);
  19062. };
  19063. // And `num` with `this` in-place
  19064. BN.prototype.iuand = function iuand(num) {
  19065. // b = min-length(num, this)
  19066. var b;
  19067. if (this.length > num.length) {
  19068. b = num;
  19069. } else {
  19070. b = this;
  19071. }
  19072. for (var i = 0; i < b.length; i++) {
  19073. this.words[i] = this.words[i] & num.words[i];
  19074. }
  19075. this.length = b.length;
  19076. return this.strip();
  19077. };
  19078. BN.prototype.iand = function iand(num) {
  19079. assert((this.negative | num.negative) === 0);
  19080. return this.iuand(num);
  19081. };
  19082. // And `num` with `this`
  19083. BN.prototype.and = function and(num) {
  19084. if (this.length > num.length) return this.clone().iand(num);
  19085. return num.clone().iand(this);
  19086. };
  19087. BN.prototype.uand = function uand(num) {
  19088. if (this.length > num.length) return this.clone().iuand(num);
  19089. return num.clone().iuand(this);
  19090. };
  19091. // Xor `num` with `this` in-place
  19092. BN.prototype.iuxor = function iuxor(num) {
  19093. // a.length > b.length
  19094. var a;
  19095. var b;
  19096. if (this.length > num.length) {
  19097. a = this;
  19098. b = num;
  19099. } else {
  19100. a = num;
  19101. b = this;
  19102. }
  19103. for (var i = 0; i < b.length; i++) {
  19104. this.words[i] = a.words[i] ^ b.words[i];
  19105. }
  19106. if (this !== a) {
  19107. for (; i < a.length; i++) {
  19108. this.words[i] = a.words[i];
  19109. }
  19110. }
  19111. this.length = a.length;
  19112. return this.strip();
  19113. };
  19114. BN.prototype.ixor = function ixor(num) {
  19115. assert((this.negative | num.negative) === 0);
  19116. return this.iuxor(num);
  19117. };
  19118. // Xor `num` with `this`
  19119. BN.prototype.xor = function xor(num) {
  19120. if (this.length > num.length) return this.clone().ixor(num);
  19121. return num.clone().ixor(this);
  19122. };
  19123. BN.prototype.uxor = function uxor(num) {
  19124. if (this.length > num.length) return this.clone().iuxor(num);
  19125. return num.clone().iuxor(this);
  19126. };
  19127. // Not ``this`` with ``width`` bitwidth
  19128. BN.prototype.inotn = function inotn(width) {
  19129. assert(typeof width === 'number' && width >= 0);
  19130. var bytesNeeded = Math.ceil(width / 26) | 0;
  19131. var bitsLeft = width % 26;
  19132. // Extend the buffer with leading zeroes
  19133. this._expand(bytesNeeded);
  19134. if (bitsLeft > 0) {
  19135. bytesNeeded--;
  19136. }
  19137. // Handle complete words
  19138. for (var i = 0; i < bytesNeeded; i++) {
  19139. this.words[i] = ~this.words[i] & 0x3ffffff;
  19140. }
  19141. // Handle the residue
  19142. if (bitsLeft > 0) {
  19143. this.words[i] = ~this.words[i] & 0x3ffffff >> 26 - bitsLeft;
  19144. }
  19145. // And remove leading zeroes
  19146. return this.strip();
  19147. };
  19148. BN.prototype.notn = function notn(width) {
  19149. return this.clone().inotn(width);
  19150. };
  19151. // Set `bit` of `this`
  19152. BN.prototype.setn = function setn(bit, val) {
  19153. assert(typeof bit === 'number' && bit >= 0);
  19154. var off = bit / 26 | 0;
  19155. var wbit = bit % 26;
  19156. this._expand(off + 1);
  19157. if (val) {
  19158. this.words[off] = this.words[off] | 1 << wbit;
  19159. } else {
  19160. this.words[off] = this.words[off] & ~(1 << wbit);
  19161. }
  19162. return this.strip();
  19163. };
  19164. // Add `num` to `this` in-place
  19165. BN.prototype.iadd = function iadd(num) {
  19166. var r;
  19167. // negative + positive
  19168. if (this.negative !== 0 && num.negative === 0) {
  19169. this.negative = 0;
  19170. r = this.isub(num);
  19171. this.negative ^= 1;
  19172. return this._normSign();
  19173. // positive + negative
  19174. } else if (this.negative === 0 && num.negative !== 0) {
  19175. num.negative = 0;
  19176. r = this.isub(num);
  19177. num.negative = 1;
  19178. return r._normSign();
  19179. }
  19180. // a.length > b.length
  19181. var a, b;
  19182. if (this.length > num.length) {
  19183. a = this;
  19184. b = num;
  19185. } else {
  19186. a = num;
  19187. b = this;
  19188. }
  19189. var carry = 0;
  19190. for (var i = 0; i < b.length; i++) {
  19191. r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
  19192. this.words[i] = r & 0x3ffffff;
  19193. carry = r >>> 26;
  19194. }
  19195. for (; carry !== 0 && i < a.length; i++) {
  19196. r = (a.words[i] | 0) + carry;
  19197. this.words[i] = r & 0x3ffffff;
  19198. carry = r >>> 26;
  19199. }
  19200. this.length = a.length;
  19201. if (carry !== 0) {
  19202. this.words[this.length] = carry;
  19203. this.length++;
  19204. // Copy the rest of the words
  19205. } else if (a !== this) {
  19206. for (; i < a.length; i++) {
  19207. this.words[i] = a.words[i];
  19208. }
  19209. }
  19210. return this;
  19211. };
  19212. // Add `num` to `this`
  19213. BN.prototype.add = function add(num) {
  19214. var res;
  19215. if (num.negative !== 0 && this.negative === 0) {
  19216. num.negative = 0;
  19217. res = this.sub(num);
  19218. num.negative ^= 1;
  19219. return res;
  19220. } else if (num.negative === 0 && this.negative !== 0) {
  19221. this.negative = 0;
  19222. res = num.sub(this);
  19223. this.negative = 1;
  19224. return res;
  19225. }
  19226. if (this.length > num.length) return this.clone().iadd(num);
  19227. return num.clone().iadd(this);
  19228. };
  19229. // Subtract `num` from `this` in-place
  19230. BN.prototype.isub = function isub(num) {
  19231. // this - (-num) = this + num
  19232. if (num.negative !== 0) {
  19233. num.negative = 0;
  19234. var r = this.iadd(num);
  19235. num.negative = 1;
  19236. return r._normSign();
  19237. // -this - num = -(this + num)
  19238. } else if (this.negative !== 0) {
  19239. this.negative = 0;
  19240. this.iadd(num);
  19241. this.negative = 1;
  19242. return this._normSign();
  19243. }
  19244. // At this point both numbers are positive
  19245. var cmp = this.cmp(num);
  19246. // Optimization - zeroify
  19247. if (cmp === 0) {
  19248. this.negative = 0;
  19249. this.length = 1;
  19250. this.words[0] = 0;
  19251. return this;
  19252. }
  19253. // a > b
  19254. var a, b;
  19255. if (cmp > 0) {
  19256. a = this;
  19257. b = num;
  19258. } else {
  19259. a = num;
  19260. b = this;
  19261. }
  19262. var carry = 0;
  19263. for (var i = 0; i < b.length; i++) {
  19264. r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
  19265. carry = r >> 26;
  19266. this.words[i] = r & 0x3ffffff;
  19267. }
  19268. for (; carry !== 0 && i < a.length; i++) {
  19269. r = (a.words[i] | 0) + carry;
  19270. carry = r >> 26;
  19271. this.words[i] = r & 0x3ffffff;
  19272. }
  19273. // Copy rest of the words
  19274. if (carry === 0 && i < a.length && a !== this) {
  19275. for (; i < a.length; i++) {
  19276. this.words[i] = a.words[i];
  19277. }
  19278. }
  19279. this.length = Math.max(this.length, i);
  19280. if (a !== this) {
  19281. this.negative = 1;
  19282. }
  19283. return this.strip();
  19284. };
  19285. // Subtract `num` from `this`
  19286. BN.prototype.sub = function sub(num) {
  19287. return this.clone().isub(num);
  19288. };
  19289. function smallMulTo(self, num, out) {
  19290. out.negative = num.negative ^ self.negative;
  19291. var len = self.length + num.length | 0;
  19292. out.length = len;
  19293. len = len - 1 | 0;
  19294. // Peel one iteration (compiler can't do it, because of code complexity)
  19295. var a = self.words[0] | 0;
  19296. var b = num.words[0] | 0;
  19297. var r = a * b;
  19298. var lo = r & 0x3ffffff;
  19299. var carry = r / 0x4000000 | 0;
  19300. out.words[0] = lo;
  19301. for (var k = 1; k < len; k++) {
  19302. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  19303. // note that ncarry could be >= 0x3ffffff
  19304. var ncarry = carry >>> 26;
  19305. var rword = carry & 0x3ffffff;
  19306. var maxJ = Math.min(k, num.length - 1);
  19307. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  19308. var i = k - j | 0;
  19309. a = self.words[i] | 0;
  19310. b = num.words[j] | 0;
  19311. r = a * b + rword;
  19312. ncarry += r / 0x4000000 | 0;
  19313. rword = r & 0x3ffffff;
  19314. }
  19315. out.words[k] = rword | 0;
  19316. carry = ncarry | 0;
  19317. }
  19318. if (carry !== 0) {
  19319. out.words[k] = carry | 0;
  19320. } else {
  19321. out.length--;
  19322. }
  19323. return out.strip();
  19324. }
  19325. // TODO(indutny): it may be reasonable to omit it for users who don't need
  19326. // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  19327. // multiplication (like elliptic secp256k1).
  19328. var comb10MulTo = function comb10MulTo(self, num, out) {
  19329. var a = self.words;
  19330. var b = num.words;
  19331. var o = out.words;
  19332. var c = 0;
  19333. var lo;
  19334. var mid;
  19335. var hi;
  19336. var a0 = a[0] | 0;
  19337. var al0 = a0 & 0x1fff;
  19338. var ah0 = a0 >>> 13;
  19339. var a1 = a[1] | 0;
  19340. var al1 = a1 & 0x1fff;
  19341. var ah1 = a1 >>> 13;
  19342. var a2 = a[2] | 0;
  19343. var al2 = a2 & 0x1fff;
  19344. var ah2 = a2 >>> 13;
  19345. var a3 = a[3] | 0;
  19346. var al3 = a3 & 0x1fff;
  19347. var ah3 = a3 >>> 13;
  19348. var a4 = a[4] | 0;
  19349. var al4 = a4 & 0x1fff;
  19350. var ah4 = a4 >>> 13;
  19351. var a5 = a[5] | 0;
  19352. var al5 = a5 & 0x1fff;
  19353. var ah5 = a5 >>> 13;
  19354. var a6 = a[6] | 0;
  19355. var al6 = a6 & 0x1fff;
  19356. var ah6 = a6 >>> 13;
  19357. var a7 = a[7] | 0;
  19358. var al7 = a7 & 0x1fff;
  19359. var ah7 = a7 >>> 13;
  19360. var a8 = a[8] | 0;
  19361. var al8 = a8 & 0x1fff;
  19362. var ah8 = a8 >>> 13;
  19363. var a9 = a[9] | 0;
  19364. var al9 = a9 & 0x1fff;
  19365. var ah9 = a9 >>> 13;
  19366. var b0 = b[0] | 0;
  19367. var bl0 = b0 & 0x1fff;
  19368. var bh0 = b0 >>> 13;
  19369. var b1 = b[1] | 0;
  19370. var bl1 = b1 & 0x1fff;
  19371. var bh1 = b1 >>> 13;
  19372. var b2 = b[2] | 0;
  19373. var bl2 = b2 & 0x1fff;
  19374. var bh2 = b2 >>> 13;
  19375. var b3 = b[3] | 0;
  19376. var bl3 = b3 & 0x1fff;
  19377. var bh3 = b3 >>> 13;
  19378. var b4 = b[4] | 0;
  19379. var bl4 = b4 & 0x1fff;
  19380. var bh4 = b4 >>> 13;
  19381. var b5 = b[5] | 0;
  19382. var bl5 = b5 & 0x1fff;
  19383. var bh5 = b5 >>> 13;
  19384. var b6 = b[6] | 0;
  19385. var bl6 = b6 & 0x1fff;
  19386. var bh6 = b6 >>> 13;
  19387. var b7 = b[7] | 0;
  19388. var bl7 = b7 & 0x1fff;
  19389. var bh7 = b7 >>> 13;
  19390. var b8 = b[8] | 0;
  19391. var bl8 = b8 & 0x1fff;
  19392. var bh8 = b8 >>> 13;
  19393. var b9 = b[9] | 0;
  19394. var bl9 = b9 & 0x1fff;
  19395. var bh9 = b9 >>> 13;
  19396. out.negative = self.negative ^ num.negative;
  19397. out.length = 19;
  19398. /* k = 0 */
  19399. lo = Math.imul(al0, bl0);
  19400. mid = Math.imul(al0, bh0);
  19401. mid = mid + Math.imul(ah0, bl0) | 0;
  19402. hi = Math.imul(ah0, bh0);
  19403. var w0 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19404. c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0;
  19405. w0 &= 0x3ffffff;
  19406. /* k = 1 */
  19407. lo = Math.imul(al1, bl0);
  19408. mid = Math.imul(al1, bh0);
  19409. mid = mid + Math.imul(ah1, bl0) | 0;
  19410. hi = Math.imul(ah1, bh0);
  19411. lo = lo + Math.imul(al0, bl1) | 0;
  19412. mid = mid + Math.imul(al0, bh1) | 0;
  19413. mid = mid + Math.imul(ah0, bl1) | 0;
  19414. hi = hi + Math.imul(ah0, bh1) | 0;
  19415. var w1 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19416. c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0;
  19417. w1 &= 0x3ffffff;
  19418. /* k = 2 */
  19419. lo = Math.imul(al2, bl0);
  19420. mid = Math.imul(al2, bh0);
  19421. mid = mid + Math.imul(ah2, bl0) | 0;
  19422. hi = Math.imul(ah2, bh0);
  19423. lo = lo + Math.imul(al1, bl1) | 0;
  19424. mid = mid + Math.imul(al1, bh1) | 0;
  19425. mid = mid + Math.imul(ah1, bl1) | 0;
  19426. hi = hi + Math.imul(ah1, bh1) | 0;
  19427. lo = lo + Math.imul(al0, bl2) | 0;
  19428. mid = mid + Math.imul(al0, bh2) | 0;
  19429. mid = mid + Math.imul(ah0, bl2) | 0;
  19430. hi = hi + Math.imul(ah0, bh2) | 0;
  19431. var w2 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19432. c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0;
  19433. w2 &= 0x3ffffff;
  19434. /* k = 3 */
  19435. lo = Math.imul(al3, bl0);
  19436. mid = Math.imul(al3, bh0);
  19437. mid = mid + Math.imul(ah3, bl0) | 0;
  19438. hi = Math.imul(ah3, bh0);
  19439. lo = lo + Math.imul(al2, bl1) | 0;
  19440. mid = mid + Math.imul(al2, bh1) | 0;
  19441. mid = mid + Math.imul(ah2, bl1) | 0;
  19442. hi = hi + Math.imul(ah2, bh1) | 0;
  19443. lo = lo + Math.imul(al1, bl2) | 0;
  19444. mid = mid + Math.imul(al1, bh2) | 0;
  19445. mid = mid + Math.imul(ah1, bl2) | 0;
  19446. hi = hi + Math.imul(ah1, bh2) | 0;
  19447. lo = lo + Math.imul(al0, bl3) | 0;
  19448. mid = mid + Math.imul(al0, bh3) | 0;
  19449. mid = mid + Math.imul(ah0, bl3) | 0;
  19450. hi = hi + Math.imul(ah0, bh3) | 0;
  19451. var w3 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19452. c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0;
  19453. w3 &= 0x3ffffff;
  19454. /* k = 4 */
  19455. lo = Math.imul(al4, bl0);
  19456. mid = Math.imul(al4, bh0);
  19457. mid = mid + Math.imul(ah4, bl0) | 0;
  19458. hi = Math.imul(ah4, bh0);
  19459. lo = lo + Math.imul(al3, bl1) | 0;
  19460. mid = mid + Math.imul(al3, bh1) | 0;
  19461. mid = mid + Math.imul(ah3, bl1) | 0;
  19462. hi = hi + Math.imul(ah3, bh1) | 0;
  19463. lo = lo + Math.imul(al2, bl2) | 0;
  19464. mid = mid + Math.imul(al2, bh2) | 0;
  19465. mid = mid + Math.imul(ah2, bl2) | 0;
  19466. hi = hi + Math.imul(ah2, bh2) | 0;
  19467. lo = lo + Math.imul(al1, bl3) | 0;
  19468. mid = mid + Math.imul(al1, bh3) | 0;
  19469. mid = mid + Math.imul(ah1, bl3) | 0;
  19470. hi = hi + Math.imul(ah1, bh3) | 0;
  19471. lo = lo + Math.imul(al0, bl4) | 0;
  19472. mid = mid + Math.imul(al0, bh4) | 0;
  19473. mid = mid + Math.imul(ah0, bl4) | 0;
  19474. hi = hi + Math.imul(ah0, bh4) | 0;
  19475. var w4 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19476. c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0;
  19477. w4 &= 0x3ffffff;
  19478. /* k = 5 */
  19479. lo = Math.imul(al5, bl0);
  19480. mid = Math.imul(al5, bh0);
  19481. mid = mid + Math.imul(ah5, bl0) | 0;
  19482. hi = Math.imul(ah5, bh0);
  19483. lo = lo + Math.imul(al4, bl1) | 0;
  19484. mid = mid + Math.imul(al4, bh1) | 0;
  19485. mid = mid + Math.imul(ah4, bl1) | 0;
  19486. hi = hi + Math.imul(ah4, bh1) | 0;
  19487. lo = lo + Math.imul(al3, bl2) | 0;
  19488. mid = mid + Math.imul(al3, bh2) | 0;
  19489. mid = mid + Math.imul(ah3, bl2) | 0;
  19490. hi = hi + Math.imul(ah3, bh2) | 0;
  19491. lo = lo + Math.imul(al2, bl3) | 0;
  19492. mid = mid + Math.imul(al2, bh3) | 0;
  19493. mid = mid + Math.imul(ah2, bl3) | 0;
  19494. hi = hi + Math.imul(ah2, bh3) | 0;
  19495. lo = lo + Math.imul(al1, bl4) | 0;
  19496. mid = mid + Math.imul(al1, bh4) | 0;
  19497. mid = mid + Math.imul(ah1, bl4) | 0;
  19498. hi = hi + Math.imul(ah1, bh4) | 0;
  19499. lo = lo + Math.imul(al0, bl5) | 0;
  19500. mid = mid + Math.imul(al0, bh5) | 0;
  19501. mid = mid + Math.imul(ah0, bl5) | 0;
  19502. hi = hi + Math.imul(ah0, bh5) | 0;
  19503. var w5 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19504. c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0;
  19505. w5 &= 0x3ffffff;
  19506. /* k = 6 */
  19507. lo = Math.imul(al6, bl0);
  19508. mid = Math.imul(al6, bh0);
  19509. mid = mid + Math.imul(ah6, bl0) | 0;
  19510. hi = Math.imul(ah6, bh0);
  19511. lo = lo + Math.imul(al5, bl1) | 0;
  19512. mid = mid + Math.imul(al5, bh1) | 0;
  19513. mid = mid + Math.imul(ah5, bl1) | 0;
  19514. hi = hi + Math.imul(ah5, bh1) | 0;
  19515. lo = lo + Math.imul(al4, bl2) | 0;
  19516. mid = mid + Math.imul(al4, bh2) | 0;
  19517. mid = mid + Math.imul(ah4, bl2) | 0;
  19518. hi = hi + Math.imul(ah4, bh2) | 0;
  19519. lo = lo + Math.imul(al3, bl3) | 0;
  19520. mid = mid + Math.imul(al3, bh3) | 0;
  19521. mid = mid + Math.imul(ah3, bl3) | 0;
  19522. hi = hi + Math.imul(ah3, bh3) | 0;
  19523. lo = lo + Math.imul(al2, bl4) | 0;
  19524. mid = mid + Math.imul(al2, bh4) | 0;
  19525. mid = mid + Math.imul(ah2, bl4) | 0;
  19526. hi = hi + Math.imul(ah2, bh4) | 0;
  19527. lo = lo + Math.imul(al1, bl5) | 0;
  19528. mid = mid + Math.imul(al1, bh5) | 0;
  19529. mid = mid + Math.imul(ah1, bl5) | 0;
  19530. hi = hi + Math.imul(ah1, bh5) | 0;
  19531. lo = lo + Math.imul(al0, bl6) | 0;
  19532. mid = mid + Math.imul(al0, bh6) | 0;
  19533. mid = mid + Math.imul(ah0, bl6) | 0;
  19534. hi = hi + Math.imul(ah0, bh6) | 0;
  19535. var w6 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19536. c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0;
  19537. w6 &= 0x3ffffff;
  19538. /* k = 7 */
  19539. lo = Math.imul(al7, bl0);
  19540. mid = Math.imul(al7, bh0);
  19541. mid = mid + Math.imul(ah7, bl0) | 0;
  19542. hi = Math.imul(ah7, bh0);
  19543. lo = lo + Math.imul(al6, bl1) | 0;
  19544. mid = mid + Math.imul(al6, bh1) | 0;
  19545. mid = mid + Math.imul(ah6, bl1) | 0;
  19546. hi = hi + Math.imul(ah6, bh1) | 0;
  19547. lo = lo + Math.imul(al5, bl2) | 0;
  19548. mid = mid + Math.imul(al5, bh2) | 0;
  19549. mid = mid + Math.imul(ah5, bl2) | 0;
  19550. hi = hi + Math.imul(ah5, bh2) | 0;
  19551. lo = lo + Math.imul(al4, bl3) | 0;
  19552. mid = mid + Math.imul(al4, bh3) | 0;
  19553. mid = mid + Math.imul(ah4, bl3) | 0;
  19554. hi = hi + Math.imul(ah4, bh3) | 0;
  19555. lo = lo + Math.imul(al3, bl4) | 0;
  19556. mid = mid + Math.imul(al3, bh4) | 0;
  19557. mid = mid + Math.imul(ah3, bl4) | 0;
  19558. hi = hi + Math.imul(ah3, bh4) | 0;
  19559. lo = lo + Math.imul(al2, bl5) | 0;
  19560. mid = mid + Math.imul(al2, bh5) | 0;
  19561. mid = mid + Math.imul(ah2, bl5) | 0;
  19562. hi = hi + Math.imul(ah2, bh5) | 0;
  19563. lo = lo + Math.imul(al1, bl6) | 0;
  19564. mid = mid + Math.imul(al1, bh6) | 0;
  19565. mid = mid + Math.imul(ah1, bl6) | 0;
  19566. hi = hi + Math.imul(ah1, bh6) | 0;
  19567. lo = lo + Math.imul(al0, bl7) | 0;
  19568. mid = mid + Math.imul(al0, bh7) | 0;
  19569. mid = mid + Math.imul(ah0, bl7) | 0;
  19570. hi = hi + Math.imul(ah0, bh7) | 0;
  19571. var w7 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19572. c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0;
  19573. w7 &= 0x3ffffff;
  19574. /* k = 8 */
  19575. lo = Math.imul(al8, bl0);
  19576. mid = Math.imul(al8, bh0);
  19577. mid = mid + Math.imul(ah8, bl0) | 0;
  19578. hi = Math.imul(ah8, bh0);
  19579. lo = lo + Math.imul(al7, bl1) | 0;
  19580. mid = mid + Math.imul(al7, bh1) | 0;
  19581. mid = mid + Math.imul(ah7, bl1) | 0;
  19582. hi = hi + Math.imul(ah7, bh1) | 0;
  19583. lo = lo + Math.imul(al6, bl2) | 0;
  19584. mid = mid + Math.imul(al6, bh2) | 0;
  19585. mid = mid + Math.imul(ah6, bl2) | 0;
  19586. hi = hi + Math.imul(ah6, bh2) | 0;
  19587. lo = lo + Math.imul(al5, bl3) | 0;
  19588. mid = mid + Math.imul(al5, bh3) | 0;
  19589. mid = mid + Math.imul(ah5, bl3) | 0;
  19590. hi = hi + Math.imul(ah5, bh3) | 0;
  19591. lo = lo + Math.imul(al4, bl4) | 0;
  19592. mid = mid + Math.imul(al4, bh4) | 0;
  19593. mid = mid + Math.imul(ah4, bl4) | 0;
  19594. hi = hi + Math.imul(ah4, bh4) | 0;
  19595. lo = lo + Math.imul(al3, bl5) | 0;
  19596. mid = mid + Math.imul(al3, bh5) | 0;
  19597. mid = mid + Math.imul(ah3, bl5) | 0;
  19598. hi = hi + Math.imul(ah3, bh5) | 0;
  19599. lo = lo + Math.imul(al2, bl6) | 0;
  19600. mid = mid + Math.imul(al2, bh6) | 0;
  19601. mid = mid + Math.imul(ah2, bl6) | 0;
  19602. hi = hi + Math.imul(ah2, bh6) | 0;
  19603. lo = lo + Math.imul(al1, bl7) | 0;
  19604. mid = mid + Math.imul(al1, bh7) | 0;
  19605. mid = mid + Math.imul(ah1, bl7) | 0;
  19606. hi = hi + Math.imul(ah1, bh7) | 0;
  19607. lo = lo + Math.imul(al0, bl8) | 0;
  19608. mid = mid + Math.imul(al0, bh8) | 0;
  19609. mid = mid + Math.imul(ah0, bl8) | 0;
  19610. hi = hi + Math.imul(ah0, bh8) | 0;
  19611. var w8 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19612. c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0;
  19613. w8 &= 0x3ffffff;
  19614. /* k = 9 */
  19615. lo = Math.imul(al9, bl0);
  19616. mid = Math.imul(al9, bh0);
  19617. mid = mid + Math.imul(ah9, bl0) | 0;
  19618. hi = Math.imul(ah9, bh0);
  19619. lo = lo + Math.imul(al8, bl1) | 0;
  19620. mid = mid + Math.imul(al8, bh1) | 0;
  19621. mid = mid + Math.imul(ah8, bl1) | 0;
  19622. hi = hi + Math.imul(ah8, bh1) | 0;
  19623. lo = lo + Math.imul(al7, bl2) | 0;
  19624. mid = mid + Math.imul(al7, bh2) | 0;
  19625. mid = mid + Math.imul(ah7, bl2) | 0;
  19626. hi = hi + Math.imul(ah7, bh2) | 0;
  19627. lo = lo + Math.imul(al6, bl3) | 0;
  19628. mid = mid + Math.imul(al6, bh3) | 0;
  19629. mid = mid + Math.imul(ah6, bl3) | 0;
  19630. hi = hi + Math.imul(ah6, bh3) | 0;
  19631. lo = lo + Math.imul(al5, bl4) | 0;
  19632. mid = mid + Math.imul(al5, bh4) | 0;
  19633. mid = mid + Math.imul(ah5, bl4) | 0;
  19634. hi = hi + Math.imul(ah5, bh4) | 0;
  19635. lo = lo + Math.imul(al4, bl5) | 0;
  19636. mid = mid + Math.imul(al4, bh5) | 0;
  19637. mid = mid + Math.imul(ah4, bl5) | 0;
  19638. hi = hi + Math.imul(ah4, bh5) | 0;
  19639. lo = lo + Math.imul(al3, bl6) | 0;
  19640. mid = mid + Math.imul(al3, bh6) | 0;
  19641. mid = mid + Math.imul(ah3, bl6) | 0;
  19642. hi = hi + Math.imul(ah3, bh6) | 0;
  19643. lo = lo + Math.imul(al2, bl7) | 0;
  19644. mid = mid + Math.imul(al2, bh7) | 0;
  19645. mid = mid + Math.imul(ah2, bl7) | 0;
  19646. hi = hi + Math.imul(ah2, bh7) | 0;
  19647. lo = lo + Math.imul(al1, bl8) | 0;
  19648. mid = mid + Math.imul(al1, bh8) | 0;
  19649. mid = mid + Math.imul(ah1, bl8) | 0;
  19650. hi = hi + Math.imul(ah1, bh8) | 0;
  19651. lo = lo + Math.imul(al0, bl9) | 0;
  19652. mid = mid + Math.imul(al0, bh9) | 0;
  19653. mid = mid + Math.imul(ah0, bl9) | 0;
  19654. hi = hi + Math.imul(ah0, bh9) | 0;
  19655. var w9 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19656. c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0;
  19657. w9 &= 0x3ffffff;
  19658. /* k = 10 */
  19659. lo = Math.imul(al9, bl1);
  19660. mid = Math.imul(al9, bh1);
  19661. mid = mid + Math.imul(ah9, bl1) | 0;
  19662. hi = Math.imul(ah9, bh1);
  19663. lo = lo + Math.imul(al8, bl2) | 0;
  19664. mid = mid + Math.imul(al8, bh2) | 0;
  19665. mid = mid + Math.imul(ah8, bl2) | 0;
  19666. hi = hi + Math.imul(ah8, bh2) | 0;
  19667. lo = lo + Math.imul(al7, bl3) | 0;
  19668. mid = mid + Math.imul(al7, bh3) | 0;
  19669. mid = mid + Math.imul(ah7, bl3) | 0;
  19670. hi = hi + Math.imul(ah7, bh3) | 0;
  19671. lo = lo + Math.imul(al6, bl4) | 0;
  19672. mid = mid + Math.imul(al6, bh4) | 0;
  19673. mid = mid + Math.imul(ah6, bl4) | 0;
  19674. hi = hi + Math.imul(ah6, bh4) | 0;
  19675. lo = lo + Math.imul(al5, bl5) | 0;
  19676. mid = mid + Math.imul(al5, bh5) | 0;
  19677. mid = mid + Math.imul(ah5, bl5) | 0;
  19678. hi = hi + Math.imul(ah5, bh5) | 0;
  19679. lo = lo + Math.imul(al4, bl6) | 0;
  19680. mid = mid + Math.imul(al4, bh6) | 0;
  19681. mid = mid + Math.imul(ah4, bl6) | 0;
  19682. hi = hi + Math.imul(ah4, bh6) | 0;
  19683. lo = lo + Math.imul(al3, bl7) | 0;
  19684. mid = mid + Math.imul(al3, bh7) | 0;
  19685. mid = mid + Math.imul(ah3, bl7) | 0;
  19686. hi = hi + Math.imul(ah3, bh7) | 0;
  19687. lo = lo + Math.imul(al2, bl8) | 0;
  19688. mid = mid + Math.imul(al2, bh8) | 0;
  19689. mid = mid + Math.imul(ah2, bl8) | 0;
  19690. hi = hi + Math.imul(ah2, bh8) | 0;
  19691. lo = lo + Math.imul(al1, bl9) | 0;
  19692. mid = mid + Math.imul(al1, bh9) | 0;
  19693. mid = mid + Math.imul(ah1, bl9) | 0;
  19694. hi = hi + Math.imul(ah1, bh9) | 0;
  19695. var w10 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19696. c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0;
  19697. w10 &= 0x3ffffff;
  19698. /* k = 11 */
  19699. lo = Math.imul(al9, bl2);
  19700. mid = Math.imul(al9, bh2);
  19701. mid = mid + Math.imul(ah9, bl2) | 0;
  19702. hi = Math.imul(ah9, bh2);
  19703. lo = lo + Math.imul(al8, bl3) | 0;
  19704. mid = mid + Math.imul(al8, bh3) | 0;
  19705. mid = mid + Math.imul(ah8, bl3) | 0;
  19706. hi = hi + Math.imul(ah8, bh3) | 0;
  19707. lo = lo + Math.imul(al7, bl4) | 0;
  19708. mid = mid + Math.imul(al7, bh4) | 0;
  19709. mid = mid + Math.imul(ah7, bl4) | 0;
  19710. hi = hi + Math.imul(ah7, bh4) | 0;
  19711. lo = lo + Math.imul(al6, bl5) | 0;
  19712. mid = mid + Math.imul(al6, bh5) | 0;
  19713. mid = mid + Math.imul(ah6, bl5) | 0;
  19714. hi = hi + Math.imul(ah6, bh5) | 0;
  19715. lo = lo + Math.imul(al5, bl6) | 0;
  19716. mid = mid + Math.imul(al5, bh6) | 0;
  19717. mid = mid + Math.imul(ah5, bl6) | 0;
  19718. hi = hi + Math.imul(ah5, bh6) | 0;
  19719. lo = lo + Math.imul(al4, bl7) | 0;
  19720. mid = mid + Math.imul(al4, bh7) | 0;
  19721. mid = mid + Math.imul(ah4, bl7) | 0;
  19722. hi = hi + Math.imul(ah4, bh7) | 0;
  19723. lo = lo + Math.imul(al3, bl8) | 0;
  19724. mid = mid + Math.imul(al3, bh8) | 0;
  19725. mid = mid + Math.imul(ah3, bl8) | 0;
  19726. hi = hi + Math.imul(ah3, bh8) | 0;
  19727. lo = lo + Math.imul(al2, bl9) | 0;
  19728. mid = mid + Math.imul(al2, bh9) | 0;
  19729. mid = mid + Math.imul(ah2, bl9) | 0;
  19730. hi = hi + Math.imul(ah2, bh9) | 0;
  19731. var w11 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19732. c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0;
  19733. w11 &= 0x3ffffff;
  19734. /* k = 12 */
  19735. lo = Math.imul(al9, bl3);
  19736. mid = Math.imul(al9, bh3);
  19737. mid = mid + Math.imul(ah9, bl3) | 0;
  19738. hi = Math.imul(ah9, bh3);
  19739. lo = lo + Math.imul(al8, bl4) | 0;
  19740. mid = mid + Math.imul(al8, bh4) | 0;
  19741. mid = mid + Math.imul(ah8, bl4) | 0;
  19742. hi = hi + Math.imul(ah8, bh4) | 0;
  19743. lo = lo + Math.imul(al7, bl5) | 0;
  19744. mid = mid + Math.imul(al7, bh5) | 0;
  19745. mid = mid + Math.imul(ah7, bl5) | 0;
  19746. hi = hi + Math.imul(ah7, bh5) | 0;
  19747. lo = lo + Math.imul(al6, bl6) | 0;
  19748. mid = mid + Math.imul(al6, bh6) | 0;
  19749. mid = mid + Math.imul(ah6, bl6) | 0;
  19750. hi = hi + Math.imul(ah6, bh6) | 0;
  19751. lo = lo + Math.imul(al5, bl7) | 0;
  19752. mid = mid + Math.imul(al5, bh7) | 0;
  19753. mid = mid + Math.imul(ah5, bl7) | 0;
  19754. hi = hi + Math.imul(ah5, bh7) | 0;
  19755. lo = lo + Math.imul(al4, bl8) | 0;
  19756. mid = mid + Math.imul(al4, bh8) | 0;
  19757. mid = mid + Math.imul(ah4, bl8) | 0;
  19758. hi = hi + Math.imul(ah4, bh8) | 0;
  19759. lo = lo + Math.imul(al3, bl9) | 0;
  19760. mid = mid + Math.imul(al3, bh9) | 0;
  19761. mid = mid + Math.imul(ah3, bl9) | 0;
  19762. hi = hi + Math.imul(ah3, bh9) | 0;
  19763. var w12 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19764. c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0;
  19765. w12 &= 0x3ffffff;
  19766. /* k = 13 */
  19767. lo = Math.imul(al9, bl4);
  19768. mid = Math.imul(al9, bh4);
  19769. mid = mid + Math.imul(ah9, bl4) | 0;
  19770. hi = Math.imul(ah9, bh4);
  19771. lo = lo + Math.imul(al8, bl5) | 0;
  19772. mid = mid + Math.imul(al8, bh5) | 0;
  19773. mid = mid + Math.imul(ah8, bl5) | 0;
  19774. hi = hi + Math.imul(ah8, bh5) | 0;
  19775. lo = lo + Math.imul(al7, bl6) | 0;
  19776. mid = mid + Math.imul(al7, bh6) | 0;
  19777. mid = mid + Math.imul(ah7, bl6) | 0;
  19778. hi = hi + Math.imul(ah7, bh6) | 0;
  19779. lo = lo + Math.imul(al6, bl7) | 0;
  19780. mid = mid + Math.imul(al6, bh7) | 0;
  19781. mid = mid + Math.imul(ah6, bl7) | 0;
  19782. hi = hi + Math.imul(ah6, bh7) | 0;
  19783. lo = lo + Math.imul(al5, bl8) | 0;
  19784. mid = mid + Math.imul(al5, bh8) | 0;
  19785. mid = mid + Math.imul(ah5, bl8) | 0;
  19786. hi = hi + Math.imul(ah5, bh8) | 0;
  19787. lo = lo + Math.imul(al4, bl9) | 0;
  19788. mid = mid + Math.imul(al4, bh9) | 0;
  19789. mid = mid + Math.imul(ah4, bl9) | 0;
  19790. hi = hi + Math.imul(ah4, bh9) | 0;
  19791. var w13 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19792. c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0;
  19793. w13 &= 0x3ffffff;
  19794. /* k = 14 */
  19795. lo = Math.imul(al9, bl5);
  19796. mid = Math.imul(al9, bh5);
  19797. mid = mid + Math.imul(ah9, bl5) | 0;
  19798. hi = Math.imul(ah9, bh5);
  19799. lo = lo + Math.imul(al8, bl6) | 0;
  19800. mid = mid + Math.imul(al8, bh6) | 0;
  19801. mid = mid + Math.imul(ah8, bl6) | 0;
  19802. hi = hi + Math.imul(ah8, bh6) | 0;
  19803. lo = lo + Math.imul(al7, bl7) | 0;
  19804. mid = mid + Math.imul(al7, bh7) | 0;
  19805. mid = mid + Math.imul(ah7, bl7) | 0;
  19806. hi = hi + Math.imul(ah7, bh7) | 0;
  19807. lo = lo + Math.imul(al6, bl8) | 0;
  19808. mid = mid + Math.imul(al6, bh8) | 0;
  19809. mid = mid + Math.imul(ah6, bl8) | 0;
  19810. hi = hi + Math.imul(ah6, bh8) | 0;
  19811. lo = lo + Math.imul(al5, bl9) | 0;
  19812. mid = mid + Math.imul(al5, bh9) | 0;
  19813. mid = mid + Math.imul(ah5, bl9) | 0;
  19814. hi = hi + Math.imul(ah5, bh9) | 0;
  19815. var w14 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19816. c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0;
  19817. w14 &= 0x3ffffff;
  19818. /* k = 15 */
  19819. lo = Math.imul(al9, bl6);
  19820. mid = Math.imul(al9, bh6);
  19821. mid = mid + Math.imul(ah9, bl6) | 0;
  19822. hi = Math.imul(ah9, bh6);
  19823. lo = lo + Math.imul(al8, bl7) | 0;
  19824. mid = mid + Math.imul(al8, bh7) | 0;
  19825. mid = mid + Math.imul(ah8, bl7) | 0;
  19826. hi = hi + Math.imul(ah8, bh7) | 0;
  19827. lo = lo + Math.imul(al7, bl8) | 0;
  19828. mid = mid + Math.imul(al7, bh8) | 0;
  19829. mid = mid + Math.imul(ah7, bl8) | 0;
  19830. hi = hi + Math.imul(ah7, bh8) | 0;
  19831. lo = lo + Math.imul(al6, bl9) | 0;
  19832. mid = mid + Math.imul(al6, bh9) | 0;
  19833. mid = mid + Math.imul(ah6, bl9) | 0;
  19834. hi = hi + Math.imul(ah6, bh9) | 0;
  19835. var w15 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19836. c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0;
  19837. w15 &= 0x3ffffff;
  19838. /* k = 16 */
  19839. lo = Math.imul(al9, bl7);
  19840. mid = Math.imul(al9, bh7);
  19841. mid = mid + Math.imul(ah9, bl7) | 0;
  19842. hi = Math.imul(ah9, bh7);
  19843. lo = lo + Math.imul(al8, bl8) | 0;
  19844. mid = mid + Math.imul(al8, bh8) | 0;
  19845. mid = mid + Math.imul(ah8, bl8) | 0;
  19846. hi = hi + Math.imul(ah8, bh8) | 0;
  19847. lo = lo + Math.imul(al7, bl9) | 0;
  19848. mid = mid + Math.imul(al7, bh9) | 0;
  19849. mid = mid + Math.imul(ah7, bl9) | 0;
  19850. hi = hi + Math.imul(ah7, bh9) | 0;
  19851. var w16 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19852. c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0;
  19853. w16 &= 0x3ffffff;
  19854. /* k = 17 */
  19855. lo = Math.imul(al9, bl8);
  19856. mid = Math.imul(al9, bh8);
  19857. mid = mid + Math.imul(ah9, bl8) | 0;
  19858. hi = Math.imul(ah9, bh8);
  19859. lo = lo + Math.imul(al8, bl9) | 0;
  19860. mid = mid + Math.imul(al8, bh9) | 0;
  19861. mid = mid + Math.imul(ah8, bl9) | 0;
  19862. hi = hi + Math.imul(ah8, bh9) | 0;
  19863. var w17 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19864. c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0;
  19865. w17 &= 0x3ffffff;
  19866. /* k = 18 */
  19867. lo = Math.imul(al9, bl9);
  19868. mid = Math.imul(al9, bh9);
  19869. mid = mid + Math.imul(ah9, bl9) | 0;
  19870. hi = Math.imul(ah9, bh9);
  19871. var w18 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  19872. c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0;
  19873. w18 &= 0x3ffffff;
  19874. o[0] = w0;
  19875. o[1] = w1;
  19876. o[2] = w2;
  19877. o[3] = w3;
  19878. o[4] = w4;
  19879. o[5] = w5;
  19880. o[6] = w6;
  19881. o[7] = w7;
  19882. o[8] = w8;
  19883. o[9] = w9;
  19884. o[10] = w10;
  19885. o[11] = w11;
  19886. o[12] = w12;
  19887. o[13] = w13;
  19888. o[14] = w14;
  19889. o[15] = w15;
  19890. o[16] = w16;
  19891. o[17] = w17;
  19892. o[18] = w18;
  19893. if (c !== 0) {
  19894. o[19] = c;
  19895. out.length++;
  19896. }
  19897. return out;
  19898. };
  19899. // Polyfill comb
  19900. if (!Math.imul) {
  19901. comb10MulTo = smallMulTo;
  19902. }
  19903. function bigMulTo(self, num, out) {
  19904. out.negative = num.negative ^ self.negative;
  19905. out.length = self.length + num.length;
  19906. var carry = 0;
  19907. var hncarry = 0;
  19908. for (var k = 0; k < out.length - 1; k++) {
  19909. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  19910. // note that ncarry could be >= 0x3ffffff
  19911. var ncarry = hncarry;
  19912. hncarry = 0;
  19913. var rword = carry & 0x3ffffff;
  19914. var maxJ = Math.min(k, num.length - 1);
  19915. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  19916. var i = k - j;
  19917. var a = self.words[i] | 0;
  19918. var b = num.words[j] | 0;
  19919. var r = a * b;
  19920. var lo = r & 0x3ffffff;
  19921. ncarry = ncarry + (r / 0x4000000 | 0) | 0;
  19922. lo = lo + rword | 0;
  19923. rword = lo & 0x3ffffff;
  19924. ncarry = ncarry + (lo >>> 26) | 0;
  19925. hncarry += ncarry >>> 26;
  19926. ncarry &= 0x3ffffff;
  19927. }
  19928. out.words[k] = rword;
  19929. carry = ncarry;
  19930. ncarry = hncarry;
  19931. }
  19932. if (carry !== 0) {
  19933. out.words[k] = carry;
  19934. } else {
  19935. out.length--;
  19936. }
  19937. return out.strip();
  19938. }
  19939. function jumboMulTo(self, num, out) {
  19940. var fftm = new FFTM();
  19941. return fftm.mulp(self, num, out);
  19942. }
  19943. BN.prototype.mulTo = function mulTo(num, out) {
  19944. var res;
  19945. var len = this.length + num.length;
  19946. if (this.length === 10 && num.length === 10) {
  19947. res = comb10MulTo(this, num, out);
  19948. } else if (len < 63) {
  19949. res = smallMulTo(this, num, out);
  19950. } else if (len < 1024) {
  19951. res = bigMulTo(this, num, out);
  19952. } else {
  19953. res = jumboMulTo(this, num, out);
  19954. }
  19955. return res;
  19956. };
  19957. // Cooley-Tukey algorithm for FFT
  19958. // slightly revisited to rely on looping instead of recursion
  19959. function FFTM(x, y) {
  19960. this.x = x;
  19961. this.y = y;
  19962. }
  19963. FFTM.prototype.makeRBT = function makeRBT(N) {
  19964. var t = new Array(N);
  19965. var l = BN.prototype._countBits(N) - 1;
  19966. for (var i = 0; i < N; i++) {
  19967. t[i] = this.revBin(i, l, N);
  19968. }
  19969. return t;
  19970. };
  19971. // Returns binary-reversed representation of `x`
  19972. FFTM.prototype.revBin = function revBin(x, l, N) {
  19973. if (x === 0 || x === N - 1) return x;
  19974. var rb = 0;
  19975. for (var i = 0; i < l; i++) {
  19976. rb |= (x & 1) << l - i - 1;
  19977. x >>= 1;
  19978. }
  19979. return rb;
  19980. };
  19981. // Performs "tweedling" phase, therefore 'emulating'
  19982. // behaviour of the recursive algorithm
  19983. FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) {
  19984. for (var i = 0; i < N; i++) {
  19985. rtws[i] = rws[rbt[i]];
  19986. itws[i] = iws[rbt[i]];
  19987. }
  19988. };
  19989. FFTM.prototype.transform = function transform(rws, iws, rtws, itws, N, rbt) {
  19990. this.permute(rbt, rws, iws, rtws, itws, N);
  19991. for (var s = 1; s < N; s <<= 1) {
  19992. var l = s << 1;
  19993. var rtwdf = Math.cos(2 * Math.PI / l);
  19994. var itwdf = Math.sin(2 * Math.PI / l);
  19995. for (var p = 0; p < N; p += l) {
  19996. var rtwdf_ = rtwdf;
  19997. var itwdf_ = itwdf;
  19998. for (var j = 0; j < s; j++) {
  19999. var re = rtws[p + j];
  20000. var ie = itws[p + j];
  20001. var ro = rtws[p + j + s];
  20002. var io = itws[p + j + s];
  20003. var rx = rtwdf_ * ro - itwdf_ * io;
  20004. io = rtwdf_ * io + itwdf_ * ro;
  20005. ro = rx;
  20006. rtws[p + j] = re + ro;
  20007. itws[p + j] = ie + io;
  20008. rtws[p + j + s] = re - ro;
  20009. itws[p + j + s] = ie - io;
  20010. /* jshint maxdepth : false */
  20011. if (j !== l) {
  20012. rx = rtwdf * rtwdf_ - itwdf * itwdf_;
  20013. itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
  20014. rtwdf_ = rx;
  20015. }
  20016. }
  20017. }
  20018. }
  20019. };
  20020. FFTM.prototype.guessLen13b = function guessLen13b(n, m) {
  20021. var N = Math.max(m, n) | 1;
  20022. var odd = N & 1;
  20023. var i = 0;
  20024. for (N = N / 2 | 0; N; N = N >>> 1) {
  20025. i++;
  20026. }
  20027. return 1 << i + 1 + odd;
  20028. };
  20029. FFTM.prototype.conjugate = function conjugate(rws, iws, N) {
  20030. if (N <= 1) return;
  20031. for (var i = 0; i < N / 2; i++) {
  20032. var t = rws[i];
  20033. rws[i] = rws[N - i - 1];
  20034. rws[N - i - 1] = t;
  20035. t = iws[i];
  20036. iws[i] = -iws[N - i - 1];
  20037. iws[N - i - 1] = -t;
  20038. }
  20039. };
  20040. FFTM.prototype.normalize13b = function normalize13b(ws, N) {
  20041. var carry = 0;
  20042. for (var i = 0; i < N / 2; i++) {
  20043. var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry;
  20044. ws[i] = w & 0x3ffffff;
  20045. if (w < 0x4000000) {
  20046. carry = 0;
  20047. } else {
  20048. carry = w / 0x4000000 | 0;
  20049. }
  20050. }
  20051. return ws;
  20052. };
  20053. FFTM.prototype.convert13b = function convert13b(ws, len, rws, N) {
  20054. var carry = 0;
  20055. for (var i = 0; i < len; i++) {
  20056. carry = carry + (ws[i] | 0);
  20057. rws[2 * i] = carry & 0x1fff;
  20058. carry = carry >>> 13;
  20059. rws[2 * i + 1] = carry & 0x1fff;
  20060. carry = carry >>> 13;
  20061. }
  20062. // Pad with zeroes
  20063. for (i = 2 * len; i < N; ++i) {
  20064. rws[i] = 0;
  20065. }
  20066. assert(carry === 0);
  20067. assert((carry & ~0x1fff) === 0);
  20068. };
  20069. FFTM.prototype.stub = function stub(N) {
  20070. var ph = new Array(N);
  20071. for (var i = 0; i < N; i++) {
  20072. ph[i] = 0;
  20073. }
  20074. return ph;
  20075. };
  20076. FFTM.prototype.mulp = function mulp(x, y, out) {
  20077. var N = 2 * this.guessLen13b(x.length, y.length);
  20078. var rbt = this.makeRBT(N);
  20079. var _ = this.stub(N);
  20080. var rws = new Array(N);
  20081. var rwst = new Array(N);
  20082. var iwst = new Array(N);
  20083. var nrws = new Array(N);
  20084. var nrwst = new Array(N);
  20085. var niwst = new Array(N);
  20086. var rmws = out.words;
  20087. rmws.length = N;
  20088. this.convert13b(x.words, x.length, rws, N);
  20089. this.convert13b(y.words, y.length, nrws, N);
  20090. this.transform(rws, _, rwst, iwst, N, rbt);
  20091. this.transform(nrws, _, nrwst, niwst, N, rbt);
  20092. for (var i = 0; i < N; i++) {
  20093. var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
  20094. iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
  20095. rwst[i] = rx;
  20096. }
  20097. this.conjugate(rwst, iwst, N);
  20098. this.transform(rwst, iwst, rmws, _, N, rbt);
  20099. this.conjugate(rmws, _, N);
  20100. this.normalize13b(rmws, N);
  20101. out.negative = x.negative ^ y.negative;
  20102. out.length = x.length + y.length;
  20103. return out.strip();
  20104. };
  20105. // Multiply `this` by `num`
  20106. BN.prototype.mul = function mul(num) {
  20107. var out = new BN(null);
  20108. out.words = new Array(this.length + num.length);
  20109. return this.mulTo(num, out);
  20110. };
  20111. // Multiply employing FFT
  20112. BN.prototype.mulf = function mulf(num) {
  20113. var out = new BN(null);
  20114. out.words = new Array(this.length + num.length);
  20115. return jumboMulTo(this, num, out);
  20116. };
  20117. // In-place Multiplication
  20118. BN.prototype.imul = function imul(num) {
  20119. return this.clone().mulTo(num, this);
  20120. };
  20121. BN.prototype.imuln = function imuln(num) {
  20122. assert(typeof num === 'number');
  20123. assert(num < 0x4000000);
  20124. // Carry
  20125. var carry = 0;
  20126. for (var i = 0; i < this.length; i++) {
  20127. var w = (this.words[i] | 0) * num;
  20128. var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
  20129. carry >>= 26;
  20130. carry += w / 0x4000000 | 0;
  20131. // NOTE: lo is 27bit maximum
  20132. carry += lo >>> 26;
  20133. this.words[i] = lo & 0x3ffffff;
  20134. }
  20135. if (carry !== 0) {
  20136. this.words[i] = carry;
  20137. this.length++;
  20138. }
  20139. return this;
  20140. };
  20141. BN.prototype.muln = function muln(num) {
  20142. return this.clone().imuln(num);
  20143. };
  20144. // `this` * `this`
  20145. BN.prototype.sqr = function sqr() {
  20146. return this.mul(this);
  20147. };
  20148. // `this` * `this` in-place
  20149. BN.prototype.isqr = function isqr() {
  20150. return this.imul(this.clone());
  20151. };
  20152. // Math.pow(`this`, `num`)
  20153. BN.prototype.pow = function pow(num) {
  20154. var w = toBitArray(num);
  20155. if (w.length === 0) return new BN(1);
  20156. // Skip leading zeroes
  20157. var res = this;
  20158. for (var i = 0; i < w.length; i++, res = res.sqr()) {
  20159. if (w[i] !== 0) break;
  20160. }
  20161. if (++i < w.length) {
  20162. for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
  20163. if (w[i] === 0) continue;
  20164. res = res.mul(q);
  20165. }
  20166. }
  20167. return res;
  20168. };
  20169. // Shift-left in-place
  20170. BN.prototype.iushln = function iushln(bits) {
  20171. assert(typeof bits === 'number' && bits >= 0);
  20172. var r = bits % 26;
  20173. var s = (bits - r) / 26;
  20174. var carryMask = 0x3ffffff >>> 26 - r << 26 - r;
  20175. var i;
  20176. if (r !== 0) {
  20177. var carry = 0;
  20178. for (i = 0; i < this.length; i++) {
  20179. var newCarry = this.words[i] & carryMask;
  20180. var c = (this.words[i] | 0) - newCarry << r;
  20181. this.words[i] = c | carry;
  20182. carry = newCarry >>> 26 - r;
  20183. }
  20184. if (carry) {
  20185. this.words[i] = carry;
  20186. this.length++;
  20187. }
  20188. }
  20189. if (s !== 0) {
  20190. for (i = this.length - 1; i >= 0; i--) {
  20191. this.words[i + s] = this.words[i];
  20192. }
  20193. for (i = 0; i < s; i++) {
  20194. this.words[i] = 0;
  20195. }
  20196. this.length += s;
  20197. }
  20198. return this.strip();
  20199. };
  20200. BN.prototype.ishln = function ishln(bits) {
  20201. // TODO(indutny): implement me
  20202. assert(this.negative === 0);
  20203. return this.iushln(bits);
  20204. };
  20205. // Shift-right in-place
  20206. // NOTE: `hint` is a lowest bit before trailing zeroes
  20207. // NOTE: if `extended` is present - it will be filled with destroyed bits
  20208. BN.prototype.iushrn = function iushrn(bits, hint, extended) {
  20209. assert(typeof bits === 'number' && bits >= 0);
  20210. var h;
  20211. if (hint) {
  20212. h = (hint - hint % 26) / 26;
  20213. } else {
  20214. h = 0;
  20215. }
  20216. var r = bits % 26;
  20217. var s = Math.min((bits - r) / 26, this.length);
  20218. var mask = 0x3ffffff ^ 0x3ffffff >>> r << r;
  20219. var maskedWords = extended;
  20220. h -= s;
  20221. h = Math.max(0, h);
  20222. // Extended mode, copy masked part
  20223. if (maskedWords) {
  20224. for (var i = 0; i < s; i++) {
  20225. maskedWords.words[i] = this.words[i];
  20226. }
  20227. maskedWords.length = s;
  20228. }
  20229. if (s === 0) {
  20230. // No-op, we should not move anything at all
  20231. } else if (this.length > s) {
  20232. this.length -= s;
  20233. for (i = 0; i < this.length; i++) {
  20234. this.words[i] = this.words[i + s];
  20235. }
  20236. } else {
  20237. this.words[0] = 0;
  20238. this.length = 1;
  20239. }
  20240. var carry = 0;
  20241. for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
  20242. var word = this.words[i] | 0;
  20243. this.words[i] = carry << 26 - r | word >>> r;
  20244. carry = word & mask;
  20245. }
  20246. // Push carried bits as a mask
  20247. if (maskedWords && carry !== 0) {
  20248. maskedWords.words[maskedWords.length++] = carry;
  20249. }
  20250. if (this.length === 0) {
  20251. this.words[0] = 0;
  20252. this.length = 1;
  20253. }
  20254. return this.strip();
  20255. };
  20256. BN.prototype.ishrn = function ishrn(bits, hint, extended) {
  20257. // TODO(indutny): implement me
  20258. assert(this.negative === 0);
  20259. return this.iushrn(bits, hint, extended);
  20260. };
  20261. // Shift-left
  20262. BN.prototype.shln = function shln(bits) {
  20263. return this.clone().ishln(bits);
  20264. };
  20265. BN.prototype.ushln = function ushln(bits) {
  20266. return this.clone().iushln(bits);
  20267. };
  20268. // Shift-right
  20269. BN.prototype.shrn = function shrn(bits) {
  20270. return this.clone().ishrn(bits);
  20271. };
  20272. BN.prototype.ushrn = function ushrn(bits) {
  20273. return this.clone().iushrn(bits);
  20274. };
  20275. // Test if n bit is set
  20276. BN.prototype.testn = function testn(bit) {
  20277. assert(typeof bit === 'number' && bit >= 0);
  20278. var r = bit % 26;
  20279. var s = (bit - r) / 26;
  20280. var q = 1 << r;
  20281. // Fast case: bit is much higher than all existing words
  20282. if (this.length <= s) return false;
  20283. // Check bit and return
  20284. var w = this.words[s];
  20285. return !!(w & q);
  20286. };
  20287. // Return only lowers bits of number (in-place)
  20288. BN.prototype.imaskn = function imaskn(bits) {
  20289. assert(typeof bits === 'number' && bits >= 0);
  20290. var r = bits % 26;
  20291. var s = (bits - r) / 26;
  20292. assert(this.negative === 0, 'imaskn works only with positive numbers');
  20293. if (this.length <= s) {
  20294. return this;
  20295. }
  20296. if (r !== 0) {
  20297. s++;
  20298. }
  20299. this.length = Math.min(s, this.length);
  20300. if (r !== 0) {
  20301. var mask = 0x3ffffff ^ 0x3ffffff >>> r << r;
  20302. this.words[this.length - 1] &= mask;
  20303. }
  20304. return this.strip();
  20305. };
  20306. // Return only lowers bits of number
  20307. BN.prototype.maskn = function maskn(bits) {
  20308. return this.clone().imaskn(bits);
  20309. };
  20310. // Add plain number `num` to `this`
  20311. BN.prototype.iaddn = function iaddn(num) {
  20312. assert(typeof num === 'number');
  20313. assert(num < 0x4000000);
  20314. if (num < 0) return this.isubn(-num);
  20315. // Possible sign change
  20316. if (this.negative !== 0) {
  20317. if (this.length === 1 && (this.words[0] | 0) < num) {
  20318. this.words[0] = num - (this.words[0] | 0);
  20319. this.negative = 0;
  20320. return this;
  20321. }
  20322. this.negative = 0;
  20323. this.isubn(num);
  20324. this.negative = 1;
  20325. return this;
  20326. }
  20327. // Add without checks
  20328. return this._iaddn(num);
  20329. };
  20330. BN.prototype._iaddn = function _iaddn(num) {
  20331. this.words[0] += num;
  20332. // Carry
  20333. for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
  20334. this.words[i] -= 0x4000000;
  20335. if (i === this.length - 1) {
  20336. this.words[i + 1] = 1;
  20337. } else {
  20338. this.words[i + 1]++;
  20339. }
  20340. }
  20341. this.length = Math.max(this.length, i + 1);
  20342. return this;
  20343. };
  20344. // Subtract plain number `num` from `this`
  20345. BN.prototype.isubn = function isubn(num) {
  20346. assert(typeof num === 'number');
  20347. assert(num < 0x4000000);
  20348. if (num < 0) return this.iaddn(-num);
  20349. if (this.negative !== 0) {
  20350. this.negative = 0;
  20351. this.iaddn(num);
  20352. this.negative = 1;
  20353. return this;
  20354. }
  20355. this.words[0] -= num;
  20356. if (this.length === 1 && this.words[0] < 0) {
  20357. this.words[0] = -this.words[0];
  20358. this.negative = 1;
  20359. } else {
  20360. // Carry
  20361. for (var i = 0; i < this.length && this.words[i] < 0; i++) {
  20362. this.words[i] += 0x4000000;
  20363. this.words[i + 1] -= 1;
  20364. }
  20365. }
  20366. return this.strip();
  20367. };
  20368. BN.prototype.addn = function addn(num) {
  20369. return this.clone().iaddn(num);
  20370. };
  20371. BN.prototype.subn = function subn(num) {
  20372. return this.clone().isubn(num);
  20373. };
  20374. BN.prototype.iabs = function iabs() {
  20375. this.negative = 0;
  20376. return this;
  20377. };
  20378. BN.prototype.abs = function abs() {
  20379. return this.clone().iabs();
  20380. };
  20381. BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
  20382. var len = num.length + shift;
  20383. var i;
  20384. this._expand(len);
  20385. var w;
  20386. var carry = 0;
  20387. for (i = 0; i < num.length; i++) {
  20388. w = (this.words[i + shift] | 0) + carry;
  20389. var right = (num.words[i] | 0) * mul;
  20390. w -= right & 0x3ffffff;
  20391. carry = (w >> 26) - (right / 0x4000000 | 0);
  20392. this.words[i + shift] = w & 0x3ffffff;
  20393. }
  20394. for (; i < this.length - shift; i++) {
  20395. w = (this.words[i + shift] | 0) + carry;
  20396. carry = w >> 26;
  20397. this.words[i + shift] = w & 0x3ffffff;
  20398. }
  20399. if (carry === 0) return this.strip();
  20400. // Subtraction overflow
  20401. assert(carry === -1);
  20402. carry = 0;
  20403. for (i = 0; i < this.length; i++) {
  20404. w = -(this.words[i] | 0) + carry;
  20405. carry = w >> 26;
  20406. this.words[i] = w & 0x3ffffff;
  20407. }
  20408. this.negative = 1;
  20409. return this.strip();
  20410. };
  20411. BN.prototype._wordDiv = function _wordDiv(num, mode) {
  20412. var shift = this.length - num.length;
  20413. var a = this.clone();
  20414. var b = num;
  20415. // Normalize
  20416. var bhi = b.words[b.length - 1] | 0;
  20417. var bhiBits = this._countBits(bhi);
  20418. shift = 26 - bhiBits;
  20419. if (shift !== 0) {
  20420. b = b.ushln(shift);
  20421. a.iushln(shift);
  20422. bhi = b.words[b.length - 1] | 0;
  20423. }
  20424. // Initialize quotient
  20425. var m = a.length - b.length;
  20426. var q;
  20427. if (mode !== 'mod') {
  20428. q = new BN(null);
  20429. q.length = m + 1;
  20430. q.words = new Array(q.length);
  20431. for (var i = 0; i < q.length; i++) {
  20432. q.words[i] = 0;
  20433. }
  20434. }
  20435. var diff = a.clone()._ishlnsubmul(b, 1, m);
  20436. if (diff.negative === 0) {
  20437. a = diff;
  20438. if (q) {
  20439. q.words[m] = 1;
  20440. }
  20441. }
  20442. for (var j = m - 1; j >= 0; j--) {
  20443. var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0);
  20444. // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
  20445. // (0x7ffffff)
  20446. qj = Math.min(qj / bhi | 0, 0x3ffffff);
  20447. a._ishlnsubmul(b, qj, j);
  20448. while (a.negative !== 0) {
  20449. qj--;
  20450. a.negative = 0;
  20451. a._ishlnsubmul(b, 1, j);
  20452. if (!a.isZero()) {
  20453. a.negative ^= 1;
  20454. }
  20455. }
  20456. if (q) {
  20457. q.words[j] = qj;
  20458. }
  20459. }
  20460. if (q) {
  20461. q.strip();
  20462. }
  20463. a.strip();
  20464. // Denormalize
  20465. if (mode !== 'div' && shift !== 0) {
  20466. a.iushrn(shift);
  20467. }
  20468. return {
  20469. div: q || null,
  20470. mod: a
  20471. };
  20472. };
  20473. // NOTE: 1) `mode` can be set to `mod` to request mod only,
  20474. // to `div` to request div only, or be absent to
  20475. // request both div & mod
  20476. // 2) `positive` is true if unsigned mod is requested
  20477. BN.prototype.divmod = function divmod(num, mode, positive) {
  20478. assert(!num.isZero());
  20479. if (this.isZero()) {
  20480. return {
  20481. div: new BN(0),
  20482. mod: new BN(0)
  20483. };
  20484. }
  20485. var div, mod, res;
  20486. if (this.negative !== 0 && num.negative === 0) {
  20487. res = this.neg().divmod(num, mode);
  20488. if (mode !== 'mod') {
  20489. div = res.div.neg();
  20490. }
  20491. if (mode !== 'div') {
  20492. mod = res.mod.neg();
  20493. if (positive && mod.negative !== 0) {
  20494. mod.iadd(num);
  20495. }
  20496. }
  20497. return {
  20498. div: div,
  20499. mod: mod
  20500. };
  20501. }
  20502. if (this.negative === 0 && num.negative !== 0) {
  20503. res = this.divmod(num.neg(), mode);
  20504. if (mode !== 'mod') {
  20505. div = res.div.neg();
  20506. }
  20507. return {
  20508. div: div,
  20509. mod: res.mod
  20510. };
  20511. }
  20512. if ((this.negative & num.negative) !== 0) {
  20513. res = this.neg().divmod(num.neg(), mode);
  20514. if (mode !== 'div') {
  20515. mod = res.mod.neg();
  20516. if (positive && mod.negative !== 0) {
  20517. mod.isub(num);
  20518. }
  20519. }
  20520. return {
  20521. div: res.div,
  20522. mod: mod
  20523. };
  20524. }
  20525. // Both numbers are positive at this point
  20526. // Strip both numbers to approximate shift value
  20527. if (num.length > this.length || this.cmp(num) < 0) {
  20528. return {
  20529. div: new BN(0),
  20530. mod: this
  20531. };
  20532. }
  20533. // Very short reduction
  20534. if (num.length === 1) {
  20535. if (mode === 'div') {
  20536. return {
  20537. div: this.divn(num.words[0]),
  20538. mod: null
  20539. };
  20540. }
  20541. if (mode === 'mod') {
  20542. return {
  20543. div: null,
  20544. mod: new BN(this.modn(num.words[0]))
  20545. };
  20546. }
  20547. return {
  20548. div: this.divn(num.words[0]),
  20549. mod: new BN(this.modn(num.words[0]))
  20550. };
  20551. }
  20552. return this._wordDiv(num, mode);
  20553. };
  20554. // Find `this` / `num`
  20555. BN.prototype.div = function div(num) {
  20556. return this.divmod(num, 'div', false).div;
  20557. };
  20558. // Find `this` % `num`
  20559. BN.prototype.mod = function mod(num) {
  20560. return this.divmod(num, 'mod', false).mod;
  20561. };
  20562. BN.prototype.umod = function umod(num) {
  20563. return this.divmod(num, 'mod', true).mod;
  20564. };
  20565. // Find Round(`this` / `num`)
  20566. BN.prototype.divRound = function divRound(num) {
  20567. var dm = this.divmod(num);
  20568. // Fast case - exact division
  20569. if (dm.mod.isZero()) return dm.div;
  20570. var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
  20571. var half = num.ushrn(1);
  20572. var r2 = num.andln(1);
  20573. var cmp = mod.cmp(half);
  20574. // Round down
  20575. if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
  20576. // Round up
  20577. return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  20578. };
  20579. BN.prototype.modn = function modn(num) {
  20580. assert(num <= 0x3ffffff);
  20581. var p = (1 << 26) % num;
  20582. var acc = 0;
  20583. for (var i = this.length - 1; i >= 0; i--) {
  20584. acc = (p * acc + (this.words[i] | 0)) % num;
  20585. }
  20586. return acc;
  20587. };
  20588. // In-place division by number
  20589. BN.prototype.idivn = function idivn(num) {
  20590. assert(num <= 0x3ffffff);
  20591. var carry = 0;
  20592. for (var i = this.length - 1; i >= 0; i--) {
  20593. var w = (this.words[i] | 0) + carry * 0x4000000;
  20594. this.words[i] = w / num | 0;
  20595. carry = w % num;
  20596. }
  20597. return this.strip();
  20598. };
  20599. BN.prototype.divn = function divn(num) {
  20600. return this.clone().idivn(num);
  20601. };
  20602. BN.prototype.egcd = function egcd(p) {
  20603. assert(p.negative === 0);
  20604. assert(!p.isZero());
  20605. var x = this;
  20606. var y = p.clone();
  20607. if (x.negative !== 0) {
  20608. x = x.umod(p);
  20609. } else {
  20610. x = x.clone();
  20611. }
  20612. // A * x + B * y = x
  20613. var A = new BN(1);
  20614. var B = new BN(0);
  20615. // C * x + D * y = y
  20616. var C = new BN(0);
  20617. var D = new BN(1);
  20618. var g = 0;
  20619. while (x.isEven() && y.isEven()) {
  20620. x.iushrn(1);
  20621. y.iushrn(1);
  20622. ++g;
  20623. }
  20624. var yp = y.clone();
  20625. var xp = x.clone();
  20626. while (!x.isZero()) {
  20627. for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  20628. if (i > 0) {
  20629. x.iushrn(i);
  20630. while (i-- > 0) {
  20631. if (A.isOdd() || B.isOdd()) {
  20632. A.iadd(yp);
  20633. B.isub(xp);
  20634. }
  20635. A.iushrn(1);
  20636. B.iushrn(1);
  20637. }
  20638. }
  20639. for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  20640. if (j > 0) {
  20641. y.iushrn(j);
  20642. while (j-- > 0) {
  20643. if (C.isOdd() || D.isOdd()) {
  20644. C.iadd(yp);
  20645. D.isub(xp);
  20646. }
  20647. C.iushrn(1);
  20648. D.iushrn(1);
  20649. }
  20650. }
  20651. if (x.cmp(y) >= 0) {
  20652. x.isub(y);
  20653. A.isub(C);
  20654. B.isub(D);
  20655. } else {
  20656. y.isub(x);
  20657. C.isub(A);
  20658. D.isub(B);
  20659. }
  20660. }
  20661. return {
  20662. a: C,
  20663. b: D,
  20664. gcd: y.iushln(g)
  20665. };
  20666. };
  20667. // This is reduced incarnation of the binary EEA
  20668. // above, designated to invert members of the
  20669. // _prime_ fields F(p) at a maximal speed
  20670. BN.prototype._invmp = function _invmp(p) {
  20671. assert(p.negative === 0);
  20672. assert(!p.isZero());
  20673. var a = this;
  20674. var b = p.clone();
  20675. if (a.negative !== 0) {
  20676. a = a.umod(p);
  20677. } else {
  20678. a = a.clone();
  20679. }
  20680. var x1 = new BN(1);
  20681. var x2 = new BN(0);
  20682. var delta = b.clone();
  20683. while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
  20684. for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  20685. if (i > 0) {
  20686. a.iushrn(i);
  20687. while (i-- > 0) {
  20688. if (x1.isOdd()) {
  20689. x1.iadd(delta);
  20690. }
  20691. x1.iushrn(1);
  20692. }
  20693. }
  20694. for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  20695. if (j > 0) {
  20696. b.iushrn(j);
  20697. while (j-- > 0) {
  20698. if (x2.isOdd()) {
  20699. x2.iadd(delta);
  20700. }
  20701. x2.iushrn(1);
  20702. }
  20703. }
  20704. if (a.cmp(b) >= 0) {
  20705. a.isub(b);
  20706. x1.isub(x2);
  20707. } else {
  20708. b.isub(a);
  20709. x2.isub(x1);
  20710. }
  20711. }
  20712. var res;
  20713. if (a.cmpn(1) === 0) {
  20714. res = x1;
  20715. } else {
  20716. res = x2;
  20717. }
  20718. if (res.cmpn(0) < 0) {
  20719. res.iadd(p);
  20720. }
  20721. return res;
  20722. };
  20723. BN.prototype.gcd = function gcd(num) {
  20724. if (this.isZero()) return num.abs();
  20725. if (num.isZero()) return this.abs();
  20726. var a = this.clone();
  20727. var b = num.clone();
  20728. a.negative = 0;
  20729. b.negative = 0;
  20730. // Remove common factor of two
  20731. for (var shift = 0; a.isEven() && b.isEven(); shift++) {
  20732. a.iushrn(1);
  20733. b.iushrn(1);
  20734. }
  20735. do {
  20736. while (a.isEven()) {
  20737. a.iushrn(1);
  20738. }
  20739. while (b.isEven()) {
  20740. b.iushrn(1);
  20741. }
  20742. var r = a.cmp(b);
  20743. if (r < 0) {
  20744. // Swap `a` and `b` to make `a` always bigger than `b`
  20745. var t = a;
  20746. a = b;
  20747. b = t;
  20748. } else if (r === 0 || b.cmpn(1) === 0) {
  20749. break;
  20750. }
  20751. a.isub(b);
  20752. } while (true);
  20753. return b.iushln(shift);
  20754. };
  20755. // Invert number in the field F(num)
  20756. BN.prototype.invm = function invm(num) {
  20757. return this.egcd(num).a.umod(num);
  20758. };
  20759. BN.prototype.isEven = function isEven() {
  20760. return (this.words[0] & 1) === 0;
  20761. };
  20762. BN.prototype.isOdd = function isOdd() {
  20763. return (this.words[0] & 1) === 1;
  20764. };
  20765. // And first word and num
  20766. BN.prototype.andln = function andln(num) {
  20767. return this.words[0] & num;
  20768. };
  20769. // Increment at the bit position in-line
  20770. BN.prototype.bincn = function bincn(bit) {
  20771. assert(typeof bit === 'number');
  20772. var r = bit % 26;
  20773. var s = (bit - r) / 26;
  20774. var q = 1 << r;
  20775. // Fast case: bit is much higher than all existing words
  20776. if (this.length <= s) {
  20777. this._expand(s + 1);
  20778. this.words[s] |= q;
  20779. return this;
  20780. }
  20781. // Add bit and propagate, if needed
  20782. var carry = q;
  20783. for (var i = s; carry !== 0 && i < this.length; i++) {
  20784. var w = this.words[i] | 0;
  20785. w += carry;
  20786. carry = w >>> 26;
  20787. w &= 0x3ffffff;
  20788. this.words[i] = w;
  20789. }
  20790. if (carry !== 0) {
  20791. this.words[i] = carry;
  20792. this.length++;
  20793. }
  20794. return this;
  20795. };
  20796. BN.prototype.isZero = function isZero() {
  20797. return this.length === 1 && this.words[0] === 0;
  20798. };
  20799. BN.prototype.cmpn = function cmpn(num) {
  20800. var negative = num < 0;
  20801. if (this.negative !== 0 && !negative) return -1;
  20802. if (this.negative === 0 && negative) return 1;
  20803. this.strip();
  20804. var res;
  20805. if (this.length > 1) {
  20806. res = 1;
  20807. } else {
  20808. if (negative) {
  20809. num = -num;
  20810. }
  20811. assert(num <= 0x3ffffff, 'Number is too big');
  20812. var w = this.words[0] | 0;
  20813. res = w === num ? 0 : w < num ? -1 : 1;
  20814. }
  20815. if (this.negative !== 0) return -res | 0;
  20816. return res;
  20817. };
  20818. // Compare two numbers and return:
  20819. // 1 - if `this` > `num`
  20820. // 0 - if `this` == `num`
  20821. // -1 - if `this` < `num`
  20822. BN.prototype.cmp = function cmp(num) {
  20823. if (this.negative !== 0 && num.negative === 0) return -1;
  20824. if (this.negative === 0 && num.negative !== 0) return 1;
  20825. var res = this.ucmp(num);
  20826. if (this.negative !== 0) return -res | 0;
  20827. return res;
  20828. };
  20829. // Unsigned comparison
  20830. BN.prototype.ucmp = function ucmp(num) {
  20831. // At this point both numbers have the same sign
  20832. if (this.length > num.length) return 1;
  20833. if (this.length < num.length) return -1;
  20834. var res = 0;
  20835. for (var i = this.length - 1; i >= 0; i--) {
  20836. var a = this.words[i] | 0;
  20837. var b = num.words[i] | 0;
  20838. if (a === b) continue;
  20839. if (a < b) {
  20840. res = -1;
  20841. } else if (a > b) {
  20842. res = 1;
  20843. }
  20844. break;
  20845. }
  20846. return res;
  20847. };
  20848. BN.prototype.gtn = function gtn(num) {
  20849. return this.cmpn(num) === 1;
  20850. };
  20851. BN.prototype.gt = function gt(num) {
  20852. return this.cmp(num) === 1;
  20853. };
  20854. BN.prototype.gten = function gten(num) {
  20855. return this.cmpn(num) >= 0;
  20856. };
  20857. BN.prototype.gte = function gte(num) {
  20858. return this.cmp(num) >= 0;
  20859. };
  20860. BN.prototype.ltn = function ltn(num) {
  20861. return this.cmpn(num) === -1;
  20862. };
  20863. BN.prototype.lt = function lt(num) {
  20864. return this.cmp(num) === -1;
  20865. };
  20866. BN.prototype.lten = function lten(num) {
  20867. return this.cmpn(num) <= 0;
  20868. };
  20869. BN.prototype.lte = function lte(num) {
  20870. return this.cmp(num) <= 0;
  20871. };
  20872. BN.prototype.eqn = function eqn(num) {
  20873. return this.cmpn(num) === 0;
  20874. };
  20875. BN.prototype.eq = function eq(num) {
  20876. return this.cmp(num) === 0;
  20877. };
  20878. //
  20879. // A reduce context, could be using montgomery or something better, depending
  20880. // on the `m` itself.
  20881. //
  20882. BN.red = function red(num) {
  20883. return new Red(num);
  20884. };
  20885. BN.prototype.toRed = function toRed(ctx) {
  20886. assert(!this.red, 'Already a number in reduction context');
  20887. assert(this.negative === 0, 'red works only with positives');
  20888. return ctx.convertTo(this)._forceRed(ctx);
  20889. };
  20890. BN.prototype.fromRed = function fromRed() {
  20891. assert(this.red, 'fromRed works only with numbers in reduction context');
  20892. return this.red.convertFrom(this);
  20893. };
  20894. BN.prototype._forceRed = function _forceRed(ctx) {
  20895. this.red = ctx;
  20896. return this;
  20897. };
  20898. BN.prototype.forceRed = function forceRed(ctx) {
  20899. assert(!this.red, 'Already a number in reduction context');
  20900. return this._forceRed(ctx);
  20901. };
  20902. BN.prototype.redAdd = function redAdd(num) {
  20903. assert(this.red, 'redAdd works only with red numbers');
  20904. return this.red.add(this, num);
  20905. };
  20906. BN.prototype.redIAdd = function redIAdd(num) {
  20907. assert(this.red, 'redIAdd works only with red numbers');
  20908. return this.red.iadd(this, num);
  20909. };
  20910. BN.prototype.redSub = function redSub(num) {
  20911. assert(this.red, 'redSub works only with red numbers');
  20912. return this.red.sub(this, num);
  20913. };
  20914. BN.prototype.redISub = function redISub(num) {
  20915. assert(this.red, 'redISub works only with red numbers');
  20916. return this.red.isub(this, num);
  20917. };
  20918. BN.prototype.redShl = function redShl(num) {
  20919. assert(this.red, 'redShl works only with red numbers');
  20920. return this.red.shl(this, num);
  20921. };
  20922. BN.prototype.redMul = function redMul(num) {
  20923. assert(this.red, 'redMul works only with red numbers');
  20924. this.red._verify2(this, num);
  20925. return this.red.mul(this, num);
  20926. };
  20927. BN.prototype.redIMul = function redIMul(num) {
  20928. assert(this.red, 'redMul works only with red numbers');
  20929. this.red._verify2(this, num);
  20930. return this.red.imul(this, num);
  20931. };
  20932. BN.prototype.redSqr = function redSqr() {
  20933. assert(this.red, 'redSqr works only with red numbers');
  20934. this.red._verify1(this);
  20935. return this.red.sqr(this);
  20936. };
  20937. BN.prototype.redISqr = function redISqr() {
  20938. assert(this.red, 'redISqr works only with red numbers');
  20939. this.red._verify1(this);
  20940. return this.red.isqr(this);
  20941. };
  20942. // Square root over p
  20943. BN.prototype.redSqrt = function redSqrt() {
  20944. assert(this.red, 'redSqrt works only with red numbers');
  20945. this.red._verify1(this);
  20946. return this.red.sqrt(this);
  20947. };
  20948. BN.prototype.redInvm = function redInvm() {
  20949. assert(this.red, 'redInvm works only with red numbers');
  20950. this.red._verify1(this);
  20951. return this.red.invm(this);
  20952. };
  20953. // Return negative clone of `this` % `red modulo`
  20954. BN.prototype.redNeg = function redNeg() {
  20955. assert(this.red, 'redNeg works only with red numbers');
  20956. this.red._verify1(this);
  20957. return this.red.neg(this);
  20958. };
  20959. BN.prototype.redPow = function redPow(num) {
  20960. assert(this.red && !num.red, 'redPow(normalNum)');
  20961. this.red._verify1(this);
  20962. return this.red.pow(this, num);
  20963. };
  20964. // Prime numbers with efficient reduction
  20965. var primes = {
  20966. k256: null,
  20967. p224: null,
  20968. p192: null,
  20969. p25519: null
  20970. };
  20971. // Pseudo-Mersenne prime
  20972. function MPrime(name, p) {
  20973. // P = 2 ^ N - K
  20974. this.name = name;
  20975. this.p = new BN(p, 16);
  20976. this.n = this.p.bitLength();
  20977. this.k = new BN(1).iushln(this.n).isub(this.p);
  20978. this.tmp = this._tmp();
  20979. }
  20980. MPrime.prototype._tmp = function _tmp() {
  20981. var tmp = new BN(null);
  20982. tmp.words = new Array(Math.ceil(this.n / 13));
  20983. return tmp;
  20984. };
  20985. MPrime.prototype.ireduce = function ireduce(num) {
  20986. // Assumes that `num` is less than `P^2`
  20987. // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
  20988. var r = num;
  20989. var rlen;
  20990. do {
  20991. this.split(r, this.tmp);
  20992. r = this.imulK(r);
  20993. r = r.iadd(this.tmp);
  20994. rlen = r.bitLength();
  20995. } while (rlen > this.n);
  20996. var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
  20997. if (cmp === 0) {
  20998. r.words[0] = 0;
  20999. r.length = 1;
  21000. } else if (cmp > 0) {
  21001. r.isub(this.p);
  21002. } else {
  21003. if (r.strip !== undefined) {
  21004. // r is BN v4 instance
  21005. r.strip();
  21006. } else {
  21007. // r is BN v5 instance
  21008. r._strip();
  21009. }
  21010. }
  21011. return r;
  21012. };
  21013. MPrime.prototype.split = function split(input, out) {
  21014. input.iushrn(this.n, 0, out);
  21015. };
  21016. MPrime.prototype.imulK = function imulK(num) {
  21017. return num.imul(this.k);
  21018. };
  21019. function K256() {
  21020. MPrime.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  21021. }
  21022. inherits(K256, MPrime);
  21023. K256.prototype.split = function split(input, output) {
  21024. // 256 = 9 * 26 + 22
  21025. var mask = 0x3fffff;
  21026. var outLen = Math.min(input.length, 9);
  21027. for (var i = 0; i < outLen; i++) {
  21028. output.words[i] = input.words[i];
  21029. }
  21030. output.length = outLen;
  21031. if (input.length <= 9) {
  21032. input.words[0] = 0;
  21033. input.length = 1;
  21034. return;
  21035. }
  21036. // Shift by 9 limbs
  21037. var prev = input.words[9];
  21038. output.words[output.length++] = prev & mask;
  21039. for (i = 10; i < input.length; i++) {
  21040. var next = input.words[i] | 0;
  21041. input.words[i - 10] = (next & mask) << 4 | prev >>> 22;
  21042. prev = next;
  21043. }
  21044. prev >>>= 22;
  21045. input.words[i - 10] = prev;
  21046. if (prev === 0 && input.length > 10) {
  21047. input.length -= 10;
  21048. } else {
  21049. input.length -= 9;
  21050. }
  21051. };
  21052. K256.prototype.imulK = function imulK(num) {
  21053. // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
  21054. num.words[num.length] = 0;
  21055. num.words[num.length + 1] = 0;
  21056. num.length += 2;
  21057. // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
  21058. var lo = 0;
  21059. for (var i = 0; i < num.length; i++) {
  21060. var w = num.words[i] | 0;
  21061. lo += w * 0x3d1;
  21062. num.words[i] = lo & 0x3ffffff;
  21063. lo = w * 0x40 + (lo / 0x4000000 | 0);
  21064. }
  21065. // Fast length reduction
  21066. if (num.words[num.length - 1] === 0) {
  21067. num.length--;
  21068. if (num.words[num.length - 1] === 0) {
  21069. num.length--;
  21070. }
  21071. }
  21072. return num;
  21073. };
  21074. function P224() {
  21075. MPrime.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  21076. }
  21077. inherits(P224, MPrime);
  21078. function P192() {
  21079. MPrime.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  21080. }
  21081. inherits(P192, MPrime);
  21082. function P25519() {
  21083. // 2 ^ 255 - 19
  21084. MPrime.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  21085. }
  21086. inherits(P25519, MPrime);
  21087. P25519.prototype.imulK = function imulK(num) {
  21088. // K = 0x13
  21089. var carry = 0;
  21090. for (var i = 0; i < num.length; i++) {
  21091. var hi = (num.words[i] | 0) * 0x13 + carry;
  21092. var lo = hi & 0x3ffffff;
  21093. hi >>>= 26;
  21094. num.words[i] = lo;
  21095. carry = hi;
  21096. }
  21097. if (carry !== 0) {
  21098. num.words[num.length++] = carry;
  21099. }
  21100. return num;
  21101. };
  21102. // Exported mostly for testing purposes, use plain name instead
  21103. BN._prime = function prime(name) {
  21104. // Cached version of prime
  21105. if (primes[name]) return primes[name];
  21106. var prime;
  21107. if (name === 'k256') {
  21108. prime = new K256();
  21109. } else if (name === 'p224') {
  21110. prime = new P224();
  21111. } else if (name === 'p192') {
  21112. prime = new P192();
  21113. } else if (name === 'p25519') {
  21114. prime = new P25519();
  21115. } else {
  21116. throw new Error('Unknown prime ' + name);
  21117. }
  21118. primes[name] = prime;
  21119. return prime;
  21120. };
  21121. //
  21122. // Base reduction engine
  21123. //
  21124. function Red(m) {
  21125. if (typeof m === 'string') {
  21126. var prime = BN._prime(m);
  21127. this.m = prime.p;
  21128. this.prime = prime;
  21129. } else {
  21130. assert(m.gtn(1), 'modulus must be greater than 1');
  21131. this.m = m;
  21132. this.prime = null;
  21133. }
  21134. }
  21135. Red.prototype._verify1 = function _verify1(a) {
  21136. assert(a.negative === 0, 'red works only with positives');
  21137. assert(a.red, 'red works only with red numbers');
  21138. };
  21139. Red.prototype._verify2 = function _verify2(a, b) {
  21140. assert((a.negative | b.negative) === 0, 'red works only with positives');
  21141. assert(a.red && a.red === b.red, 'red works only with red numbers');
  21142. };
  21143. Red.prototype.imod = function imod(a) {
  21144. if (this.prime) return this.prime.ireduce(a)._forceRed(this);
  21145. return a.umod(this.m)._forceRed(this);
  21146. };
  21147. Red.prototype.neg = function neg(a) {
  21148. if (a.isZero()) {
  21149. return a.clone();
  21150. }
  21151. return this.m.sub(a)._forceRed(this);
  21152. };
  21153. Red.prototype.add = function add(a, b) {
  21154. this._verify2(a, b);
  21155. var res = a.add(b);
  21156. if (res.cmp(this.m) >= 0) {
  21157. res.isub(this.m);
  21158. }
  21159. return res._forceRed(this);
  21160. };
  21161. Red.prototype.iadd = function iadd(a, b) {
  21162. this._verify2(a, b);
  21163. var res = a.iadd(b);
  21164. if (res.cmp(this.m) >= 0) {
  21165. res.isub(this.m);
  21166. }
  21167. return res;
  21168. };
  21169. Red.prototype.sub = function sub(a, b) {
  21170. this._verify2(a, b);
  21171. var res = a.sub(b);
  21172. if (res.cmpn(0) < 0) {
  21173. res.iadd(this.m);
  21174. }
  21175. return res._forceRed(this);
  21176. };
  21177. Red.prototype.isub = function isub(a, b) {
  21178. this._verify2(a, b);
  21179. var res = a.isub(b);
  21180. if (res.cmpn(0) < 0) {
  21181. res.iadd(this.m);
  21182. }
  21183. return res;
  21184. };
  21185. Red.prototype.shl = function shl(a, num) {
  21186. this._verify1(a);
  21187. return this.imod(a.ushln(num));
  21188. };
  21189. Red.prototype.imul = function imul(a, b) {
  21190. this._verify2(a, b);
  21191. return this.imod(a.imul(b));
  21192. };
  21193. Red.prototype.mul = function mul(a, b) {
  21194. this._verify2(a, b);
  21195. return this.imod(a.mul(b));
  21196. };
  21197. Red.prototype.isqr = function isqr(a) {
  21198. return this.imul(a, a.clone());
  21199. };
  21200. Red.prototype.sqr = function sqr(a) {
  21201. return this.mul(a, a);
  21202. };
  21203. Red.prototype.sqrt = function sqrt(a) {
  21204. if (a.isZero()) return a.clone();
  21205. var mod3 = this.m.andln(3);
  21206. assert(mod3 % 2 === 1);
  21207. // Fast case
  21208. if (mod3 === 3) {
  21209. var pow = this.m.add(new BN(1)).iushrn(2);
  21210. return this.pow(a, pow);
  21211. }
  21212. // Tonelli-Shanks algorithm (Totally unoptimized and slow)
  21213. //
  21214. // Find Q and S, that Q * 2 ^ S = (P - 1)
  21215. var q = this.m.subn(1);
  21216. var s = 0;
  21217. while (!q.isZero() && q.andln(1) === 0) {
  21218. s++;
  21219. q.iushrn(1);
  21220. }
  21221. assert(!q.isZero());
  21222. var one = new BN(1).toRed(this);
  21223. var nOne = one.redNeg();
  21224. // Find quadratic non-residue
  21225. // NOTE: Max is such because of generalized Riemann hypothesis.
  21226. var lpow = this.m.subn(1).iushrn(1);
  21227. var z = this.m.bitLength();
  21228. z = new BN(2 * z * z).toRed(this);
  21229. while (this.pow(z, lpow).cmp(nOne) !== 0) {
  21230. z.redIAdd(nOne);
  21231. }
  21232. var c = this.pow(z, q);
  21233. var r = this.pow(a, q.addn(1).iushrn(1));
  21234. var t = this.pow(a, q);
  21235. var m = s;
  21236. while (t.cmp(one) !== 0) {
  21237. var tmp = t;
  21238. for (var i = 0; tmp.cmp(one) !== 0; i++) {
  21239. tmp = tmp.redSqr();
  21240. }
  21241. assert(i < m);
  21242. var b = this.pow(c, new BN(1).iushln(m - i - 1));
  21243. r = r.redMul(b);
  21244. c = b.redSqr();
  21245. t = t.redMul(c);
  21246. m = i;
  21247. }
  21248. return r;
  21249. };
  21250. Red.prototype.invm = function invm(a) {
  21251. var inv = a._invmp(this.m);
  21252. if (inv.negative !== 0) {
  21253. inv.negative = 0;
  21254. return this.imod(inv).redNeg();
  21255. } else {
  21256. return this.imod(inv);
  21257. }
  21258. };
  21259. Red.prototype.pow = function pow(a, num) {
  21260. if (num.isZero()) return new BN(1).toRed(this);
  21261. if (num.cmpn(1) === 0) return a.clone();
  21262. var windowSize = 4;
  21263. var wnd = new Array(1 << windowSize);
  21264. wnd[0] = new BN(1).toRed(this);
  21265. wnd[1] = a;
  21266. for (var i = 2; i < wnd.length; i++) {
  21267. wnd[i] = this.mul(wnd[i - 1], a);
  21268. }
  21269. var res = wnd[0];
  21270. var current = 0;
  21271. var currentLen = 0;
  21272. var start = num.bitLength() % 26;
  21273. if (start === 0) {
  21274. start = 26;
  21275. }
  21276. for (i = num.length - 1; i >= 0; i--) {
  21277. var word = num.words[i];
  21278. for (var j = start - 1; j >= 0; j--) {
  21279. var bit = word >> j & 1;
  21280. if (res !== wnd[0]) {
  21281. res = this.sqr(res);
  21282. }
  21283. if (bit === 0 && current === 0) {
  21284. currentLen = 0;
  21285. continue;
  21286. }
  21287. current <<= 1;
  21288. current |= bit;
  21289. currentLen++;
  21290. if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
  21291. res = this.mul(res, wnd[current]);
  21292. currentLen = 0;
  21293. current = 0;
  21294. }
  21295. start = 26;
  21296. }
  21297. return res;
  21298. };
  21299. Red.prototype.convertTo = function convertTo(num) {
  21300. var r = num.umod(this.m);
  21301. return r === num ? r.clone() : r;
  21302. };
  21303. Red.prototype.convertFrom = function convertFrom(num) {
  21304. var res = num.clone();
  21305. res.red = null;
  21306. return res;
  21307. };
  21308. //
  21309. // Montgomery method engine
  21310. //
  21311. BN.mont = function mont(num) {
  21312. return new Mont(num);
  21313. };
  21314. function Mont(m) {
  21315. Red.call(this, m);
  21316. this.shift = this.m.bitLength();
  21317. if (this.shift % 26 !== 0) {
  21318. this.shift += 26 - this.shift % 26;
  21319. }
  21320. this.r = new BN(1).iushln(this.shift);
  21321. this.r2 = this.imod(this.r.sqr());
  21322. this.rinv = this.r._invmp(this.m);
  21323. this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
  21324. this.minv = this.minv.umod(this.r);
  21325. this.minv = this.r.sub(this.minv);
  21326. }
  21327. inherits(Mont, Red);
  21328. Mont.prototype.convertTo = function convertTo(num) {
  21329. return this.imod(num.ushln(this.shift));
  21330. };
  21331. Mont.prototype.convertFrom = function convertFrom(num) {
  21332. var r = this.imod(num.mul(this.rinv));
  21333. r.red = null;
  21334. return r;
  21335. };
  21336. Mont.prototype.imul = function imul(a, b) {
  21337. if (a.isZero() || b.isZero()) {
  21338. a.words[0] = 0;
  21339. a.length = 1;
  21340. return a;
  21341. }
  21342. var t = a.imul(b);
  21343. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  21344. var u = t.isub(c).iushrn(this.shift);
  21345. var res = u;
  21346. if (u.cmp(this.m) >= 0) {
  21347. res = u.isub(this.m);
  21348. } else if (u.cmpn(0) < 0) {
  21349. res = u.iadd(this.m);
  21350. }
  21351. return res._forceRed(this);
  21352. };
  21353. Mont.prototype.mul = function mul(a, b) {
  21354. if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
  21355. var t = a.mul(b);
  21356. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  21357. var u = t.isub(c).iushrn(this.shift);
  21358. var res = u;
  21359. if (u.cmp(this.m) >= 0) {
  21360. res = u.isub(this.m);
  21361. } else if (u.cmpn(0) < 0) {
  21362. res = u.iadd(this.m);
  21363. }
  21364. return res._forceRed(this);
  21365. };
  21366. Mont.prototype.invm = function invm(a) {
  21367. // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
  21368. var res = this.imod(a._invmp(this.m).mul(this.r2));
  21369. return res._forceRed(this);
  21370. };
  21371. })(typeof module === 'undefined' || module, void 0);
  21372. },{"buffer":188}],185:[function(require,module,exports){
  21373. 'use strict';
  21374. exports.byteLength = byteLength;
  21375. exports.toByteArray = toByteArray;
  21376. exports.fromByteArray = fromByteArray;
  21377. var lookup = [];
  21378. var revLookup = [];
  21379. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  21380. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  21381. for (var i = 0, len = code.length; i < len; ++i) {
  21382. lookup[i] = code[i];
  21383. revLookup[code.charCodeAt(i)] = i;
  21384. }
  21385. // Support decoding URL-safe base64 strings, as Node.js does.
  21386. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  21387. revLookup['-'.charCodeAt(0)] = 62;
  21388. revLookup['_'.charCodeAt(0)] = 63;
  21389. function getLens(b64) {
  21390. var len = b64.length;
  21391. if (len % 4 > 0) {
  21392. throw new Error('Invalid string. Length must be a multiple of 4');
  21393. }
  21394. // Trim off extra bytes after placeholder bytes are found
  21395. // See: https://github.com/beatgammit/base64-js/issues/42
  21396. var validLen = b64.indexOf('=');
  21397. if (validLen === -1) validLen = len;
  21398. var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
  21399. return [validLen, placeHoldersLen];
  21400. }
  21401. // base64 is 4/3 + up to two characters of the original data
  21402. function byteLength(b64) {
  21403. var lens = getLens(b64);
  21404. var validLen = lens[0];
  21405. var placeHoldersLen = lens[1];
  21406. return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  21407. }
  21408. function _byteLength(b64, validLen, placeHoldersLen) {
  21409. return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  21410. }
  21411. function toByteArray(b64) {
  21412. var tmp;
  21413. var lens = getLens(b64);
  21414. var validLen = lens[0];
  21415. var placeHoldersLen = lens[1];
  21416. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
  21417. var curByte = 0;
  21418. // if there are placeholders, only get up to the last complete 4 chars
  21419. var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
  21420. var i;
  21421. for (i = 0; i < len; i += 4) {
  21422. tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
  21423. arr[curByte++] = tmp >> 16 & 0xFF;
  21424. arr[curByte++] = tmp >> 8 & 0xFF;
  21425. arr[curByte++] = tmp & 0xFF;
  21426. }
  21427. if (placeHoldersLen === 2) {
  21428. tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
  21429. arr[curByte++] = tmp & 0xFF;
  21430. }
  21431. if (placeHoldersLen === 1) {
  21432. tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
  21433. arr[curByte++] = tmp >> 8 & 0xFF;
  21434. arr[curByte++] = tmp & 0xFF;
  21435. }
  21436. return arr;
  21437. }
  21438. function tripletToBase64(num) {
  21439. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
  21440. }
  21441. function encodeChunk(uint8, start, end) {
  21442. var tmp;
  21443. var output = [];
  21444. for (var i = start; i < end; i += 3) {
  21445. tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF);
  21446. output.push(tripletToBase64(tmp));
  21447. }
  21448. return output.join('');
  21449. }
  21450. function fromByteArray(uint8) {
  21451. var tmp;
  21452. var len = uint8.length;
  21453. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  21454. var parts = [];
  21455. var maxChunkLength = 16383; // must be multiple of 3
  21456. // go through the array every three bytes, we'll deal with trailing stuff later
  21457. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  21458. parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
  21459. }
  21460. // pad the end with zeros, but make sure to not forget the extra bytes
  21461. if (extraBytes === 1) {
  21462. tmp = uint8[len - 1];
  21463. parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '==');
  21464. } else if (extraBytes === 2) {
  21465. tmp = (uint8[len - 2] << 8) + uint8[len - 1];
  21466. parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '=');
  21467. }
  21468. return parts.join('');
  21469. }
  21470. },{}],186:[function(require,module,exports){
  21471. "use strict";
  21472. (function (module, exports) {
  21473. 'use strict';
  21474. // Utils
  21475. function assert(val, msg) {
  21476. if (!val) throw new Error(msg || 'Assertion failed');
  21477. }
  21478. // Could use `inherits` module, but don't want to move from single file
  21479. // architecture yet.
  21480. function inherits(ctor, superCtor) {
  21481. ctor.super_ = superCtor;
  21482. var TempCtor = function () {};
  21483. TempCtor.prototype = superCtor.prototype;
  21484. ctor.prototype = new TempCtor();
  21485. ctor.prototype.constructor = ctor;
  21486. }
  21487. // BN
  21488. function BN(number, base, endian) {
  21489. if (BN.isBN(number)) {
  21490. return number;
  21491. }
  21492. this.negative = 0;
  21493. this.words = null;
  21494. this.length = 0;
  21495. // Reduction context
  21496. this.red = null;
  21497. if (number !== null) {
  21498. if (base === 'le' || base === 'be') {
  21499. endian = base;
  21500. base = 10;
  21501. }
  21502. this._init(number || 0, base || 10, endian || 'be');
  21503. }
  21504. }
  21505. if (typeof module === 'object') {
  21506. module.exports = BN;
  21507. } else {
  21508. exports.BN = BN;
  21509. }
  21510. BN.BN = BN;
  21511. BN.wordSize = 26;
  21512. var Buffer;
  21513. try {
  21514. if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
  21515. Buffer = window.Buffer;
  21516. } else {
  21517. Buffer = require('buffer').Buffer;
  21518. }
  21519. } catch (e) {}
  21520. BN.isBN = function isBN(num) {
  21521. if (num instanceof BN) {
  21522. return true;
  21523. }
  21524. return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  21525. };
  21526. BN.max = function max(left, right) {
  21527. if (left.cmp(right) > 0) return left;
  21528. return right;
  21529. };
  21530. BN.min = function min(left, right) {
  21531. if (left.cmp(right) < 0) return left;
  21532. return right;
  21533. };
  21534. BN.prototype._init = function init(number, base, endian) {
  21535. if (typeof number === 'number') {
  21536. return this._initNumber(number, base, endian);
  21537. }
  21538. if (typeof number === 'object') {
  21539. return this._initArray(number, base, endian);
  21540. }
  21541. if (base === 'hex') {
  21542. base = 16;
  21543. }
  21544. assert(base === (base | 0) && base >= 2 && base <= 36);
  21545. number = number.toString().replace(/\s+/g, '');
  21546. var start = 0;
  21547. if (number[0] === '-') {
  21548. start++;
  21549. this.negative = 1;
  21550. }
  21551. if (start < number.length) {
  21552. if (base === 16) {
  21553. this._parseHex(number, start, endian);
  21554. } else {
  21555. this._parseBase(number, base, start);
  21556. if (endian === 'le') {
  21557. this._initArray(this.toArray(), base, endian);
  21558. }
  21559. }
  21560. }
  21561. };
  21562. BN.prototype._initNumber = function _initNumber(number, base, endian) {
  21563. if (number < 0) {
  21564. this.negative = 1;
  21565. number = -number;
  21566. }
  21567. if (number < 0x4000000) {
  21568. this.words = [number & 0x3ffffff];
  21569. this.length = 1;
  21570. } else if (number < 0x10000000000000) {
  21571. this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff];
  21572. this.length = 2;
  21573. } else {
  21574. assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
  21575. this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff, 1];
  21576. this.length = 3;
  21577. }
  21578. if (endian !== 'le') return;
  21579. // Reverse the bytes
  21580. this._initArray(this.toArray(), base, endian);
  21581. };
  21582. BN.prototype._initArray = function _initArray(number, base, endian) {
  21583. // Perhaps a Uint8Array
  21584. assert(typeof number.length === 'number');
  21585. if (number.length <= 0) {
  21586. this.words = [0];
  21587. this.length = 1;
  21588. return this;
  21589. }
  21590. this.length = Math.ceil(number.length / 3);
  21591. this.words = new Array(this.length);
  21592. for (var i = 0; i < this.length; i++) {
  21593. this.words[i] = 0;
  21594. }
  21595. var j, w;
  21596. var off = 0;
  21597. if (endian === 'be') {
  21598. for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
  21599. w = number[i] | number[i - 1] << 8 | number[i - 2] << 16;
  21600. this.words[j] |= w << off & 0x3ffffff;
  21601. this.words[j + 1] = w >>> 26 - off & 0x3ffffff;
  21602. off += 24;
  21603. if (off >= 26) {
  21604. off -= 26;
  21605. j++;
  21606. }
  21607. }
  21608. } else if (endian === 'le') {
  21609. for (i = 0, j = 0; i < number.length; i += 3) {
  21610. w = number[i] | number[i + 1] << 8 | number[i + 2] << 16;
  21611. this.words[j] |= w << off & 0x3ffffff;
  21612. this.words[j + 1] = w >>> 26 - off & 0x3ffffff;
  21613. off += 24;
  21614. if (off >= 26) {
  21615. off -= 26;
  21616. j++;
  21617. }
  21618. }
  21619. }
  21620. return this._strip();
  21621. };
  21622. function parseHex4Bits(string, index) {
  21623. var c = string.charCodeAt(index);
  21624. // '0' - '9'
  21625. if (c >= 48 && c <= 57) {
  21626. return c - 48;
  21627. // 'A' - 'F'
  21628. } else if (c >= 65 && c <= 70) {
  21629. return c - 55;
  21630. // 'a' - 'f'
  21631. } else if (c >= 97 && c <= 102) {
  21632. return c - 87;
  21633. } else {
  21634. assert(false, 'Invalid character in ' + string);
  21635. }
  21636. }
  21637. function parseHexByte(string, lowerBound, index) {
  21638. var r = parseHex4Bits(string, index);
  21639. if (index - 1 >= lowerBound) {
  21640. r |= parseHex4Bits(string, index - 1) << 4;
  21641. }
  21642. return r;
  21643. }
  21644. BN.prototype._parseHex = function _parseHex(number, start, endian) {
  21645. // Create possibly bigger array to ensure that it fits the number
  21646. this.length = Math.ceil((number.length - start) / 6);
  21647. this.words = new Array(this.length);
  21648. for (var i = 0; i < this.length; i++) {
  21649. this.words[i] = 0;
  21650. }
  21651. // 24-bits chunks
  21652. var off = 0;
  21653. var j = 0;
  21654. var w;
  21655. if (endian === 'be') {
  21656. for (i = number.length - 1; i >= start; i -= 2) {
  21657. w = parseHexByte(number, start, i) << off;
  21658. this.words[j] |= w & 0x3ffffff;
  21659. if (off >= 18) {
  21660. off -= 18;
  21661. j += 1;
  21662. this.words[j] |= w >>> 26;
  21663. } else {
  21664. off += 8;
  21665. }
  21666. }
  21667. } else {
  21668. var parseLength = number.length - start;
  21669. for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {
  21670. w = parseHexByte(number, start, i) << off;
  21671. this.words[j] |= w & 0x3ffffff;
  21672. if (off >= 18) {
  21673. off -= 18;
  21674. j += 1;
  21675. this.words[j] |= w >>> 26;
  21676. } else {
  21677. off += 8;
  21678. }
  21679. }
  21680. }
  21681. this._strip();
  21682. };
  21683. function parseBase(str, start, end, mul) {
  21684. var r = 0;
  21685. var b = 0;
  21686. var len = Math.min(str.length, end);
  21687. for (var i = start; i < len; i++) {
  21688. var c = str.charCodeAt(i) - 48;
  21689. r *= mul;
  21690. // 'a'
  21691. if (c >= 49) {
  21692. b = c - 49 + 0xa;
  21693. // 'A'
  21694. } else if (c >= 17) {
  21695. b = c - 17 + 0xa;
  21696. // '0' - '9'
  21697. } else {
  21698. b = c;
  21699. }
  21700. assert(c >= 0 && b < mul, 'Invalid character');
  21701. r += b;
  21702. }
  21703. return r;
  21704. }
  21705. BN.prototype._parseBase = function _parseBase(number, base, start) {
  21706. // Initialize as zero
  21707. this.words = [0];
  21708. this.length = 1;
  21709. // Find length of limb in base
  21710. for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
  21711. limbLen++;
  21712. }
  21713. limbLen--;
  21714. limbPow = limbPow / base | 0;
  21715. var total = number.length - start;
  21716. var mod = total % limbLen;
  21717. var end = Math.min(total, total - mod) + start;
  21718. var word = 0;
  21719. for (var i = start; i < end; i += limbLen) {
  21720. word = parseBase(number, i, i + limbLen, base);
  21721. this.imuln(limbPow);
  21722. if (this.words[0] + word < 0x4000000) {
  21723. this.words[0] += word;
  21724. } else {
  21725. this._iaddn(word);
  21726. }
  21727. }
  21728. if (mod !== 0) {
  21729. var pow = 1;
  21730. word = parseBase(number, i, number.length, base);
  21731. for (i = 0; i < mod; i++) {
  21732. pow *= base;
  21733. }
  21734. this.imuln(pow);
  21735. if (this.words[0] + word < 0x4000000) {
  21736. this.words[0] += word;
  21737. } else {
  21738. this._iaddn(word);
  21739. }
  21740. }
  21741. this._strip();
  21742. };
  21743. BN.prototype.copy = function copy(dest) {
  21744. dest.words = new Array(this.length);
  21745. for (var i = 0; i < this.length; i++) {
  21746. dest.words[i] = this.words[i];
  21747. }
  21748. dest.length = this.length;
  21749. dest.negative = this.negative;
  21750. dest.red = this.red;
  21751. };
  21752. function move(dest, src) {
  21753. dest.words = src.words;
  21754. dest.length = src.length;
  21755. dest.negative = src.negative;
  21756. dest.red = src.red;
  21757. }
  21758. BN.prototype._move = function _move(dest) {
  21759. move(dest, this);
  21760. };
  21761. BN.prototype.clone = function clone() {
  21762. var r = new BN(null);
  21763. this.copy(r);
  21764. return r;
  21765. };
  21766. BN.prototype._expand = function _expand(size) {
  21767. while (this.length < size) {
  21768. this.words[this.length++] = 0;
  21769. }
  21770. return this;
  21771. };
  21772. // Remove leading `0` from `this`
  21773. BN.prototype._strip = function strip() {
  21774. while (this.length > 1 && this.words[this.length - 1] === 0) {
  21775. this.length--;
  21776. }
  21777. return this._normSign();
  21778. };
  21779. BN.prototype._normSign = function _normSign() {
  21780. // -0 = 0
  21781. if (this.length === 1 && this.words[0] === 0) {
  21782. this.negative = 0;
  21783. }
  21784. return this;
  21785. };
  21786. // Check Symbol.for because not everywhere where Symbol defined
  21787. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility
  21788. if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {
  21789. try {
  21790. BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;
  21791. } catch (e) {
  21792. BN.prototype.inspect = inspect;
  21793. }
  21794. } else {
  21795. BN.prototype.inspect = inspect;
  21796. }
  21797. function inspect() {
  21798. return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  21799. }
  21800. /*
  21801. var zeros = [];
  21802. var groupSizes = [];
  21803. var groupBases = [];
  21804. var s = '';
  21805. var i = -1;
  21806. while (++i < BN.wordSize) {
  21807. zeros[i] = s;
  21808. s += '0';
  21809. }
  21810. groupSizes[0] = 0;
  21811. groupSizes[1] = 0;
  21812. groupBases[0] = 0;
  21813. groupBases[1] = 0;
  21814. var base = 2 - 1;
  21815. while (++base < 36 + 1) {
  21816. var groupSize = 0;
  21817. var groupBase = 1;
  21818. while (groupBase < (1 << BN.wordSize) / base) {
  21819. groupBase *= base;
  21820. groupSize += 1;
  21821. }
  21822. groupSizes[base] = groupSize;
  21823. groupBases[base] = groupBase;
  21824. }
  21825. */
  21826. var zeros = ['', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000'];
  21827. var groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5];
  21828. var groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176];
  21829. BN.prototype.toString = function toString(base, padding) {
  21830. base = base || 10;
  21831. padding = padding | 0 || 1;
  21832. var out;
  21833. if (base === 16 || base === 'hex') {
  21834. out = '';
  21835. var off = 0;
  21836. var carry = 0;
  21837. for (var i = 0; i < this.length; i++) {
  21838. var w = this.words[i];
  21839. var word = ((w << off | carry) & 0xffffff).toString(16);
  21840. carry = w >>> 24 - off & 0xffffff;
  21841. off += 2;
  21842. if (off >= 26) {
  21843. off -= 26;
  21844. i--;
  21845. }
  21846. if (carry !== 0 || i !== this.length - 1) {
  21847. out = zeros[6 - word.length] + word + out;
  21848. } else {
  21849. out = word + out;
  21850. }
  21851. }
  21852. if (carry !== 0) {
  21853. out = carry.toString(16) + out;
  21854. }
  21855. while (out.length % padding !== 0) {
  21856. out = '0' + out;
  21857. }
  21858. if (this.negative !== 0) {
  21859. out = '-' + out;
  21860. }
  21861. return out;
  21862. }
  21863. if (base === (base | 0) && base >= 2 && base <= 36) {
  21864. // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
  21865. var groupSize = groupSizes[base];
  21866. // var groupBase = Math.pow(base, groupSize);
  21867. var groupBase = groupBases[base];
  21868. out = '';
  21869. var c = this.clone();
  21870. c.negative = 0;
  21871. while (!c.isZero()) {
  21872. var r = c.modrn(groupBase).toString(base);
  21873. c = c.idivn(groupBase);
  21874. if (!c.isZero()) {
  21875. out = zeros[groupSize - r.length] + r + out;
  21876. } else {
  21877. out = r + out;
  21878. }
  21879. }
  21880. if (this.isZero()) {
  21881. out = '0' + out;
  21882. }
  21883. while (out.length % padding !== 0) {
  21884. out = '0' + out;
  21885. }
  21886. if (this.negative !== 0) {
  21887. out = '-' + out;
  21888. }
  21889. return out;
  21890. }
  21891. assert(false, 'Base should be between 2 and 36');
  21892. };
  21893. BN.prototype.toNumber = function toNumber() {
  21894. var ret = this.words[0];
  21895. if (this.length === 2) {
  21896. ret += this.words[1] * 0x4000000;
  21897. } else if (this.length === 3 && this.words[2] === 0x01) {
  21898. // NOTE: at this stage it is known that the top bit is set
  21899. ret += 0x10000000000000 + this.words[1] * 0x4000000;
  21900. } else if (this.length > 2) {
  21901. assert(false, 'Number can only safely store up to 53 bits');
  21902. }
  21903. return this.negative !== 0 ? -ret : ret;
  21904. };
  21905. BN.prototype.toJSON = function toJSON() {
  21906. return this.toString(16, 2);
  21907. };
  21908. if (Buffer) {
  21909. BN.prototype.toBuffer = function toBuffer(endian, length) {
  21910. return this.toArrayLike(Buffer, endian, length);
  21911. };
  21912. }
  21913. BN.prototype.toArray = function toArray(endian, length) {
  21914. return this.toArrayLike(Array, endian, length);
  21915. };
  21916. var allocate = function allocate(ArrayType, size) {
  21917. if (ArrayType.allocUnsafe) {
  21918. return ArrayType.allocUnsafe(size);
  21919. }
  21920. return new ArrayType(size);
  21921. };
  21922. BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) {
  21923. this._strip();
  21924. var byteLength = this.byteLength();
  21925. var reqLength = length || Math.max(1, byteLength);
  21926. assert(byteLength <= reqLength, 'byte array longer than desired length');
  21927. assert(reqLength > 0, 'Requested array length <= 0');
  21928. var res = allocate(ArrayType, reqLength);
  21929. var postfix = endian === 'le' ? 'LE' : 'BE';
  21930. this['_toArrayLike' + postfix](res, byteLength);
  21931. return res;
  21932. };
  21933. BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) {
  21934. var position = 0;
  21935. var carry = 0;
  21936. for (var i = 0, shift = 0; i < this.length; i++) {
  21937. var word = this.words[i] << shift | carry;
  21938. res[position++] = word & 0xff;
  21939. if (position < res.length) {
  21940. res[position++] = word >> 8 & 0xff;
  21941. }
  21942. if (position < res.length) {
  21943. res[position++] = word >> 16 & 0xff;
  21944. }
  21945. if (shift === 6) {
  21946. if (position < res.length) {
  21947. res[position++] = word >> 24 & 0xff;
  21948. }
  21949. carry = 0;
  21950. shift = 0;
  21951. } else {
  21952. carry = word >>> 24;
  21953. shift += 2;
  21954. }
  21955. }
  21956. if (position < res.length) {
  21957. res[position++] = carry;
  21958. while (position < res.length) {
  21959. res[position++] = 0;
  21960. }
  21961. }
  21962. };
  21963. BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) {
  21964. var position = res.length - 1;
  21965. var carry = 0;
  21966. for (var i = 0, shift = 0; i < this.length; i++) {
  21967. var word = this.words[i] << shift | carry;
  21968. res[position--] = word & 0xff;
  21969. if (position >= 0) {
  21970. res[position--] = word >> 8 & 0xff;
  21971. }
  21972. if (position >= 0) {
  21973. res[position--] = word >> 16 & 0xff;
  21974. }
  21975. if (shift === 6) {
  21976. if (position >= 0) {
  21977. res[position--] = word >> 24 & 0xff;
  21978. }
  21979. carry = 0;
  21980. shift = 0;
  21981. } else {
  21982. carry = word >>> 24;
  21983. shift += 2;
  21984. }
  21985. }
  21986. if (position >= 0) {
  21987. res[position--] = carry;
  21988. while (position >= 0) {
  21989. res[position--] = 0;
  21990. }
  21991. }
  21992. };
  21993. if (Math.clz32) {
  21994. BN.prototype._countBits = function _countBits(w) {
  21995. return 32 - Math.clz32(w);
  21996. };
  21997. } else {
  21998. BN.prototype._countBits = function _countBits(w) {
  21999. var t = w;
  22000. var r = 0;
  22001. if (t >= 0x1000) {
  22002. r += 13;
  22003. t >>>= 13;
  22004. }
  22005. if (t >= 0x40) {
  22006. r += 7;
  22007. t >>>= 7;
  22008. }
  22009. if (t >= 0x8) {
  22010. r += 4;
  22011. t >>>= 4;
  22012. }
  22013. if (t >= 0x02) {
  22014. r += 2;
  22015. t >>>= 2;
  22016. }
  22017. return r + t;
  22018. };
  22019. }
  22020. BN.prototype._zeroBits = function _zeroBits(w) {
  22021. // Short-cut
  22022. if (w === 0) return 26;
  22023. var t = w;
  22024. var r = 0;
  22025. if ((t & 0x1fff) === 0) {
  22026. r += 13;
  22027. t >>>= 13;
  22028. }
  22029. if ((t & 0x7f) === 0) {
  22030. r += 7;
  22031. t >>>= 7;
  22032. }
  22033. if ((t & 0xf) === 0) {
  22034. r += 4;
  22035. t >>>= 4;
  22036. }
  22037. if ((t & 0x3) === 0) {
  22038. r += 2;
  22039. t >>>= 2;
  22040. }
  22041. if ((t & 0x1) === 0) {
  22042. r++;
  22043. }
  22044. return r;
  22045. };
  22046. // Return number of used bits in a BN
  22047. BN.prototype.bitLength = function bitLength() {
  22048. var w = this.words[this.length - 1];
  22049. var hi = this._countBits(w);
  22050. return (this.length - 1) * 26 + hi;
  22051. };
  22052. function toBitArray(num) {
  22053. var w = new Array(num.bitLength());
  22054. for (var bit = 0; bit < w.length; bit++) {
  22055. var off = bit / 26 | 0;
  22056. var wbit = bit % 26;
  22057. w[bit] = num.words[off] >>> wbit & 0x01;
  22058. }
  22059. return w;
  22060. }
  22061. // Number of trailing zero bits
  22062. BN.prototype.zeroBits = function zeroBits() {
  22063. if (this.isZero()) return 0;
  22064. var r = 0;
  22065. for (var i = 0; i < this.length; i++) {
  22066. var b = this._zeroBits(this.words[i]);
  22067. r += b;
  22068. if (b !== 26) break;
  22069. }
  22070. return r;
  22071. };
  22072. BN.prototype.byteLength = function byteLength() {
  22073. return Math.ceil(this.bitLength() / 8);
  22074. };
  22075. BN.prototype.toTwos = function toTwos(width) {
  22076. if (this.negative !== 0) {
  22077. return this.abs().inotn(width).iaddn(1);
  22078. }
  22079. return this.clone();
  22080. };
  22081. BN.prototype.fromTwos = function fromTwos(width) {
  22082. if (this.testn(width - 1)) {
  22083. return this.notn(width).iaddn(1).ineg();
  22084. }
  22085. return this.clone();
  22086. };
  22087. BN.prototype.isNeg = function isNeg() {
  22088. return this.negative !== 0;
  22089. };
  22090. // Return negative clone of `this`
  22091. BN.prototype.neg = function neg() {
  22092. return this.clone().ineg();
  22093. };
  22094. BN.prototype.ineg = function ineg() {
  22095. if (!this.isZero()) {
  22096. this.negative ^= 1;
  22097. }
  22098. return this;
  22099. };
  22100. // Or `num` with `this` in-place
  22101. BN.prototype.iuor = function iuor(num) {
  22102. while (this.length < num.length) {
  22103. this.words[this.length++] = 0;
  22104. }
  22105. for (var i = 0; i < num.length; i++) {
  22106. this.words[i] = this.words[i] | num.words[i];
  22107. }
  22108. return this._strip();
  22109. };
  22110. BN.prototype.ior = function ior(num) {
  22111. assert((this.negative | num.negative) === 0);
  22112. return this.iuor(num);
  22113. };
  22114. // Or `num` with `this`
  22115. BN.prototype.or = function or(num) {
  22116. if (this.length > num.length) return this.clone().ior(num);
  22117. return num.clone().ior(this);
  22118. };
  22119. BN.prototype.uor = function uor(num) {
  22120. if (this.length > num.length) return this.clone().iuor(num);
  22121. return num.clone().iuor(this);
  22122. };
  22123. // And `num` with `this` in-place
  22124. BN.prototype.iuand = function iuand(num) {
  22125. // b = min-length(num, this)
  22126. var b;
  22127. if (this.length > num.length) {
  22128. b = num;
  22129. } else {
  22130. b = this;
  22131. }
  22132. for (var i = 0; i < b.length; i++) {
  22133. this.words[i] = this.words[i] & num.words[i];
  22134. }
  22135. this.length = b.length;
  22136. return this._strip();
  22137. };
  22138. BN.prototype.iand = function iand(num) {
  22139. assert((this.negative | num.negative) === 0);
  22140. return this.iuand(num);
  22141. };
  22142. // And `num` with `this`
  22143. BN.prototype.and = function and(num) {
  22144. if (this.length > num.length) return this.clone().iand(num);
  22145. return num.clone().iand(this);
  22146. };
  22147. BN.prototype.uand = function uand(num) {
  22148. if (this.length > num.length) return this.clone().iuand(num);
  22149. return num.clone().iuand(this);
  22150. };
  22151. // Xor `num` with `this` in-place
  22152. BN.prototype.iuxor = function iuxor(num) {
  22153. // a.length > b.length
  22154. var a;
  22155. var b;
  22156. if (this.length > num.length) {
  22157. a = this;
  22158. b = num;
  22159. } else {
  22160. a = num;
  22161. b = this;
  22162. }
  22163. for (var i = 0; i < b.length; i++) {
  22164. this.words[i] = a.words[i] ^ b.words[i];
  22165. }
  22166. if (this !== a) {
  22167. for (; i < a.length; i++) {
  22168. this.words[i] = a.words[i];
  22169. }
  22170. }
  22171. this.length = a.length;
  22172. return this._strip();
  22173. };
  22174. BN.prototype.ixor = function ixor(num) {
  22175. assert((this.negative | num.negative) === 0);
  22176. return this.iuxor(num);
  22177. };
  22178. // Xor `num` with `this`
  22179. BN.prototype.xor = function xor(num) {
  22180. if (this.length > num.length) return this.clone().ixor(num);
  22181. return num.clone().ixor(this);
  22182. };
  22183. BN.prototype.uxor = function uxor(num) {
  22184. if (this.length > num.length) return this.clone().iuxor(num);
  22185. return num.clone().iuxor(this);
  22186. };
  22187. // Not ``this`` with ``width`` bitwidth
  22188. BN.prototype.inotn = function inotn(width) {
  22189. assert(typeof width === 'number' && width >= 0);
  22190. var bytesNeeded = Math.ceil(width / 26) | 0;
  22191. var bitsLeft = width % 26;
  22192. // Extend the buffer with leading zeroes
  22193. this._expand(bytesNeeded);
  22194. if (bitsLeft > 0) {
  22195. bytesNeeded--;
  22196. }
  22197. // Handle complete words
  22198. for (var i = 0; i < bytesNeeded; i++) {
  22199. this.words[i] = ~this.words[i] & 0x3ffffff;
  22200. }
  22201. // Handle the residue
  22202. if (bitsLeft > 0) {
  22203. this.words[i] = ~this.words[i] & 0x3ffffff >> 26 - bitsLeft;
  22204. }
  22205. // And remove leading zeroes
  22206. return this._strip();
  22207. };
  22208. BN.prototype.notn = function notn(width) {
  22209. return this.clone().inotn(width);
  22210. };
  22211. // Set `bit` of `this`
  22212. BN.prototype.setn = function setn(bit, val) {
  22213. assert(typeof bit === 'number' && bit >= 0);
  22214. var off = bit / 26 | 0;
  22215. var wbit = bit % 26;
  22216. this._expand(off + 1);
  22217. if (val) {
  22218. this.words[off] = this.words[off] | 1 << wbit;
  22219. } else {
  22220. this.words[off] = this.words[off] & ~(1 << wbit);
  22221. }
  22222. return this._strip();
  22223. };
  22224. // Add `num` to `this` in-place
  22225. BN.prototype.iadd = function iadd(num) {
  22226. var r;
  22227. // negative + positive
  22228. if (this.negative !== 0 && num.negative === 0) {
  22229. this.negative = 0;
  22230. r = this.isub(num);
  22231. this.negative ^= 1;
  22232. return this._normSign();
  22233. // positive + negative
  22234. } else if (this.negative === 0 && num.negative !== 0) {
  22235. num.negative = 0;
  22236. r = this.isub(num);
  22237. num.negative = 1;
  22238. return r._normSign();
  22239. }
  22240. // a.length > b.length
  22241. var a, b;
  22242. if (this.length > num.length) {
  22243. a = this;
  22244. b = num;
  22245. } else {
  22246. a = num;
  22247. b = this;
  22248. }
  22249. var carry = 0;
  22250. for (var i = 0; i < b.length; i++) {
  22251. r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
  22252. this.words[i] = r & 0x3ffffff;
  22253. carry = r >>> 26;
  22254. }
  22255. for (; carry !== 0 && i < a.length; i++) {
  22256. r = (a.words[i] | 0) + carry;
  22257. this.words[i] = r & 0x3ffffff;
  22258. carry = r >>> 26;
  22259. }
  22260. this.length = a.length;
  22261. if (carry !== 0) {
  22262. this.words[this.length] = carry;
  22263. this.length++;
  22264. // Copy the rest of the words
  22265. } else if (a !== this) {
  22266. for (; i < a.length; i++) {
  22267. this.words[i] = a.words[i];
  22268. }
  22269. }
  22270. return this;
  22271. };
  22272. // Add `num` to `this`
  22273. BN.prototype.add = function add(num) {
  22274. var res;
  22275. if (num.negative !== 0 && this.negative === 0) {
  22276. num.negative = 0;
  22277. res = this.sub(num);
  22278. num.negative ^= 1;
  22279. return res;
  22280. } else if (num.negative === 0 && this.negative !== 0) {
  22281. this.negative = 0;
  22282. res = num.sub(this);
  22283. this.negative = 1;
  22284. return res;
  22285. }
  22286. if (this.length > num.length) return this.clone().iadd(num);
  22287. return num.clone().iadd(this);
  22288. };
  22289. // Subtract `num` from `this` in-place
  22290. BN.prototype.isub = function isub(num) {
  22291. // this - (-num) = this + num
  22292. if (num.negative !== 0) {
  22293. num.negative = 0;
  22294. var r = this.iadd(num);
  22295. num.negative = 1;
  22296. return r._normSign();
  22297. // -this - num = -(this + num)
  22298. } else if (this.negative !== 0) {
  22299. this.negative = 0;
  22300. this.iadd(num);
  22301. this.negative = 1;
  22302. return this._normSign();
  22303. }
  22304. // At this point both numbers are positive
  22305. var cmp = this.cmp(num);
  22306. // Optimization - zeroify
  22307. if (cmp === 0) {
  22308. this.negative = 0;
  22309. this.length = 1;
  22310. this.words[0] = 0;
  22311. return this;
  22312. }
  22313. // a > b
  22314. var a, b;
  22315. if (cmp > 0) {
  22316. a = this;
  22317. b = num;
  22318. } else {
  22319. a = num;
  22320. b = this;
  22321. }
  22322. var carry = 0;
  22323. for (var i = 0; i < b.length; i++) {
  22324. r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
  22325. carry = r >> 26;
  22326. this.words[i] = r & 0x3ffffff;
  22327. }
  22328. for (; carry !== 0 && i < a.length; i++) {
  22329. r = (a.words[i] | 0) + carry;
  22330. carry = r >> 26;
  22331. this.words[i] = r & 0x3ffffff;
  22332. }
  22333. // Copy rest of the words
  22334. if (carry === 0 && i < a.length && a !== this) {
  22335. for (; i < a.length; i++) {
  22336. this.words[i] = a.words[i];
  22337. }
  22338. }
  22339. this.length = Math.max(this.length, i);
  22340. if (a !== this) {
  22341. this.negative = 1;
  22342. }
  22343. return this._strip();
  22344. };
  22345. // Subtract `num` from `this`
  22346. BN.prototype.sub = function sub(num) {
  22347. return this.clone().isub(num);
  22348. };
  22349. function smallMulTo(self, num, out) {
  22350. out.negative = num.negative ^ self.negative;
  22351. var len = self.length + num.length | 0;
  22352. out.length = len;
  22353. len = len - 1 | 0;
  22354. // Peel one iteration (compiler can't do it, because of code complexity)
  22355. var a = self.words[0] | 0;
  22356. var b = num.words[0] | 0;
  22357. var r = a * b;
  22358. var lo = r & 0x3ffffff;
  22359. var carry = r / 0x4000000 | 0;
  22360. out.words[0] = lo;
  22361. for (var k = 1; k < len; k++) {
  22362. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  22363. // note that ncarry could be >= 0x3ffffff
  22364. var ncarry = carry >>> 26;
  22365. var rword = carry & 0x3ffffff;
  22366. var maxJ = Math.min(k, num.length - 1);
  22367. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  22368. var i = k - j | 0;
  22369. a = self.words[i] | 0;
  22370. b = num.words[j] | 0;
  22371. r = a * b + rword;
  22372. ncarry += r / 0x4000000 | 0;
  22373. rword = r & 0x3ffffff;
  22374. }
  22375. out.words[k] = rword | 0;
  22376. carry = ncarry | 0;
  22377. }
  22378. if (carry !== 0) {
  22379. out.words[k] = carry | 0;
  22380. } else {
  22381. out.length--;
  22382. }
  22383. return out._strip();
  22384. }
  22385. // TODO(indutny): it may be reasonable to omit it for users who don't need
  22386. // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  22387. // multiplication (like elliptic secp256k1).
  22388. var comb10MulTo = function comb10MulTo(self, num, out) {
  22389. var a = self.words;
  22390. var b = num.words;
  22391. var o = out.words;
  22392. var c = 0;
  22393. var lo;
  22394. var mid;
  22395. var hi;
  22396. var a0 = a[0] | 0;
  22397. var al0 = a0 & 0x1fff;
  22398. var ah0 = a0 >>> 13;
  22399. var a1 = a[1] | 0;
  22400. var al1 = a1 & 0x1fff;
  22401. var ah1 = a1 >>> 13;
  22402. var a2 = a[2] | 0;
  22403. var al2 = a2 & 0x1fff;
  22404. var ah2 = a2 >>> 13;
  22405. var a3 = a[3] | 0;
  22406. var al3 = a3 & 0x1fff;
  22407. var ah3 = a3 >>> 13;
  22408. var a4 = a[4] | 0;
  22409. var al4 = a4 & 0x1fff;
  22410. var ah4 = a4 >>> 13;
  22411. var a5 = a[5] | 0;
  22412. var al5 = a5 & 0x1fff;
  22413. var ah5 = a5 >>> 13;
  22414. var a6 = a[6] | 0;
  22415. var al6 = a6 & 0x1fff;
  22416. var ah6 = a6 >>> 13;
  22417. var a7 = a[7] | 0;
  22418. var al7 = a7 & 0x1fff;
  22419. var ah7 = a7 >>> 13;
  22420. var a8 = a[8] | 0;
  22421. var al8 = a8 & 0x1fff;
  22422. var ah8 = a8 >>> 13;
  22423. var a9 = a[9] | 0;
  22424. var al9 = a9 & 0x1fff;
  22425. var ah9 = a9 >>> 13;
  22426. var b0 = b[0] | 0;
  22427. var bl0 = b0 & 0x1fff;
  22428. var bh0 = b0 >>> 13;
  22429. var b1 = b[1] | 0;
  22430. var bl1 = b1 & 0x1fff;
  22431. var bh1 = b1 >>> 13;
  22432. var b2 = b[2] | 0;
  22433. var bl2 = b2 & 0x1fff;
  22434. var bh2 = b2 >>> 13;
  22435. var b3 = b[3] | 0;
  22436. var bl3 = b3 & 0x1fff;
  22437. var bh3 = b3 >>> 13;
  22438. var b4 = b[4] | 0;
  22439. var bl4 = b4 & 0x1fff;
  22440. var bh4 = b4 >>> 13;
  22441. var b5 = b[5] | 0;
  22442. var bl5 = b5 & 0x1fff;
  22443. var bh5 = b5 >>> 13;
  22444. var b6 = b[6] | 0;
  22445. var bl6 = b6 & 0x1fff;
  22446. var bh6 = b6 >>> 13;
  22447. var b7 = b[7] | 0;
  22448. var bl7 = b7 & 0x1fff;
  22449. var bh7 = b7 >>> 13;
  22450. var b8 = b[8] | 0;
  22451. var bl8 = b8 & 0x1fff;
  22452. var bh8 = b8 >>> 13;
  22453. var b9 = b[9] | 0;
  22454. var bl9 = b9 & 0x1fff;
  22455. var bh9 = b9 >>> 13;
  22456. out.negative = self.negative ^ num.negative;
  22457. out.length = 19;
  22458. /* k = 0 */
  22459. lo = Math.imul(al0, bl0);
  22460. mid = Math.imul(al0, bh0);
  22461. mid = mid + Math.imul(ah0, bl0) | 0;
  22462. hi = Math.imul(ah0, bh0);
  22463. var w0 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22464. c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0;
  22465. w0 &= 0x3ffffff;
  22466. /* k = 1 */
  22467. lo = Math.imul(al1, bl0);
  22468. mid = Math.imul(al1, bh0);
  22469. mid = mid + Math.imul(ah1, bl0) | 0;
  22470. hi = Math.imul(ah1, bh0);
  22471. lo = lo + Math.imul(al0, bl1) | 0;
  22472. mid = mid + Math.imul(al0, bh1) | 0;
  22473. mid = mid + Math.imul(ah0, bl1) | 0;
  22474. hi = hi + Math.imul(ah0, bh1) | 0;
  22475. var w1 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22476. c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0;
  22477. w1 &= 0x3ffffff;
  22478. /* k = 2 */
  22479. lo = Math.imul(al2, bl0);
  22480. mid = Math.imul(al2, bh0);
  22481. mid = mid + Math.imul(ah2, bl0) | 0;
  22482. hi = Math.imul(ah2, bh0);
  22483. lo = lo + Math.imul(al1, bl1) | 0;
  22484. mid = mid + Math.imul(al1, bh1) | 0;
  22485. mid = mid + Math.imul(ah1, bl1) | 0;
  22486. hi = hi + Math.imul(ah1, bh1) | 0;
  22487. lo = lo + Math.imul(al0, bl2) | 0;
  22488. mid = mid + Math.imul(al0, bh2) | 0;
  22489. mid = mid + Math.imul(ah0, bl2) | 0;
  22490. hi = hi + Math.imul(ah0, bh2) | 0;
  22491. var w2 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22492. c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0;
  22493. w2 &= 0x3ffffff;
  22494. /* k = 3 */
  22495. lo = Math.imul(al3, bl0);
  22496. mid = Math.imul(al3, bh0);
  22497. mid = mid + Math.imul(ah3, bl0) | 0;
  22498. hi = Math.imul(ah3, bh0);
  22499. lo = lo + Math.imul(al2, bl1) | 0;
  22500. mid = mid + Math.imul(al2, bh1) | 0;
  22501. mid = mid + Math.imul(ah2, bl1) | 0;
  22502. hi = hi + Math.imul(ah2, bh1) | 0;
  22503. lo = lo + Math.imul(al1, bl2) | 0;
  22504. mid = mid + Math.imul(al1, bh2) | 0;
  22505. mid = mid + Math.imul(ah1, bl2) | 0;
  22506. hi = hi + Math.imul(ah1, bh2) | 0;
  22507. lo = lo + Math.imul(al0, bl3) | 0;
  22508. mid = mid + Math.imul(al0, bh3) | 0;
  22509. mid = mid + Math.imul(ah0, bl3) | 0;
  22510. hi = hi + Math.imul(ah0, bh3) | 0;
  22511. var w3 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22512. c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0;
  22513. w3 &= 0x3ffffff;
  22514. /* k = 4 */
  22515. lo = Math.imul(al4, bl0);
  22516. mid = Math.imul(al4, bh0);
  22517. mid = mid + Math.imul(ah4, bl0) | 0;
  22518. hi = Math.imul(ah4, bh0);
  22519. lo = lo + Math.imul(al3, bl1) | 0;
  22520. mid = mid + Math.imul(al3, bh1) | 0;
  22521. mid = mid + Math.imul(ah3, bl1) | 0;
  22522. hi = hi + Math.imul(ah3, bh1) | 0;
  22523. lo = lo + Math.imul(al2, bl2) | 0;
  22524. mid = mid + Math.imul(al2, bh2) | 0;
  22525. mid = mid + Math.imul(ah2, bl2) | 0;
  22526. hi = hi + Math.imul(ah2, bh2) | 0;
  22527. lo = lo + Math.imul(al1, bl3) | 0;
  22528. mid = mid + Math.imul(al1, bh3) | 0;
  22529. mid = mid + Math.imul(ah1, bl3) | 0;
  22530. hi = hi + Math.imul(ah1, bh3) | 0;
  22531. lo = lo + Math.imul(al0, bl4) | 0;
  22532. mid = mid + Math.imul(al0, bh4) | 0;
  22533. mid = mid + Math.imul(ah0, bl4) | 0;
  22534. hi = hi + Math.imul(ah0, bh4) | 0;
  22535. var w4 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22536. c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0;
  22537. w4 &= 0x3ffffff;
  22538. /* k = 5 */
  22539. lo = Math.imul(al5, bl0);
  22540. mid = Math.imul(al5, bh0);
  22541. mid = mid + Math.imul(ah5, bl0) | 0;
  22542. hi = Math.imul(ah5, bh0);
  22543. lo = lo + Math.imul(al4, bl1) | 0;
  22544. mid = mid + Math.imul(al4, bh1) | 0;
  22545. mid = mid + Math.imul(ah4, bl1) | 0;
  22546. hi = hi + Math.imul(ah4, bh1) | 0;
  22547. lo = lo + Math.imul(al3, bl2) | 0;
  22548. mid = mid + Math.imul(al3, bh2) | 0;
  22549. mid = mid + Math.imul(ah3, bl2) | 0;
  22550. hi = hi + Math.imul(ah3, bh2) | 0;
  22551. lo = lo + Math.imul(al2, bl3) | 0;
  22552. mid = mid + Math.imul(al2, bh3) | 0;
  22553. mid = mid + Math.imul(ah2, bl3) | 0;
  22554. hi = hi + Math.imul(ah2, bh3) | 0;
  22555. lo = lo + Math.imul(al1, bl4) | 0;
  22556. mid = mid + Math.imul(al1, bh4) | 0;
  22557. mid = mid + Math.imul(ah1, bl4) | 0;
  22558. hi = hi + Math.imul(ah1, bh4) | 0;
  22559. lo = lo + Math.imul(al0, bl5) | 0;
  22560. mid = mid + Math.imul(al0, bh5) | 0;
  22561. mid = mid + Math.imul(ah0, bl5) | 0;
  22562. hi = hi + Math.imul(ah0, bh5) | 0;
  22563. var w5 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22564. c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0;
  22565. w5 &= 0x3ffffff;
  22566. /* k = 6 */
  22567. lo = Math.imul(al6, bl0);
  22568. mid = Math.imul(al6, bh0);
  22569. mid = mid + Math.imul(ah6, bl0) | 0;
  22570. hi = Math.imul(ah6, bh0);
  22571. lo = lo + Math.imul(al5, bl1) | 0;
  22572. mid = mid + Math.imul(al5, bh1) | 0;
  22573. mid = mid + Math.imul(ah5, bl1) | 0;
  22574. hi = hi + Math.imul(ah5, bh1) | 0;
  22575. lo = lo + Math.imul(al4, bl2) | 0;
  22576. mid = mid + Math.imul(al4, bh2) | 0;
  22577. mid = mid + Math.imul(ah4, bl2) | 0;
  22578. hi = hi + Math.imul(ah4, bh2) | 0;
  22579. lo = lo + Math.imul(al3, bl3) | 0;
  22580. mid = mid + Math.imul(al3, bh3) | 0;
  22581. mid = mid + Math.imul(ah3, bl3) | 0;
  22582. hi = hi + Math.imul(ah3, bh3) | 0;
  22583. lo = lo + Math.imul(al2, bl4) | 0;
  22584. mid = mid + Math.imul(al2, bh4) | 0;
  22585. mid = mid + Math.imul(ah2, bl4) | 0;
  22586. hi = hi + Math.imul(ah2, bh4) | 0;
  22587. lo = lo + Math.imul(al1, bl5) | 0;
  22588. mid = mid + Math.imul(al1, bh5) | 0;
  22589. mid = mid + Math.imul(ah1, bl5) | 0;
  22590. hi = hi + Math.imul(ah1, bh5) | 0;
  22591. lo = lo + Math.imul(al0, bl6) | 0;
  22592. mid = mid + Math.imul(al0, bh6) | 0;
  22593. mid = mid + Math.imul(ah0, bl6) | 0;
  22594. hi = hi + Math.imul(ah0, bh6) | 0;
  22595. var w6 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22596. c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0;
  22597. w6 &= 0x3ffffff;
  22598. /* k = 7 */
  22599. lo = Math.imul(al7, bl0);
  22600. mid = Math.imul(al7, bh0);
  22601. mid = mid + Math.imul(ah7, bl0) | 0;
  22602. hi = Math.imul(ah7, bh0);
  22603. lo = lo + Math.imul(al6, bl1) | 0;
  22604. mid = mid + Math.imul(al6, bh1) | 0;
  22605. mid = mid + Math.imul(ah6, bl1) | 0;
  22606. hi = hi + Math.imul(ah6, bh1) | 0;
  22607. lo = lo + Math.imul(al5, bl2) | 0;
  22608. mid = mid + Math.imul(al5, bh2) | 0;
  22609. mid = mid + Math.imul(ah5, bl2) | 0;
  22610. hi = hi + Math.imul(ah5, bh2) | 0;
  22611. lo = lo + Math.imul(al4, bl3) | 0;
  22612. mid = mid + Math.imul(al4, bh3) | 0;
  22613. mid = mid + Math.imul(ah4, bl3) | 0;
  22614. hi = hi + Math.imul(ah4, bh3) | 0;
  22615. lo = lo + Math.imul(al3, bl4) | 0;
  22616. mid = mid + Math.imul(al3, bh4) | 0;
  22617. mid = mid + Math.imul(ah3, bl4) | 0;
  22618. hi = hi + Math.imul(ah3, bh4) | 0;
  22619. lo = lo + Math.imul(al2, bl5) | 0;
  22620. mid = mid + Math.imul(al2, bh5) | 0;
  22621. mid = mid + Math.imul(ah2, bl5) | 0;
  22622. hi = hi + Math.imul(ah2, bh5) | 0;
  22623. lo = lo + Math.imul(al1, bl6) | 0;
  22624. mid = mid + Math.imul(al1, bh6) | 0;
  22625. mid = mid + Math.imul(ah1, bl6) | 0;
  22626. hi = hi + Math.imul(ah1, bh6) | 0;
  22627. lo = lo + Math.imul(al0, bl7) | 0;
  22628. mid = mid + Math.imul(al0, bh7) | 0;
  22629. mid = mid + Math.imul(ah0, bl7) | 0;
  22630. hi = hi + Math.imul(ah0, bh7) | 0;
  22631. var w7 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22632. c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0;
  22633. w7 &= 0x3ffffff;
  22634. /* k = 8 */
  22635. lo = Math.imul(al8, bl0);
  22636. mid = Math.imul(al8, bh0);
  22637. mid = mid + Math.imul(ah8, bl0) | 0;
  22638. hi = Math.imul(ah8, bh0);
  22639. lo = lo + Math.imul(al7, bl1) | 0;
  22640. mid = mid + Math.imul(al7, bh1) | 0;
  22641. mid = mid + Math.imul(ah7, bl1) | 0;
  22642. hi = hi + Math.imul(ah7, bh1) | 0;
  22643. lo = lo + Math.imul(al6, bl2) | 0;
  22644. mid = mid + Math.imul(al6, bh2) | 0;
  22645. mid = mid + Math.imul(ah6, bl2) | 0;
  22646. hi = hi + Math.imul(ah6, bh2) | 0;
  22647. lo = lo + Math.imul(al5, bl3) | 0;
  22648. mid = mid + Math.imul(al5, bh3) | 0;
  22649. mid = mid + Math.imul(ah5, bl3) | 0;
  22650. hi = hi + Math.imul(ah5, bh3) | 0;
  22651. lo = lo + Math.imul(al4, bl4) | 0;
  22652. mid = mid + Math.imul(al4, bh4) | 0;
  22653. mid = mid + Math.imul(ah4, bl4) | 0;
  22654. hi = hi + Math.imul(ah4, bh4) | 0;
  22655. lo = lo + Math.imul(al3, bl5) | 0;
  22656. mid = mid + Math.imul(al3, bh5) | 0;
  22657. mid = mid + Math.imul(ah3, bl5) | 0;
  22658. hi = hi + Math.imul(ah3, bh5) | 0;
  22659. lo = lo + Math.imul(al2, bl6) | 0;
  22660. mid = mid + Math.imul(al2, bh6) | 0;
  22661. mid = mid + Math.imul(ah2, bl6) | 0;
  22662. hi = hi + Math.imul(ah2, bh6) | 0;
  22663. lo = lo + Math.imul(al1, bl7) | 0;
  22664. mid = mid + Math.imul(al1, bh7) | 0;
  22665. mid = mid + Math.imul(ah1, bl7) | 0;
  22666. hi = hi + Math.imul(ah1, bh7) | 0;
  22667. lo = lo + Math.imul(al0, bl8) | 0;
  22668. mid = mid + Math.imul(al0, bh8) | 0;
  22669. mid = mid + Math.imul(ah0, bl8) | 0;
  22670. hi = hi + Math.imul(ah0, bh8) | 0;
  22671. var w8 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22672. c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0;
  22673. w8 &= 0x3ffffff;
  22674. /* k = 9 */
  22675. lo = Math.imul(al9, bl0);
  22676. mid = Math.imul(al9, bh0);
  22677. mid = mid + Math.imul(ah9, bl0) | 0;
  22678. hi = Math.imul(ah9, bh0);
  22679. lo = lo + Math.imul(al8, bl1) | 0;
  22680. mid = mid + Math.imul(al8, bh1) | 0;
  22681. mid = mid + Math.imul(ah8, bl1) | 0;
  22682. hi = hi + Math.imul(ah8, bh1) | 0;
  22683. lo = lo + Math.imul(al7, bl2) | 0;
  22684. mid = mid + Math.imul(al7, bh2) | 0;
  22685. mid = mid + Math.imul(ah7, bl2) | 0;
  22686. hi = hi + Math.imul(ah7, bh2) | 0;
  22687. lo = lo + Math.imul(al6, bl3) | 0;
  22688. mid = mid + Math.imul(al6, bh3) | 0;
  22689. mid = mid + Math.imul(ah6, bl3) | 0;
  22690. hi = hi + Math.imul(ah6, bh3) | 0;
  22691. lo = lo + Math.imul(al5, bl4) | 0;
  22692. mid = mid + Math.imul(al5, bh4) | 0;
  22693. mid = mid + Math.imul(ah5, bl4) | 0;
  22694. hi = hi + Math.imul(ah5, bh4) | 0;
  22695. lo = lo + Math.imul(al4, bl5) | 0;
  22696. mid = mid + Math.imul(al4, bh5) | 0;
  22697. mid = mid + Math.imul(ah4, bl5) | 0;
  22698. hi = hi + Math.imul(ah4, bh5) | 0;
  22699. lo = lo + Math.imul(al3, bl6) | 0;
  22700. mid = mid + Math.imul(al3, bh6) | 0;
  22701. mid = mid + Math.imul(ah3, bl6) | 0;
  22702. hi = hi + Math.imul(ah3, bh6) | 0;
  22703. lo = lo + Math.imul(al2, bl7) | 0;
  22704. mid = mid + Math.imul(al2, bh7) | 0;
  22705. mid = mid + Math.imul(ah2, bl7) | 0;
  22706. hi = hi + Math.imul(ah2, bh7) | 0;
  22707. lo = lo + Math.imul(al1, bl8) | 0;
  22708. mid = mid + Math.imul(al1, bh8) | 0;
  22709. mid = mid + Math.imul(ah1, bl8) | 0;
  22710. hi = hi + Math.imul(ah1, bh8) | 0;
  22711. lo = lo + Math.imul(al0, bl9) | 0;
  22712. mid = mid + Math.imul(al0, bh9) | 0;
  22713. mid = mid + Math.imul(ah0, bl9) | 0;
  22714. hi = hi + Math.imul(ah0, bh9) | 0;
  22715. var w9 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22716. c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0;
  22717. w9 &= 0x3ffffff;
  22718. /* k = 10 */
  22719. lo = Math.imul(al9, bl1);
  22720. mid = Math.imul(al9, bh1);
  22721. mid = mid + Math.imul(ah9, bl1) | 0;
  22722. hi = Math.imul(ah9, bh1);
  22723. lo = lo + Math.imul(al8, bl2) | 0;
  22724. mid = mid + Math.imul(al8, bh2) | 0;
  22725. mid = mid + Math.imul(ah8, bl2) | 0;
  22726. hi = hi + Math.imul(ah8, bh2) | 0;
  22727. lo = lo + Math.imul(al7, bl3) | 0;
  22728. mid = mid + Math.imul(al7, bh3) | 0;
  22729. mid = mid + Math.imul(ah7, bl3) | 0;
  22730. hi = hi + Math.imul(ah7, bh3) | 0;
  22731. lo = lo + Math.imul(al6, bl4) | 0;
  22732. mid = mid + Math.imul(al6, bh4) | 0;
  22733. mid = mid + Math.imul(ah6, bl4) | 0;
  22734. hi = hi + Math.imul(ah6, bh4) | 0;
  22735. lo = lo + Math.imul(al5, bl5) | 0;
  22736. mid = mid + Math.imul(al5, bh5) | 0;
  22737. mid = mid + Math.imul(ah5, bl5) | 0;
  22738. hi = hi + Math.imul(ah5, bh5) | 0;
  22739. lo = lo + Math.imul(al4, bl6) | 0;
  22740. mid = mid + Math.imul(al4, bh6) | 0;
  22741. mid = mid + Math.imul(ah4, bl6) | 0;
  22742. hi = hi + Math.imul(ah4, bh6) | 0;
  22743. lo = lo + Math.imul(al3, bl7) | 0;
  22744. mid = mid + Math.imul(al3, bh7) | 0;
  22745. mid = mid + Math.imul(ah3, bl7) | 0;
  22746. hi = hi + Math.imul(ah3, bh7) | 0;
  22747. lo = lo + Math.imul(al2, bl8) | 0;
  22748. mid = mid + Math.imul(al2, bh8) | 0;
  22749. mid = mid + Math.imul(ah2, bl8) | 0;
  22750. hi = hi + Math.imul(ah2, bh8) | 0;
  22751. lo = lo + Math.imul(al1, bl9) | 0;
  22752. mid = mid + Math.imul(al1, bh9) | 0;
  22753. mid = mid + Math.imul(ah1, bl9) | 0;
  22754. hi = hi + Math.imul(ah1, bh9) | 0;
  22755. var w10 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22756. c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0;
  22757. w10 &= 0x3ffffff;
  22758. /* k = 11 */
  22759. lo = Math.imul(al9, bl2);
  22760. mid = Math.imul(al9, bh2);
  22761. mid = mid + Math.imul(ah9, bl2) | 0;
  22762. hi = Math.imul(ah9, bh2);
  22763. lo = lo + Math.imul(al8, bl3) | 0;
  22764. mid = mid + Math.imul(al8, bh3) | 0;
  22765. mid = mid + Math.imul(ah8, bl3) | 0;
  22766. hi = hi + Math.imul(ah8, bh3) | 0;
  22767. lo = lo + Math.imul(al7, bl4) | 0;
  22768. mid = mid + Math.imul(al7, bh4) | 0;
  22769. mid = mid + Math.imul(ah7, bl4) | 0;
  22770. hi = hi + Math.imul(ah7, bh4) | 0;
  22771. lo = lo + Math.imul(al6, bl5) | 0;
  22772. mid = mid + Math.imul(al6, bh5) | 0;
  22773. mid = mid + Math.imul(ah6, bl5) | 0;
  22774. hi = hi + Math.imul(ah6, bh5) | 0;
  22775. lo = lo + Math.imul(al5, bl6) | 0;
  22776. mid = mid + Math.imul(al5, bh6) | 0;
  22777. mid = mid + Math.imul(ah5, bl6) | 0;
  22778. hi = hi + Math.imul(ah5, bh6) | 0;
  22779. lo = lo + Math.imul(al4, bl7) | 0;
  22780. mid = mid + Math.imul(al4, bh7) | 0;
  22781. mid = mid + Math.imul(ah4, bl7) | 0;
  22782. hi = hi + Math.imul(ah4, bh7) | 0;
  22783. lo = lo + Math.imul(al3, bl8) | 0;
  22784. mid = mid + Math.imul(al3, bh8) | 0;
  22785. mid = mid + Math.imul(ah3, bl8) | 0;
  22786. hi = hi + Math.imul(ah3, bh8) | 0;
  22787. lo = lo + Math.imul(al2, bl9) | 0;
  22788. mid = mid + Math.imul(al2, bh9) | 0;
  22789. mid = mid + Math.imul(ah2, bl9) | 0;
  22790. hi = hi + Math.imul(ah2, bh9) | 0;
  22791. var w11 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22792. c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0;
  22793. w11 &= 0x3ffffff;
  22794. /* k = 12 */
  22795. lo = Math.imul(al9, bl3);
  22796. mid = Math.imul(al9, bh3);
  22797. mid = mid + Math.imul(ah9, bl3) | 0;
  22798. hi = Math.imul(ah9, bh3);
  22799. lo = lo + Math.imul(al8, bl4) | 0;
  22800. mid = mid + Math.imul(al8, bh4) | 0;
  22801. mid = mid + Math.imul(ah8, bl4) | 0;
  22802. hi = hi + Math.imul(ah8, bh4) | 0;
  22803. lo = lo + Math.imul(al7, bl5) | 0;
  22804. mid = mid + Math.imul(al7, bh5) | 0;
  22805. mid = mid + Math.imul(ah7, bl5) | 0;
  22806. hi = hi + Math.imul(ah7, bh5) | 0;
  22807. lo = lo + Math.imul(al6, bl6) | 0;
  22808. mid = mid + Math.imul(al6, bh6) | 0;
  22809. mid = mid + Math.imul(ah6, bl6) | 0;
  22810. hi = hi + Math.imul(ah6, bh6) | 0;
  22811. lo = lo + Math.imul(al5, bl7) | 0;
  22812. mid = mid + Math.imul(al5, bh7) | 0;
  22813. mid = mid + Math.imul(ah5, bl7) | 0;
  22814. hi = hi + Math.imul(ah5, bh7) | 0;
  22815. lo = lo + Math.imul(al4, bl8) | 0;
  22816. mid = mid + Math.imul(al4, bh8) | 0;
  22817. mid = mid + Math.imul(ah4, bl8) | 0;
  22818. hi = hi + Math.imul(ah4, bh8) | 0;
  22819. lo = lo + Math.imul(al3, bl9) | 0;
  22820. mid = mid + Math.imul(al3, bh9) | 0;
  22821. mid = mid + Math.imul(ah3, bl9) | 0;
  22822. hi = hi + Math.imul(ah3, bh9) | 0;
  22823. var w12 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22824. c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0;
  22825. w12 &= 0x3ffffff;
  22826. /* k = 13 */
  22827. lo = Math.imul(al9, bl4);
  22828. mid = Math.imul(al9, bh4);
  22829. mid = mid + Math.imul(ah9, bl4) | 0;
  22830. hi = Math.imul(ah9, bh4);
  22831. lo = lo + Math.imul(al8, bl5) | 0;
  22832. mid = mid + Math.imul(al8, bh5) | 0;
  22833. mid = mid + Math.imul(ah8, bl5) | 0;
  22834. hi = hi + Math.imul(ah8, bh5) | 0;
  22835. lo = lo + Math.imul(al7, bl6) | 0;
  22836. mid = mid + Math.imul(al7, bh6) | 0;
  22837. mid = mid + Math.imul(ah7, bl6) | 0;
  22838. hi = hi + Math.imul(ah7, bh6) | 0;
  22839. lo = lo + Math.imul(al6, bl7) | 0;
  22840. mid = mid + Math.imul(al6, bh7) | 0;
  22841. mid = mid + Math.imul(ah6, bl7) | 0;
  22842. hi = hi + Math.imul(ah6, bh7) | 0;
  22843. lo = lo + Math.imul(al5, bl8) | 0;
  22844. mid = mid + Math.imul(al5, bh8) | 0;
  22845. mid = mid + Math.imul(ah5, bl8) | 0;
  22846. hi = hi + Math.imul(ah5, bh8) | 0;
  22847. lo = lo + Math.imul(al4, bl9) | 0;
  22848. mid = mid + Math.imul(al4, bh9) | 0;
  22849. mid = mid + Math.imul(ah4, bl9) | 0;
  22850. hi = hi + Math.imul(ah4, bh9) | 0;
  22851. var w13 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22852. c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0;
  22853. w13 &= 0x3ffffff;
  22854. /* k = 14 */
  22855. lo = Math.imul(al9, bl5);
  22856. mid = Math.imul(al9, bh5);
  22857. mid = mid + Math.imul(ah9, bl5) | 0;
  22858. hi = Math.imul(ah9, bh5);
  22859. lo = lo + Math.imul(al8, bl6) | 0;
  22860. mid = mid + Math.imul(al8, bh6) | 0;
  22861. mid = mid + Math.imul(ah8, bl6) | 0;
  22862. hi = hi + Math.imul(ah8, bh6) | 0;
  22863. lo = lo + Math.imul(al7, bl7) | 0;
  22864. mid = mid + Math.imul(al7, bh7) | 0;
  22865. mid = mid + Math.imul(ah7, bl7) | 0;
  22866. hi = hi + Math.imul(ah7, bh7) | 0;
  22867. lo = lo + Math.imul(al6, bl8) | 0;
  22868. mid = mid + Math.imul(al6, bh8) | 0;
  22869. mid = mid + Math.imul(ah6, bl8) | 0;
  22870. hi = hi + Math.imul(ah6, bh8) | 0;
  22871. lo = lo + Math.imul(al5, bl9) | 0;
  22872. mid = mid + Math.imul(al5, bh9) | 0;
  22873. mid = mid + Math.imul(ah5, bl9) | 0;
  22874. hi = hi + Math.imul(ah5, bh9) | 0;
  22875. var w14 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22876. c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0;
  22877. w14 &= 0x3ffffff;
  22878. /* k = 15 */
  22879. lo = Math.imul(al9, bl6);
  22880. mid = Math.imul(al9, bh6);
  22881. mid = mid + Math.imul(ah9, bl6) | 0;
  22882. hi = Math.imul(ah9, bh6);
  22883. lo = lo + Math.imul(al8, bl7) | 0;
  22884. mid = mid + Math.imul(al8, bh7) | 0;
  22885. mid = mid + Math.imul(ah8, bl7) | 0;
  22886. hi = hi + Math.imul(ah8, bh7) | 0;
  22887. lo = lo + Math.imul(al7, bl8) | 0;
  22888. mid = mid + Math.imul(al7, bh8) | 0;
  22889. mid = mid + Math.imul(ah7, bl8) | 0;
  22890. hi = hi + Math.imul(ah7, bh8) | 0;
  22891. lo = lo + Math.imul(al6, bl9) | 0;
  22892. mid = mid + Math.imul(al6, bh9) | 0;
  22893. mid = mid + Math.imul(ah6, bl9) | 0;
  22894. hi = hi + Math.imul(ah6, bh9) | 0;
  22895. var w15 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22896. c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0;
  22897. w15 &= 0x3ffffff;
  22898. /* k = 16 */
  22899. lo = Math.imul(al9, bl7);
  22900. mid = Math.imul(al9, bh7);
  22901. mid = mid + Math.imul(ah9, bl7) | 0;
  22902. hi = Math.imul(ah9, bh7);
  22903. lo = lo + Math.imul(al8, bl8) | 0;
  22904. mid = mid + Math.imul(al8, bh8) | 0;
  22905. mid = mid + Math.imul(ah8, bl8) | 0;
  22906. hi = hi + Math.imul(ah8, bh8) | 0;
  22907. lo = lo + Math.imul(al7, bl9) | 0;
  22908. mid = mid + Math.imul(al7, bh9) | 0;
  22909. mid = mid + Math.imul(ah7, bl9) | 0;
  22910. hi = hi + Math.imul(ah7, bh9) | 0;
  22911. var w16 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22912. c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0;
  22913. w16 &= 0x3ffffff;
  22914. /* k = 17 */
  22915. lo = Math.imul(al9, bl8);
  22916. mid = Math.imul(al9, bh8);
  22917. mid = mid + Math.imul(ah9, bl8) | 0;
  22918. hi = Math.imul(ah9, bh8);
  22919. lo = lo + Math.imul(al8, bl9) | 0;
  22920. mid = mid + Math.imul(al8, bh9) | 0;
  22921. mid = mid + Math.imul(ah8, bl9) | 0;
  22922. hi = hi + Math.imul(ah8, bh9) | 0;
  22923. var w17 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22924. c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0;
  22925. w17 &= 0x3ffffff;
  22926. /* k = 18 */
  22927. lo = Math.imul(al9, bl9);
  22928. mid = Math.imul(al9, bh9);
  22929. mid = mid + Math.imul(ah9, bl9) | 0;
  22930. hi = Math.imul(ah9, bh9);
  22931. var w18 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
  22932. c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0;
  22933. w18 &= 0x3ffffff;
  22934. o[0] = w0;
  22935. o[1] = w1;
  22936. o[2] = w2;
  22937. o[3] = w3;
  22938. o[4] = w4;
  22939. o[5] = w5;
  22940. o[6] = w6;
  22941. o[7] = w7;
  22942. o[8] = w8;
  22943. o[9] = w9;
  22944. o[10] = w10;
  22945. o[11] = w11;
  22946. o[12] = w12;
  22947. o[13] = w13;
  22948. o[14] = w14;
  22949. o[15] = w15;
  22950. o[16] = w16;
  22951. o[17] = w17;
  22952. o[18] = w18;
  22953. if (c !== 0) {
  22954. o[19] = c;
  22955. out.length++;
  22956. }
  22957. return out;
  22958. };
  22959. // Polyfill comb
  22960. if (!Math.imul) {
  22961. comb10MulTo = smallMulTo;
  22962. }
  22963. function bigMulTo(self, num, out) {
  22964. out.negative = num.negative ^ self.negative;
  22965. out.length = self.length + num.length;
  22966. var carry = 0;
  22967. var hncarry = 0;
  22968. for (var k = 0; k < out.length - 1; k++) {
  22969. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  22970. // note that ncarry could be >= 0x3ffffff
  22971. var ncarry = hncarry;
  22972. hncarry = 0;
  22973. var rword = carry & 0x3ffffff;
  22974. var maxJ = Math.min(k, num.length - 1);
  22975. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  22976. var i = k - j;
  22977. var a = self.words[i] | 0;
  22978. var b = num.words[j] | 0;
  22979. var r = a * b;
  22980. var lo = r & 0x3ffffff;
  22981. ncarry = ncarry + (r / 0x4000000 | 0) | 0;
  22982. lo = lo + rword | 0;
  22983. rword = lo & 0x3ffffff;
  22984. ncarry = ncarry + (lo >>> 26) | 0;
  22985. hncarry += ncarry >>> 26;
  22986. ncarry &= 0x3ffffff;
  22987. }
  22988. out.words[k] = rword;
  22989. carry = ncarry;
  22990. ncarry = hncarry;
  22991. }
  22992. if (carry !== 0) {
  22993. out.words[k] = carry;
  22994. } else {
  22995. out.length--;
  22996. }
  22997. return out._strip();
  22998. }
  22999. function jumboMulTo(self, num, out) {
  23000. // Temporary disable, see https://github.com/indutny/bn.js/issues/211
  23001. // var fftm = new FFTM();
  23002. // return fftm.mulp(self, num, out);
  23003. return bigMulTo(self, num, out);
  23004. }
  23005. BN.prototype.mulTo = function mulTo(num, out) {
  23006. var res;
  23007. var len = this.length + num.length;
  23008. if (this.length === 10 && num.length === 10) {
  23009. res = comb10MulTo(this, num, out);
  23010. } else if (len < 63) {
  23011. res = smallMulTo(this, num, out);
  23012. } else if (len < 1024) {
  23013. res = bigMulTo(this, num, out);
  23014. } else {
  23015. res = jumboMulTo(this, num, out);
  23016. }
  23017. return res;
  23018. };
  23019. // Cooley-Tukey algorithm for FFT
  23020. // slightly revisited to rely on looping instead of recursion
  23021. function FFTM(x, y) {
  23022. this.x = x;
  23023. this.y = y;
  23024. }
  23025. FFTM.prototype.makeRBT = function makeRBT(N) {
  23026. var t = new Array(N);
  23027. var l = BN.prototype._countBits(N) - 1;
  23028. for (var i = 0; i < N; i++) {
  23029. t[i] = this.revBin(i, l, N);
  23030. }
  23031. return t;
  23032. };
  23033. // Returns binary-reversed representation of `x`
  23034. FFTM.prototype.revBin = function revBin(x, l, N) {
  23035. if (x === 0 || x === N - 1) return x;
  23036. var rb = 0;
  23037. for (var i = 0; i < l; i++) {
  23038. rb |= (x & 1) << l - i - 1;
  23039. x >>= 1;
  23040. }
  23041. return rb;
  23042. };
  23043. // Performs "tweedling" phase, therefore 'emulating'
  23044. // behaviour of the recursive algorithm
  23045. FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) {
  23046. for (var i = 0; i < N; i++) {
  23047. rtws[i] = rws[rbt[i]];
  23048. itws[i] = iws[rbt[i]];
  23049. }
  23050. };
  23051. FFTM.prototype.transform = function transform(rws, iws, rtws, itws, N, rbt) {
  23052. this.permute(rbt, rws, iws, rtws, itws, N);
  23053. for (var s = 1; s < N; s <<= 1) {
  23054. var l = s << 1;
  23055. var rtwdf = Math.cos(2 * Math.PI / l);
  23056. var itwdf = Math.sin(2 * Math.PI / l);
  23057. for (var p = 0; p < N; p += l) {
  23058. var rtwdf_ = rtwdf;
  23059. var itwdf_ = itwdf;
  23060. for (var j = 0; j < s; j++) {
  23061. var re = rtws[p + j];
  23062. var ie = itws[p + j];
  23063. var ro = rtws[p + j + s];
  23064. var io = itws[p + j + s];
  23065. var rx = rtwdf_ * ro - itwdf_ * io;
  23066. io = rtwdf_ * io + itwdf_ * ro;
  23067. ro = rx;
  23068. rtws[p + j] = re + ro;
  23069. itws[p + j] = ie + io;
  23070. rtws[p + j + s] = re - ro;
  23071. itws[p + j + s] = ie - io;
  23072. /* jshint maxdepth : false */
  23073. if (j !== l) {
  23074. rx = rtwdf * rtwdf_ - itwdf * itwdf_;
  23075. itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
  23076. rtwdf_ = rx;
  23077. }
  23078. }
  23079. }
  23080. }
  23081. };
  23082. FFTM.prototype.guessLen13b = function guessLen13b(n, m) {
  23083. var N = Math.max(m, n) | 1;
  23084. var odd = N & 1;
  23085. var i = 0;
  23086. for (N = N / 2 | 0; N; N = N >>> 1) {
  23087. i++;
  23088. }
  23089. return 1 << i + 1 + odd;
  23090. };
  23091. FFTM.prototype.conjugate = function conjugate(rws, iws, N) {
  23092. if (N <= 1) return;
  23093. for (var i = 0; i < N / 2; i++) {
  23094. var t = rws[i];
  23095. rws[i] = rws[N - i - 1];
  23096. rws[N - i - 1] = t;
  23097. t = iws[i];
  23098. iws[i] = -iws[N - i - 1];
  23099. iws[N - i - 1] = -t;
  23100. }
  23101. };
  23102. FFTM.prototype.normalize13b = function normalize13b(ws, N) {
  23103. var carry = 0;
  23104. for (var i = 0; i < N / 2; i++) {
  23105. var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry;
  23106. ws[i] = w & 0x3ffffff;
  23107. if (w < 0x4000000) {
  23108. carry = 0;
  23109. } else {
  23110. carry = w / 0x4000000 | 0;
  23111. }
  23112. }
  23113. return ws;
  23114. };
  23115. FFTM.prototype.convert13b = function convert13b(ws, len, rws, N) {
  23116. var carry = 0;
  23117. for (var i = 0; i < len; i++) {
  23118. carry = carry + (ws[i] | 0);
  23119. rws[2 * i] = carry & 0x1fff;
  23120. carry = carry >>> 13;
  23121. rws[2 * i + 1] = carry & 0x1fff;
  23122. carry = carry >>> 13;
  23123. }
  23124. // Pad with zeroes
  23125. for (i = 2 * len; i < N; ++i) {
  23126. rws[i] = 0;
  23127. }
  23128. assert(carry === 0);
  23129. assert((carry & ~0x1fff) === 0);
  23130. };
  23131. FFTM.prototype.stub = function stub(N) {
  23132. var ph = new Array(N);
  23133. for (var i = 0; i < N; i++) {
  23134. ph[i] = 0;
  23135. }
  23136. return ph;
  23137. };
  23138. FFTM.prototype.mulp = function mulp(x, y, out) {
  23139. var N = 2 * this.guessLen13b(x.length, y.length);
  23140. var rbt = this.makeRBT(N);
  23141. var _ = this.stub(N);
  23142. var rws = new Array(N);
  23143. var rwst = new Array(N);
  23144. var iwst = new Array(N);
  23145. var nrws = new Array(N);
  23146. var nrwst = new Array(N);
  23147. var niwst = new Array(N);
  23148. var rmws = out.words;
  23149. rmws.length = N;
  23150. this.convert13b(x.words, x.length, rws, N);
  23151. this.convert13b(y.words, y.length, nrws, N);
  23152. this.transform(rws, _, rwst, iwst, N, rbt);
  23153. this.transform(nrws, _, nrwst, niwst, N, rbt);
  23154. for (var i = 0; i < N; i++) {
  23155. var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
  23156. iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
  23157. rwst[i] = rx;
  23158. }
  23159. this.conjugate(rwst, iwst, N);
  23160. this.transform(rwst, iwst, rmws, _, N, rbt);
  23161. this.conjugate(rmws, _, N);
  23162. this.normalize13b(rmws, N);
  23163. out.negative = x.negative ^ y.negative;
  23164. out.length = x.length + y.length;
  23165. return out._strip();
  23166. };
  23167. // Multiply `this` by `num`
  23168. BN.prototype.mul = function mul(num) {
  23169. var out = new BN(null);
  23170. out.words = new Array(this.length + num.length);
  23171. return this.mulTo(num, out);
  23172. };
  23173. // Multiply employing FFT
  23174. BN.prototype.mulf = function mulf(num) {
  23175. var out = new BN(null);
  23176. out.words = new Array(this.length + num.length);
  23177. return jumboMulTo(this, num, out);
  23178. };
  23179. // In-place Multiplication
  23180. BN.prototype.imul = function imul(num) {
  23181. return this.clone().mulTo(num, this);
  23182. };
  23183. BN.prototype.imuln = function imuln(num) {
  23184. var isNegNum = num < 0;
  23185. if (isNegNum) num = -num;
  23186. assert(typeof num === 'number');
  23187. assert(num < 0x4000000);
  23188. // Carry
  23189. var carry = 0;
  23190. for (var i = 0; i < this.length; i++) {
  23191. var w = (this.words[i] | 0) * num;
  23192. var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
  23193. carry >>= 26;
  23194. carry += w / 0x4000000 | 0;
  23195. // NOTE: lo is 27bit maximum
  23196. carry += lo >>> 26;
  23197. this.words[i] = lo & 0x3ffffff;
  23198. }
  23199. if (carry !== 0) {
  23200. this.words[i] = carry;
  23201. this.length++;
  23202. }
  23203. return isNegNum ? this.ineg() : this;
  23204. };
  23205. BN.prototype.muln = function muln(num) {
  23206. return this.clone().imuln(num);
  23207. };
  23208. // `this` * `this`
  23209. BN.prototype.sqr = function sqr() {
  23210. return this.mul(this);
  23211. };
  23212. // `this` * `this` in-place
  23213. BN.prototype.isqr = function isqr() {
  23214. return this.imul(this.clone());
  23215. };
  23216. // Math.pow(`this`, `num`)
  23217. BN.prototype.pow = function pow(num) {
  23218. var w = toBitArray(num);
  23219. if (w.length === 0) return new BN(1);
  23220. // Skip leading zeroes
  23221. var res = this;
  23222. for (var i = 0; i < w.length; i++, res = res.sqr()) {
  23223. if (w[i] !== 0) break;
  23224. }
  23225. if (++i < w.length) {
  23226. for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
  23227. if (w[i] === 0) continue;
  23228. res = res.mul(q);
  23229. }
  23230. }
  23231. return res;
  23232. };
  23233. // Shift-left in-place
  23234. BN.prototype.iushln = function iushln(bits) {
  23235. assert(typeof bits === 'number' && bits >= 0);
  23236. var r = bits % 26;
  23237. var s = (bits - r) / 26;
  23238. var carryMask = 0x3ffffff >>> 26 - r << 26 - r;
  23239. var i;
  23240. if (r !== 0) {
  23241. var carry = 0;
  23242. for (i = 0; i < this.length; i++) {
  23243. var newCarry = this.words[i] & carryMask;
  23244. var c = (this.words[i] | 0) - newCarry << r;
  23245. this.words[i] = c | carry;
  23246. carry = newCarry >>> 26 - r;
  23247. }
  23248. if (carry) {
  23249. this.words[i] = carry;
  23250. this.length++;
  23251. }
  23252. }
  23253. if (s !== 0) {
  23254. for (i = this.length - 1; i >= 0; i--) {
  23255. this.words[i + s] = this.words[i];
  23256. }
  23257. for (i = 0; i < s; i++) {
  23258. this.words[i] = 0;
  23259. }
  23260. this.length += s;
  23261. }
  23262. return this._strip();
  23263. };
  23264. BN.prototype.ishln = function ishln(bits) {
  23265. // TODO(indutny): implement me
  23266. assert(this.negative === 0);
  23267. return this.iushln(bits);
  23268. };
  23269. // Shift-right in-place
  23270. // NOTE: `hint` is a lowest bit before trailing zeroes
  23271. // NOTE: if `extended` is present - it will be filled with destroyed bits
  23272. BN.prototype.iushrn = function iushrn(bits, hint, extended) {
  23273. assert(typeof bits === 'number' && bits >= 0);
  23274. var h;
  23275. if (hint) {
  23276. h = (hint - hint % 26) / 26;
  23277. } else {
  23278. h = 0;
  23279. }
  23280. var r = bits % 26;
  23281. var s = Math.min((bits - r) / 26, this.length);
  23282. var mask = 0x3ffffff ^ 0x3ffffff >>> r << r;
  23283. var maskedWords = extended;
  23284. h -= s;
  23285. h = Math.max(0, h);
  23286. // Extended mode, copy masked part
  23287. if (maskedWords) {
  23288. for (var i = 0; i < s; i++) {
  23289. maskedWords.words[i] = this.words[i];
  23290. }
  23291. maskedWords.length = s;
  23292. }
  23293. if (s === 0) {
  23294. // No-op, we should not move anything at all
  23295. } else if (this.length > s) {
  23296. this.length -= s;
  23297. for (i = 0; i < this.length; i++) {
  23298. this.words[i] = this.words[i + s];
  23299. }
  23300. } else {
  23301. this.words[0] = 0;
  23302. this.length = 1;
  23303. }
  23304. var carry = 0;
  23305. for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
  23306. var word = this.words[i] | 0;
  23307. this.words[i] = carry << 26 - r | word >>> r;
  23308. carry = word & mask;
  23309. }
  23310. // Push carried bits as a mask
  23311. if (maskedWords && carry !== 0) {
  23312. maskedWords.words[maskedWords.length++] = carry;
  23313. }
  23314. if (this.length === 0) {
  23315. this.words[0] = 0;
  23316. this.length = 1;
  23317. }
  23318. return this._strip();
  23319. };
  23320. BN.prototype.ishrn = function ishrn(bits, hint, extended) {
  23321. // TODO(indutny): implement me
  23322. assert(this.negative === 0);
  23323. return this.iushrn(bits, hint, extended);
  23324. };
  23325. // Shift-left
  23326. BN.prototype.shln = function shln(bits) {
  23327. return this.clone().ishln(bits);
  23328. };
  23329. BN.prototype.ushln = function ushln(bits) {
  23330. return this.clone().iushln(bits);
  23331. };
  23332. // Shift-right
  23333. BN.prototype.shrn = function shrn(bits) {
  23334. return this.clone().ishrn(bits);
  23335. };
  23336. BN.prototype.ushrn = function ushrn(bits) {
  23337. return this.clone().iushrn(bits);
  23338. };
  23339. // Test if n bit is set
  23340. BN.prototype.testn = function testn(bit) {
  23341. assert(typeof bit === 'number' && bit >= 0);
  23342. var r = bit % 26;
  23343. var s = (bit - r) / 26;
  23344. var q = 1 << r;
  23345. // Fast case: bit is much higher than all existing words
  23346. if (this.length <= s) return false;
  23347. // Check bit and return
  23348. var w = this.words[s];
  23349. return !!(w & q);
  23350. };
  23351. // Return only lowers bits of number (in-place)
  23352. BN.prototype.imaskn = function imaskn(bits) {
  23353. assert(typeof bits === 'number' && bits >= 0);
  23354. var r = bits % 26;
  23355. var s = (bits - r) / 26;
  23356. assert(this.negative === 0, 'imaskn works only with positive numbers');
  23357. if (this.length <= s) {
  23358. return this;
  23359. }
  23360. if (r !== 0) {
  23361. s++;
  23362. }
  23363. this.length = Math.min(s, this.length);
  23364. if (r !== 0) {
  23365. var mask = 0x3ffffff ^ 0x3ffffff >>> r << r;
  23366. this.words[this.length - 1] &= mask;
  23367. }
  23368. return this._strip();
  23369. };
  23370. // Return only lowers bits of number
  23371. BN.prototype.maskn = function maskn(bits) {
  23372. return this.clone().imaskn(bits);
  23373. };
  23374. // Add plain number `num` to `this`
  23375. BN.prototype.iaddn = function iaddn(num) {
  23376. assert(typeof num === 'number');
  23377. assert(num < 0x4000000);
  23378. if (num < 0) return this.isubn(-num);
  23379. // Possible sign change
  23380. if (this.negative !== 0) {
  23381. if (this.length === 1 && (this.words[0] | 0) <= num) {
  23382. this.words[0] = num - (this.words[0] | 0);
  23383. this.negative = 0;
  23384. return this;
  23385. }
  23386. this.negative = 0;
  23387. this.isubn(num);
  23388. this.negative = 1;
  23389. return this;
  23390. }
  23391. // Add without checks
  23392. return this._iaddn(num);
  23393. };
  23394. BN.prototype._iaddn = function _iaddn(num) {
  23395. this.words[0] += num;
  23396. // Carry
  23397. for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
  23398. this.words[i] -= 0x4000000;
  23399. if (i === this.length - 1) {
  23400. this.words[i + 1] = 1;
  23401. } else {
  23402. this.words[i + 1]++;
  23403. }
  23404. }
  23405. this.length = Math.max(this.length, i + 1);
  23406. return this;
  23407. };
  23408. // Subtract plain number `num` from `this`
  23409. BN.prototype.isubn = function isubn(num) {
  23410. assert(typeof num === 'number');
  23411. assert(num < 0x4000000);
  23412. if (num < 0) return this.iaddn(-num);
  23413. if (this.negative !== 0) {
  23414. this.negative = 0;
  23415. this.iaddn(num);
  23416. this.negative = 1;
  23417. return this;
  23418. }
  23419. this.words[0] -= num;
  23420. if (this.length === 1 && this.words[0] < 0) {
  23421. this.words[0] = -this.words[0];
  23422. this.negative = 1;
  23423. } else {
  23424. // Carry
  23425. for (var i = 0; i < this.length && this.words[i] < 0; i++) {
  23426. this.words[i] += 0x4000000;
  23427. this.words[i + 1] -= 1;
  23428. }
  23429. }
  23430. return this._strip();
  23431. };
  23432. BN.prototype.addn = function addn(num) {
  23433. return this.clone().iaddn(num);
  23434. };
  23435. BN.prototype.subn = function subn(num) {
  23436. return this.clone().isubn(num);
  23437. };
  23438. BN.prototype.iabs = function iabs() {
  23439. this.negative = 0;
  23440. return this;
  23441. };
  23442. BN.prototype.abs = function abs() {
  23443. return this.clone().iabs();
  23444. };
  23445. BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
  23446. var len = num.length + shift;
  23447. var i;
  23448. this._expand(len);
  23449. var w;
  23450. var carry = 0;
  23451. for (i = 0; i < num.length; i++) {
  23452. w = (this.words[i + shift] | 0) + carry;
  23453. var right = (num.words[i] | 0) * mul;
  23454. w -= right & 0x3ffffff;
  23455. carry = (w >> 26) - (right / 0x4000000 | 0);
  23456. this.words[i + shift] = w & 0x3ffffff;
  23457. }
  23458. for (; i < this.length - shift; i++) {
  23459. w = (this.words[i + shift] | 0) + carry;
  23460. carry = w >> 26;
  23461. this.words[i + shift] = w & 0x3ffffff;
  23462. }
  23463. if (carry === 0) return this._strip();
  23464. // Subtraction overflow
  23465. assert(carry === -1);
  23466. carry = 0;
  23467. for (i = 0; i < this.length; i++) {
  23468. w = -(this.words[i] | 0) + carry;
  23469. carry = w >> 26;
  23470. this.words[i] = w & 0x3ffffff;
  23471. }
  23472. this.negative = 1;
  23473. return this._strip();
  23474. };
  23475. BN.prototype._wordDiv = function _wordDiv(num, mode) {
  23476. var shift = this.length - num.length;
  23477. var a = this.clone();
  23478. var b = num;
  23479. // Normalize
  23480. var bhi = b.words[b.length - 1] | 0;
  23481. var bhiBits = this._countBits(bhi);
  23482. shift = 26 - bhiBits;
  23483. if (shift !== 0) {
  23484. b = b.ushln(shift);
  23485. a.iushln(shift);
  23486. bhi = b.words[b.length - 1] | 0;
  23487. }
  23488. // Initialize quotient
  23489. var m = a.length - b.length;
  23490. var q;
  23491. if (mode !== 'mod') {
  23492. q = new BN(null);
  23493. q.length = m + 1;
  23494. q.words = new Array(q.length);
  23495. for (var i = 0; i < q.length; i++) {
  23496. q.words[i] = 0;
  23497. }
  23498. }
  23499. var diff = a.clone()._ishlnsubmul(b, 1, m);
  23500. if (diff.negative === 0) {
  23501. a = diff;
  23502. if (q) {
  23503. q.words[m] = 1;
  23504. }
  23505. }
  23506. for (var j = m - 1; j >= 0; j--) {
  23507. var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0);
  23508. // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
  23509. // (0x7ffffff)
  23510. qj = Math.min(qj / bhi | 0, 0x3ffffff);
  23511. a._ishlnsubmul(b, qj, j);
  23512. while (a.negative !== 0) {
  23513. qj--;
  23514. a.negative = 0;
  23515. a._ishlnsubmul(b, 1, j);
  23516. if (!a.isZero()) {
  23517. a.negative ^= 1;
  23518. }
  23519. }
  23520. if (q) {
  23521. q.words[j] = qj;
  23522. }
  23523. }
  23524. if (q) {
  23525. q._strip();
  23526. }
  23527. a._strip();
  23528. // Denormalize
  23529. if (mode !== 'div' && shift !== 0) {
  23530. a.iushrn(shift);
  23531. }
  23532. return {
  23533. div: q || null,
  23534. mod: a
  23535. };
  23536. };
  23537. // NOTE: 1) `mode` can be set to `mod` to request mod only,
  23538. // to `div` to request div only, or be absent to
  23539. // request both div & mod
  23540. // 2) `positive` is true if unsigned mod is requested
  23541. BN.prototype.divmod = function divmod(num, mode, positive) {
  23542. assert(!num.isZero());
  23543. if (this.isZero()) {
  23544. return {
  23545. div: new BN(0),
  23546. mod: new BN(0)
  23547. };
  23548. }
  23549. var div, mod, res;
  23550. if (this.negative !== 0 && num.negative === 0) {
  23551. res = this.neg().divmod(num, mode);
  23552. if (mode !== 'mod') {
  23553. div = res.div.neg();
  23554. }
  23555. if (mode !== 'div') {
  23556. mod = res.mod.neg();
  23557. if (positive && mod.negative !== 0) {
  23558. mod.iadd(num);
  23559. }
  23560. }
  23561. return {
  23562. div: div,
  23563. mod: mod
  23564. };
  23565. }
  23566. if (this.negative === 0 && num.negative !== 0) {
  23567. res = this.divmod(num.neg(), mode);
  23568. if (mode !== 'mod') {
  23569. div = res.div.neg();
  23570. }
  23571. return {
  23572. div: div,
  23573. mod: res.mod
  23574. };
  23575. }
  23576. if ((this.negative & num.negative) !== 0) {
  23577. res = this.neg().divmod(num.neg(), mode);
  23578. if (mode !== 'div') {
  23579. mod = res.mod.neg();
  23580. if (positive && mod.negative !== 0) {
  23581. mod.isub(num);
  23582. }
  23583. }
  23584. return {
  23585. div: res.div,
  23586. mod: mod
  23587. };
  23588. }
  23589. // Both numbers are positive at this point
  23590. // Strip both numbers to approximate shift value
  23591. if (num.length > this.length || this.cmp(num) < 0) {
  23592. return {
  23593. div: new BN(0),
  23594. mod: this
  23595. };
  23596. }
  23597. // Very short reduction
  23598. if (num.length === 1) {
  23599. if (mode === 'div') {
  23600. return {
  23601. div: this.divn(num.words[0]),
  23602. mod: null
  23603. };
  23604. }
  23605. if (mode === 'mod') {
  23606. return {
  23607. div: null,
  23608. mod: new BN(this.modrn(num.words[0]))
  23609. };
  23610. }
  23611. return {
  23612. div: this.divn(num.words[0]),
  23613. mod: new BN(this.modrn(num.words[0]))
  23614. };
  23615. }
  23616. return this._wordDiv(num, mode);
  23617. };
  23618. // Find `this` / `num`
  23619. BN.prototype.div = function div(num) {
  23620. return this.divmod(num, 'div', false).div;
  23621. };
  23622. // Find `this` % `num`
  23623. BN.prototype.mod = function mod(num) {
  23624. return this.divmod(num, 'mod', false).mod;
  23625. };
  23626. BN.prototype.umod = function umod(num) {
  23627. return this.divmod(num, 'mod', true).mod;
  23628. };
  23629. // Find Round(`this` / `num`)
  23630. BN.prototype.divRound = function divRound(num) {
  23631. var dm = this.divmod(num);
  23632. // Fast case - exact division
  23633. if (dm.mod.isZero()) return dm.div;
  23634. var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
  23635. var half = num.ushrn(1);
  23636. var r2 = num.andln(1);
  23637. var cmp = mod.cmp(half);
  23638. // Round down
  23639. if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
  23640. // Round up
  23641. return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  23642. };
  23643. BN.prototype.modrn = function modrn(num) {
  23644. var isNegNum = num < 0;
  23645. if (isNegNum) num = -num;
  23646. assert(num <= 0x3ffffff);
  23647. var p = (1 << 26) % num;
  23648. var acc = 0;
  23649. for (var i = this.length - 1; i >= 0; i--) {
  23650. acc = (p * acc + (this.words[i] | 0)) % num;
  23651. }
  23652. return isNegNum ? -acc : acc;
  23653. };
  23654. // WARNING: DEPRECATED
  23655. BN.prototype.modn = function modn(num) {
  23656. return this.modrn(num);
  23657. };
  23658. // In-place division by number
  23659. BN.prototype.idivn = function idivn(num) {
  23660. var isNegNum = num < 0;
  23661. if (isNegNum) num = -num;
  23662. assert(num <= 0x3ffffff);
  23663. var carry = 0;
  23664. for (var i = this.length - 1; i >= 0; i--) {
  23665. var w = (this.words[i] | 0) + carry * 0x4000000;
  23666. this.words[i] = w / num | 0;
  23667. carry = w % num;
  23668. }
  23669. this._strip();
  23670. return isNegNum ? this.ineg() : this;
  23671. };
  23672. BN.prototype.divn = function divn(num) {
  23673. return this.clone().idivn(num);
  23674. };
  23675. BN.prototype.egcd = function egcd(p) {
  23676. assert(p.negative === 0);
  23677. assert(!p.isZero());
  23678. var x = this;
  23679. var y = p.clone();
  23680. if (x.negative !== 0) {
  23681. x = x.umod(p);
  23682. } else {
  23683. x = x.clone();
  23684. }
  23685. // A * x + B * y = x
  23686. var A = new BN(1);
  23687. var B = new BN(0);
  23688. // C * x + D * y = y
  23689. var C = new BN(0);
  23690. var D = new BN(1);
  23691. var g = 0;
  23692. while (x.isEven() && y.isEven()) {
  23693. x.iushrn(1);
  23694. y.iushrn(1);
  23695. ++g;
  23696. }
  23697. var yp = y.clone();
  23698. var xp = x.clone();
  23699. while (!x.isZero()) {
  23700. for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  23701. if (i > 0) {
  23702. x.iushrn(i);
  23703. while (i-- > 0) {
  23704. if (A.isOdd() || B.isOdd()) {
  23705. A.iadd(yp);
  23706. B.isub(xp);
  23707. }
  23708. A.iushrn(1);
  23709. B.iushrn(1);
  23710. }
  23711. }
  23712. for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  23713. if (j > 0) {
  23714. y.iushrn(j);
  23715. while (j-- > 0) {
  23716. if (C.isOdd() || D.isOdd()) {
  23717. C.iadd(yp);
  23718. D.isub(xp);
  23719. }
  23720. C.iushrn(1);
  23721. D.iushrn(1);
  23722. }
  23723. }
  23724. if (x.cmp(y) >= 0) {
  23725. x.isub(y);
  23726. A.isub(C);
  23727. B.isub(D);
  23728. } else {
  23729. y.isub(x);
  23730. C.isub(A);
  23731. D.isub(B);
  23732. }
  23733. }
  23734. return {
  23735. a: C,
  23736. b: D,
  23737. gcd: y.iushln(g)
  23738. };
  23739. };
  23740. // This is reduced incarnation of the binary EEA
  23741. // above, designated to invert members of the
  23742. // _prime_ fields F(p) at a maximal speed
  23743. BN.prototype._invmp = function _invmp(p) {
  23744. assert(p.negative === 0);
  23745. assert(!p.isZero());
  23746. var a = this;
  23747. var b = p.clone();
  23748. if (a.negative !== 0) {
  23749. a = a.umod(p);
  23750. } else {
  23751. a = a.clone();
  23752. }
  23753. var x1 = new BN(1);
  23754. var x2 = new BN(0);
  23755. var delta = b.clone();
  23756. while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
  23757. for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  23758. if (i > 0) {
  23759. a.iushrn(i);
  23760. while (i-- > 0) {
  23761. if (x1.isOdd()) {
  23762. x1.iadd(delta);
  23763. }
  23764. x1.iushrn(1);
  23765. }
  23766. }
  23767. for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  23768. if (j > 0) {
  23769. b.iushrn(j);
  23770. while (j-- > 0) {
  23771. if (x2.isOdd()) {
  23772. x2.iadd(delta);
  23773. }
  23774. x2.iushrn(1);
  23775. }
  23776. }
  23777. if (a.cmp(b) >= 0) {
  23778. a.isub(b);
  23779. x1.isub(x2);
  23780. } else {
  23781. b.isub(a);
  23782. x2.isub(x1);
  23783. }
  23784. }
  23785. var res;
  23786. if (a.cmpn(1) === 0) {
  23787. res = x1;
  23788. } else {
  23789. res = x2;
  23790. }
  23791. if (res.cmpn(0) < 0) {
  23792. res.iadd(p);
  23793. }
  23794. return res;
  23795. };
  23796. BN.prototype.gcd = function gcd(num) {
  23797. if (this.isZero()) return num.abs();
  23798. if (num.isZero()) return this.abs();
  23799. var a = this.clone();
  23800. var b = num.clone();
  23801. a.negative = 0;
  23802. b.negative = 0;
  23803. // Remove common factor of two
  23804. for (var shift = 0; a.isEven() && b.isEven(); shift++) {
  23805. a.iushrn(1);
  23806. b.iushrn(1);
  23807. }
  23808. do {
  23809. while (a.isEven()) {
  23810. a.iushrn(1);
  23811. }
  23812. while (b.isEven()) {
  23813. b.iushrn(1);
  23814. }
  23815. var r = a.cmp(b);
  23816. if (r < 0) {
  23817. // Swap `a` and `b` to make `a` always bigger than `b`
  23818. var t = a;
  23819. a = b;
  23820. b = t;
  23821. } else if (r === 0 || b.cmpn(1) === 0) {
  23822. break;
  23823. }
  23824. a.isub(b);
  23825. } while (true);
  23826. return b.iushln(shift);
  23827. };
  23828. // Invert number in the field F(num)
  23829. BN.prototype.invm = function invm(num) {
  23830. return this.egcd(num).a.umod(num);
  23831. };
  23832. BN.prototype.isEven = function isEven() {
  23833. return (this.words[0] & 1) === 0;
  23834. };
  23835. BN.prototype.isOdd = function isOdd() {
  23836. return (this.words[0] & 1) === 1;
  23837. };
  23838. // And first word and num
  23839. BN.prototype.andln = function andln(num) {
  23840. return this.words[0] & num;
  23841. };
  23842. // Increment at the bit position in-line
  23843. BN.prototype.bincn = function bincn(bit) {
  23844. assert(typeof bit === 'number');
  23845. var r = bit % 26;
  23846. var s = (bit - r) / 26;
  23847. var q = 1 << r;
  23848. // Fast case: bit is much higher than all existing words
  23849. if (this.length <= s) {
  23850. this._expand(s + 1);
  23851. this.words[s] |= q;
  23852. return this;
  23853. }
  23854. // Add bit and propagate, if needed
  23855. var carry = q;
  23856. for (var i = s; carry !== 0 && i < this.length; i++) {
  23857. var w = this.words[i] | 0;
  23858. w += carry;
  23859. carry = w >>> 26;
  23860. w &= 0x3ffffff;
  23861. this.words[i] = w;
  23862. }
  23863. if (carry !== 0) {
  23864. this.words[i] = carry;
  23865. this.length++;
  23866. }
  23867. return this;
  23868. };
  23869. BN.prototype.isZero = function isZero() {
  23870. return this.length === 1 && this.words[0] === 0;
  23871. };
  23872. BN.prototype.cmpn = function cmpn(num) {
  23873. var negative = num < 0;
  23874. if (this.negative !== 0 && !negative) return -1;
  23875. if (this.negative === 0 && negative) return 1;
  23876. this._strip();
  23877. var res;
  23878. if (this.length > 1) {
  23879. res = 1;
  23880. } else {
  23881. if (negative) {
  23882. num = -num;
  23883. }
  23884. assert(num <= 0x3ffffff, 'Number is too big');
  23885. var w = this.words[0] | 0;
  23886. res = w === num ? 0 : w < num ? -1 : 1;
  23887. }
  23888. if (this.negative !== 0) return -res | 0;
  23889. return res;
  23890. };
  23891. // Compare two numbers and return:
  23892. // 1 - if `this` > `num`
  23893. // 0 - if `this` == `num`
  23894. // -1 - if `this` < `num`
  23895. BN.prototype.cmp = function cmp(num) {
  23896. if (this.negative !== 0 && num.negative === 0) return -1;
  23897. if (this.negative === 0 && num.negative !== 0) return 1;
  23898. var res = this.ucmp(num);
  23899. if (this.negative !== 0) return -res | 0;
  23900. return res;
  23901. };
  23902. // Unsigned comparison
  23903. BN.prototype.ucmp = function ucmp(num) {
  23904. // At this point both numbers have the same sign
  23905. if (this.length > num.length) return 1;
  23906. if (this.length < num.length) return -1;
  23907. var res = 0;
  23908. for (var i = this.length - 1; i >= 0; i--) {
  23909. var a = this.words[i] | 0;
  23910. var b = num.words[i] | 0;
  23911. if (a === b) continue;
  23912. if (a < b) {
  23913. res = -1;
  23914. } else if (a > b) {
  23915. res = 1;
  23916. }
  23917. break;
  23918. }
  23919. return res;
  23920. };
  23921. BN.prototype.gtn = function gtn(num) {
  23922. return this.cmpn(num) === 1;
  23923. };
  23924. BN.prototype.gt = function gt(num) {
  23925. return this.cmp(num) === 1;
  23926. };
  23927. BN.prototype.gten = function gten(num) {
  23928. return this.cmpn(num) >= 0;
  23929. };
  23930. BN.prototype.gte = function gte(num) {
  23931. return this.cmp(num) >= 0;
  23932. };
  23933. BN.prototype.ltn = function ltn(num) {
  23934. return this.cmpn(num) === -1;
  23935. };
  23936. BN.prototype.lt = function lt(num) {
  23937. return this.cmp(num) === -1;
  23938. };
  23939. BN.prototype.lten = function lten(num) {
  23940. return this.cmpn(num) <= 0;
  23941. };
  23942. BN.prototype.lte = function lte(num) {
  23943. return this.cmp(num) <= 0;
  23944. };
  23945. BN.prototype.eqn = function eqn(num) {
  23946. return this.cmpn(num) === 0;
  23947. };
  23948. BN.prototype.eq = function eq(num) {
  23949. return this.cmp(num) === 0;
  23950. };
  23951. //
  23952. // A reduce context, could be using montgomery or something better, depending
  23953. // on the `m` itself.
  23954. //
  23955. BN.red = function red(num) {
  23956. return new Red(num);
  23957. };
  23958. BN.prototype.toRed = function toRed(ctx) {
  23959. assert(!this.red, 'Already a number in reduction context');
  23960. assert(this.negative === 0, 'red works only with positives');
  23961. return ctx.convertTo(this)._forceRed(ctx);
  23962. };
  23963. BN.prototype.fromRed = function fromRed() {
  23964. assert(this.red, 'fromRed works only with numbers in reduction context');
  23965. return this.red.convertFrom(this);
  23966. };
  23967. BN.prototype._forceRed = function _forceRed(ctx) {
  23968. this.red = ctx;
  23969. return this;
  23970. };
  23971. BN.prototype.forceRed = function forceRed(ctx) {
  23972. assert(!this.red, 'Already a number in reduction context');
  23973. return this._forceRed(ctx);
  23974. };
  23975. BN.prototype.redAdd = function redAdd(num) {
  23976. assert(this.red, 'redAdd works only with red numbers');
  23977. return this.red.add(this, num);
  23978. };
  23979. BN.prototype.redIAdd = function redIAdd(num) {
  23980. assert(this.red, 'redIAdd works only with red numbers');
  23981. return this.red.iadd(this, num);
  23982. };
  23983. BN.prototype.redSub = function redSub(num) {
  23984. assert(this.red, 'redSub works only with red numbers');
  23985. return this.red.sub(this, num);
  23986. };
  23987. BN.prototype.redISub = function redISub(num) {
  23988. assert(this.red, 'redISub works only with red numbers');
  23989. return this.red.isub(this, num);
  23990. };
  23991. BN.prototype.redShl = function redShl(num) {
  23992. assert(this.red, 'redShl works only with red numbers');
  23993. return this.red.shl(this, num);
  23994. };
  23995. BN.prototype.redMul = function redMul(num) {
  23996. assert(this.red, 'redMul works only with red numbers');
  23997. this.red._verify2(this, num);
  23998. return this.red.mul(this, num);
  23999. };
  24000. BN.prototype.redIMul = function redIMul(num) {
  24001. assert(this.red, 'redMul works only with red numbers');
  24002. this.red._verify2(this, num);
  24003. return this.red.imul(this, num);
  24004. };
  24005. BN.prototype.redSqr = function redSqr() {
  24006. assert(this.red, 'redSqr works only with red numbers');
  24007. this.red._verify1(this);
  24008. return this.red.sqr(this);
  24009. };
  24010. BN.prototype.redISqr = function redISqr() {
  24011. assert(this.red, 'redISqr works only with red numbers');
  24012. this.red._verify1(this);
  24013. return this.red.isqr(this);
  24014. };
  24015. // Square root over p
  24016. BN.prototype.redSqrt = function redSqrt() {
  24017. assert(this.red, 'redSqrt works only with red numbers');
  24018. this.red._verify1(this);
  24019. return this.red.sqrt(this);
  24020. };
  24021. BN.prototype.redInvm = function redInvm() {
  24022. assert(this.red, 'redInvm works only with red numbers');
  24023. this.red._verify1(this);
  24024. return this.red.invm(this);
  24025. };
  24026. // Return negative clone of `this` % `red modulo`
  24027. BN.prototype.redNeg = function redNeg() {
  24028. assert(this.red, 'redNeg works only with red numbers');
  24029. this.red._verify1(this);
  24030. return this.red.neg(this);
  24031. };
  24032. BN.prototype.redPow = function redPow(num) {
  24033. assert(this.red && !num.red, 'redPow(normalNum)');
  24034. this.red._verify1(this);
  24035. return this.red.pow(this, num);
  24036. };
  24037. // Prime numbers with efficient reduction
  24038. var primes = {
  24039. k256: null,
  24040. p224: null,
  24041. p192: null,
  24042. p25519: null
  24043. };
  24044. // Pseudo-Mersenne prime
  24045. function MPrime(name, p) {
  24046. // P = 2 ^ N - K
  24047. this.name = name;
  24048. this.p = new BN(p, 16);
  24049. this.n = this.p.bitLength();
  24050. this.k = new BN(1).iushln(this.n).isub(this.p);
  24051. this.tmp = this._tmp();
  24052. }
  24053. MPrime.prototype._tmp = function _tmp() {
  24054. var tmp = new BN(null);
  24055. tmp.words = new Array(Math.ceil(this.n / 13));
  24056. return tmp;
  24057. };
  24058. MPrime.prototype.ireduce = function ireduce(num) {
  24059. // Assumes that `num` is less than `P^2`
  24060. // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
  24061. var r = num;
  24062. var rlen;
  24063. do {
  24064. this.split(r, this.tmp);
  24065. r = this.imulK(r);
  24066. r = r.iadd(this.tmp);
  24067. rlen = r.bitLength();
  24068. } while (rlen > this.n);
  24069. var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
  24070. if (cmp === 0) {
  24071. r.words[0] = 0;
  24072. r.length = 1;
  24073. } else if (cmp > 0) {
  24074. r.isub(this.p);
  24075. } else {
  24076. if (r.strip !== undefined) {
  24077. // r is a BN v4 instance
  24078. r.strip();
  24079. } else {
  24080. // r is a BN v5 instance
  24081. r._strip();
  24082. }
  24083. }
  24084. return r;
  24085. };
  24086. MPrime.prototype.split = function split(input, out) {
  24087. input.iushrn(this.n, 0, out);
  24088. };
  24089. MPrime.prototype.imulK = function imulK(num) {
  24090. return num.imul(this.k);
  24091. };
  24092. function K256() {
  24093. MPrime.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  24094. }
  24095. inherits(K256, MPrime);
  24096. K256.prototype.split = function split(input, output) {
  24097. // 256 = 9 * 26 + 22
  24098. var mask = 0x3fffff;
  24099. var outLen = Math.min(input.length, 9);
  24100. for (var i = 0; i < outLen; i++) {
  24101. output.words[i] = input.words[i];
  24102. }
  24103. output.length = outLen;
  24104. if (input.length <= 9) {
  24105. input.words[0] = 0;
  24106. input.length = 1;
  24107. return;
  24108. }
  24109. // Shift by 9 limbs
  24110. var prev = input.words[9];
  24111. output.words[output.length++] = prev & mask;
  24112. for (i = 10; i < input.length; i++) {
  24113. var next = input.words[i] | 0;
  24114. input.words[i - 10] = (next & mask) << 4 | prev >>> 22;
  24115. prev = next;
  24116. }
  24117. prev >>>= 22;
  24118. input.words[i - 10] = prev;
  24119. if (prev === 0 && input.length > 10) {
  24120. input.length -= 10;
  24121. } else {
  24122. input.length -= 9;
  24123. }
  24124. };
  24125. K256.prototype.imulK = function imulK(num) {
  24126. // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
  24127. num.words[num.length] = 0;
  24128. num.words[num.length + 1] = 0;
  24129. num.length += 2;
  24130. // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
  24131. var lo = 0;
  24132. for (var i = 0; i < num.length; i++) {
  24133. var w = num.words[i] | 0;
  24134. lo += w * 0x3d1;
  24135. num.words[i] = lo & 0x3ffffff;
  24136. lo = w * 0x40 + (lo / 0x4000000 | 0);
  24137. }
  24138. // Fast length reduction
  24139. if (num.words[num.length - 1] === 0) {
  24140. num.length--;
  24141. if (num.words[num.length - 1] === 0) {
  24142. num.length--;
  24143. }
  24144. }
  24145. return num;
  24146. };
  24147. function P224() {
  24148. MPrime.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  24149. }
  24150. inherits(P224, MPrime);
  24151. function P192() {
  24152. MPrime.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  24153. }
  24154. inherits(P192, MPrime);
  24155. function P25519() {
  24156. // 2 ^ 255 - 19
  24157. MPrime.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  24158. }
  24159. inherits(P25519, MPrime);
  24160. P25519.prototype.imulK = function imulK(num) {
  24161. // K = 0x13
  24162. var carry = 0;
  24163. for (var i = 0; i < num.length; i++) {
  24164. var hi = (num.words[i] | 0) * 0x13 + carry;
  24165. var lo = hi & 0x3ffffff;
  24166. hi >>>= 26;
  24167. num.words[i] = lo;
  24168. carry = hi;
  24169. }
  24170. if (carry !== 0) {
  24171. num.words[num.length++] = carry;
  24172. }
  24173. return num;
  24174. };
  24175. // Exported mostly for testing purposes, use plain name instead
  24176. BN._prime = function prime(name) {
  24177. // Cached version of prime
  24178. if (primes[name]) return primes[name];
  24179. var prime;
  24180. if (name === 'k256') {
  24181. prime = new K256();
  24182. } else if (name === 'p224') {
  24183. prime = new P224();
  24184. } else if (name === 'p192') {
  24185. prime = new P192();
  24186. } else if (name === 'p25519') {
  24187. prime = new P25519();
  24188. } else {
  24189. throw new Error('Unknown prime ' + name);
  24190. }
  24191. primes[name] = prime;
  24192. return prime;
  24193. };
  24194. //
  24195. // Base reduction engine
  24196. //
  24197. function Red(m) {
  24198. if (typeof m === 'string') {
  24199. var prime = BN._prime(m);
  24200. this.m = prime.p;
  24201. this.prime = prime;
  24202. } else {
  24203. assert(m.gtn(1), 'modulus must be greater than 1');
  24204. this.m = m;
  24205. this.prime = null;
  24206. }
  24207. }
  24208. Red.prototype._verify1 = function _verify1(a) {
  24209. assert(a.negative === 0, 'red works only with positives');
  24210. assert(a.red, 'red works only with red numbers');
  24211. };
  24212. Red.prototype._verify2 = function _verify2(a, b) {
  24213. assert((a.negative | b.negative) === 0, 'red works only with positives');
  24214. assert(a.red && a.red === b.red, 'red works only with red numbers');
  24215. };
  24216. Red.prototype.imod = function imod(a) {
  24217. if (this.prime) return this.prime.ireduce(a)._forceRed(this);
  24218. move(a, a.umod(this.m)._forceRed(this));
  24219. return a;
  24220. };
  24221. Red.prototype.neg = function neg(a) {
  24222. if (a.isZero()) {
  24223. return a.clone();
  24224. }
  24225. return this.m.sub(a)._forceRed(this);
  24226. };
  24227. Red.prototype.add = function add(a, b) {
  24228. this._verify2(a, b);
  24229. var res = a.add(b);
  24230. if (res.cmp(this.m) >= 0) {
  24231. res.isub(this.m);
  24232. }
  24233. return res._forceRed(this);
  24234. };
  24235. Red.prototype.iadd = function iadd(a, b) {
  24236. this._verify2(a, b);
  24237. var res = a.iadd(b);
  24238. if (res.cmp(this.m) >= 0) {
  24239. res.isub(this.m);
  24240. }
  24241. return res;
  24242. };
  24243. Red.prototype.sub = function sub(a, b) {
  24244. this._verify2(a, b);
  24245. var res = a.sub(b);
  24246. if (res.cmpn(0) < 0) {
  24247. res.iadd(this.m);
  24248. }
  24249. return res._forceRed(this);
  24250. };
  24251. Red.prototype.isub = function isub(a, b) {
  24252. this._verify2(a, b);
  24253. var res = a.isub(b);
  24254. if (res.cmpn(0) < 0) {
  24255. res.iadd(this.m);
  24256. }
  24257. return res;
  24258. };
  24259. Red.prototype.shl = function shl(a, num) {
  24260. this._verify1(a);
  24261. return this.imod(a.ushln(num));
  24262. };
  24263. Red.prototype.imul = function imul(a, b) {
  24264. this._verify2(a, b);
  24265. return this.imod(a.imul(b));
  24266. };
  24267. Red.prototype.mul = function mul(a, b) {
  24268. this._verify2(a, b);
  24269. return this.imod(a.mul(b));
  24270. };
  24271. Red.prototype.isqr = function isqr(a) {
  24272. return this.imul(a, a.clone());
  24273. };
  24274. Red.prototype.sqr = function sqr(a) {
  24275. return this.mul(a, a);
  24276. };
  24277. Red.prototype.sqrt = function sqrt(a) {
  24278. if (a.isZero()) return a.clone();
  24279. var mod3 = this.m.andln(3);
  24280. assert(mod3 % 2 === 1);
  24281. // Fast case
  24282. if (mod3 === 3) {
  24283. var pow = this.m.add(new BN(1)).iushrn(2);
  24284. return this.pow(a, pow);
  24285. }
  24286. // Tonelli-Shanks algorithm (Totally unoptimized and slow)
  24287. //
  24288. // Find Q and S, that Q * 2 ^ S = (P - 1)
  24289. var q = this.m.subn(1);
  24290. var s = 0;
  24291. while (!q.isZero() && q.andln(1) === 0) {
  24292. s++;
  24293. q.iushrn(1);
  24294. }
  24295. assert(!q.isZero());
  24296. var one = new BN(1).toRed(this);
  24297. var nOne = one.redNeg();
  24298. // Find quadratic non-residue
  24299. // NOTE: Max is such because of generalized Riemann hypothesis.
  24300. var lpow = this.m.subn(1).iushrn(1);
  24301. var z = this.m.bitLength();
  24302. z = new BN(2 * z * z).toRed(this);
  24303. while (this.pow(z, lpow).cmp(nOne) !== 0) {
  24304. z.redIAdd(nOne);
  24305. }
  24306. var c = this.pow(z, q);
  24307. var r = this.pow(a, q.addn(1).iushrn(1));
  24308. var t = this.pow(a, q);
  24309. var m = s;
  24310. while (t.cmp(one) !== 0) {
  24311. var tmp = t;
  24312. for (var i = 0; tmp.cmp(one) !== 0; i++) {
  24313. tmp = tmp.redSqr();
  24314. }
  24315. assert(i < m);
  24316. var b = this.pow(c, new BN(1).iushln(m - i - 1));
  24317. r = r.redMul(b);
  24318. c = b.redSqr();
  24319. t = t.redMul(c);
  24320. m = i;
  24321. }
  24322. return r;
  24323. };
  24324. Red.prototype.invm = function invm(a) {
  24325. var inv = a._invmp(this.m);
  24326. if (inv.negative !== 0) {
  24327. inv.negative = 0;
  24328. return this.imod(inv).redNeg();
  24329. } else {
  24330. return this.imod(inv);
  24331. }
  24332. };
  24333. Red.prototype.pow = function pow(a, num) {
  24334. if (num.isZero()) return new BN(1).toRed(this);
  24335. if (num.cmpn(1) === 0) return a.clone();
  24336. var windowSize = 4;
  24337. var wnd = new Array(1 << windowSize);
  24338. wnd[0] = new BN(1).toRed(this);
  24339. wnd[1] = a;
  24340. for (var i = 2; i < wnd.length; i++) {
  24341. wnd[i] = this.mul(wnd[i - 1], a);
  24342. }
  24343. var res = wnd[0];
  24344. var current = 0;
  24345. var currentLen = 0;
  24346. var start = num.bitLength() % 26;
  24347. if (start === 0) {
  24348. start = 26;
  24349. }
  24350. for (i = num.length - 1; i >= 0; i--) {
  24351. var word = num.words[i];
  24352. for (var j = start - 1; j >= 0; j--) {
  24353. var bit = word >> j & 1;
  24354. if (res !== wnd[0]) {
  24355. res = this.sqr(res);
  24356. }
  24357. if (bit === 0 && current === 0) {
  24358. currentLen = 0;
  24359. continue;
  24360. }
  24361. current <<= 1;
  24362. current |= bit;
  24363. currentLen++;
  24364. if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
  24365. res = this.mul(res, wnd[current]);
  24366. currentLen = 0;
  24367. current = 0;
  24368. }
  24369. start = 26;
  24370. }
  24371. return res;
  24372. };
  24373. Red.prototype.convertTo = function convertTo(num) {
  24374. var r = num.umod(this.m);
  24375. return r === num ? r.clone() : r;
  24376. };
  24377. Red.prototype.convertFrom = function convertFrom(num) {
  24378. var res = num.clone();
  24379. res.red = null;
  24380. return res;
  24381. };
  24382. //
  24383. // Montgomery method engine
  24384. //
  24385. BN.mont = function mont(num) {
  24386. return new Mont(num);
  24387. };
  24388. function Mont(m) {
  24389. Red.call(this, m);
  24390. this.shift = this.m.bitLength();
  24391. if (this.shift % 26 !== 0) {
  24392. this.shift += 26 - this.shift % 26;
  24393. }
  24394. this.r = new BN(1).iushln(this.shift);
  24395. this.r2 = this.imod(this.r.sqr());
  24396. this.rinv = this.r._invmp(this.m);
  24397. this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
  24398. this.minv = this.minv.umod(this.r);
  24399. this.minv = this.r.sub(this.minv);
  24400. }
  24401. inherits(Mont, Red);
  24402. Mont.prototype.convertTo = function convertTo(num) {
  24403. return this.imod(num.ushln(this.shift));
  24404. };
  24405. Mont.prototype.convertFrom = function convertFrom(num) {
  24406. var r = this.imod(num.mul(this.rinv));
  24407. r.red = null;
  24408. return r;
  24409. };
  24410. Mont.prototype.imul = function imul(a, b) {
  24411. if (a.isZero() || b.isZero()) {
  24412. a.words[0] = 0;
  24413. a.length = 1;
  24414. return a;
  24415. }
  24416. var t = a.imul(b);
  24417. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  24418. var u = t.isub(c).iushrn(this.shift);
  24419. var res = u;
  24420. if (u.cmp(this.m) >= 0) {
  24421. res = u.isub(this.m);
  24422. } else if (u.cmpn(0) < 0) {
  24423. res = u.iadd(this.m);
  24424. }
  24425. return res._forceRed(this);
  24426. };
  24427. Mont.prototype.mul = function mul(a, b) {
  24428. if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
  24429. var t = a.mul(b);
  24430. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  24431. var u = t.isub(c).iushrn(this.shift);
  24432. var res = u;
  24433. if (u.cmp(this.m) >= 0) {
  24434. res = u.isub(this.m);
  24435. } else if (u.cmpn(0) < 0) {
  24436. res = u.iadd(this.m);
  24437. }
  24438. return res._forceRed(this);
  24439. };
  24440. Mont.prototype.invm = function invm(a) {
  24441. // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
  24442. var res = this.imod(a._invmp(this.m).mul(this.r2));
  24443. return res._forceRed(this);
  24444. };
  24445. })(typeof module === 'undefined' || module, void 0);
  24446. },{"buffer":188}],187:[function(require,module,exports){
  24447. "use strict";
  24448. var r;
  24449. module.exports = function rand(len) {
  24450. if (!r) r = new Rand(null);
  24451. return r.generate(len);
  24452. };
  24453. function Rand(rand) {
  24454. this.rand = rand;
  24455. }
  24456. module.exports.Rand = Rand;
  24457. Rand.prototype.generate = function generate(len) {
  24458. return this._rand(len);
  24459. };
  24460. // Emulate crypto API using randy
  24461. Rand.prototype._rand = function _rand(n) {
  24462. if (this.rand.getBytes) return this.rand.getBytes(n);
  24463. var res = new Uint8Array(n);
  24464. for (var i = 0; i < res.length; i++) res[i] = this.rand.getByte();
  24465. return res;
  24466. };
  24467. if (typeof self === 'object') {
  24468. if (self.crypto && self.crypto.getRandomValues) {
  24469. // Modern browsers
  24470. Rand.prototype._rand = function _rand(n) {
  24471. var arr = new Uint8Array(n);
  24472. self.crypto.getRandomValues(arr);
  24473. return arr;
  24474. };
  24475. } else if (self.msCrypto && self.msCrypto.getRandomValues) {
  24476. // IE
  24477. Rand.prototype._rand = function _rand(n) {
  24478. var arr = new Uint8Array(n);
  24479. self.msCrypto.getRandomValues(arr);
  24480. return arr;
  24481. };
  24482. // Safari's WebWorkers do not have `crypto`
  24483. } else if (typeof window === 'object') {
  24484. // Old junk
  24485. Rand.prototype._rand = function () {
  24486. throw new Error('Not implemented yet');
  24487. };
  24488. }
  24489. } else {
  24490. // Node.js or Web worker with no crypto support
  24491. try {
  24492. var crypto = require('crypto');
  24493. if (typeof crypto.randomBytes !== 'function') throw new Error('Not supported');
  24494. Rand.prototype._rand = function _rand(n) {
  24495. return crypto.randomBytes(n);
  24496. };
  24497. } catch (e) {}
  24498. }
  24499. },{"crypto":188}],188:[function(require,module,exports){
  24500. "use strict";
  24501. },{}],189:[function(require,module,exports){
  24502. "use strict";
  24503. // based on the aes implimentation in triple sec
  24504. // https://github.com/keybase/triplesec
  24505. // which is in turn based on the one from crypto-js
  24506. // https://code.google.com/p/crypto-js/
  24507. var Buffer = require('safe-buffer').Buffer;
  24508. function asUInt32Array(buf) {
  24509. if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
  24510. var len = buf.length / 4 | 0;
  24511. var out = new Array(len);
  24512. for (var i = 0; i < len; i++) {
  24513. out[i] = buf.readUInt32BE(i * 4);
  24514. }
  24515. return out;
  24516. }
  24517. function scrubVec(v) {
  24518. for (var i = 0; i < v.length; v++) {
  24519. v[i] = 0;
  24520. }
  24521. }
  24522. function cryptBlock(M, keySchedule, SUB_MIX, SBOX, nRounds) {
  24523. var SUB_MIX0 = SUB_MIX[0];
  24524. var SUB_MIX1 = SUB_MIX[1];
  24525. var SUB_MIX2 = SUB_MIX[2];
  24526. var SUB_MIX3 = SUB_MIX[3];
  24527. var s0 = M[0] ^ keySchedule[0];
  24528. var s1 = M[1] ^ keySchedule[1];
  24529. var s2 = M[2] ^ keySchedule[2];
  24530. var s3 = M[3] ^ keySchedule[3];
  24531. var t0, t1, t2, t3;
  24532. var ksRow = 4;
  24533. for (var round = 1; round < nRounds; round++) {
  24534. t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[s1 >>> 16 & 0xff] ^ SUB_MIX2[s2 >>> 8 & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++];
  24535. t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[s2 >>> 16 & 0xff] ^ SUB_MIX2[s3 >>> 8 & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++];
  24536. t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[s3 >>> 16 & 0xff] ^ SUB_MIX2[s0 >>> 8 & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++];
  24537. t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[s0 >>> 16 & 0xff] ^ SUB_MIX2[s1 >>> 8 & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++];
  24538. s0 = t0;
  24539. s1 = t1;
  24540. s2 = t2;
  24541. s3 = t3;
  24542. }
  24543. t0 = (SBOX[s0 >>> 24] << 24 | SBOX[s1 >>> 16 & 0xff] << 16 | SBOX[s2 >>> 8 & 0xff] << 8 | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
  24544. t1 = (SBOX[s1 >>> 24] << 24 | SBOX[s2 >>> 16 & 0xff] << 16 | SBOX[s3 >>> 8 & 0xff] << 8 | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
  24545. t2 = (SBOX[s2 >>> 24] << 24 | SBOX[s3 >>> 16 & 0xff] << 16 | SBOX[s0 >>> 8 & 0xff] << 8 | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
  24546. t3 = (SBOX[s3 >>> 24] << 24 | SBOX[s0 >>> 16 & 0xff] << 16 | SBOX[s1 >>> 8 & 0xff] << 8 | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
  24547. t0 = t0 >>> 0;
  24548. t1 = t1 >>> 0;
  24549. t2 = t2 >>> 0;
  24550. t3 = t3 >>> 0;
  24551. return [t0, t1, t2, t3];
  24552. }
  24553. // AES constants
  24554. var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  24555. var G = function () {
  24556. // Compute double table
  24557. var d = new Array(256);
  24558. for (var j = 0; j < 256; j++) {
  24559. if (j < 128) {
  24560. d[j] = j << 1;
  24561. } else {
  24562. d[j] = j << 1 ^ 0x11b;
  24563. }
  24564. }
  24565. var SBOX = [];
  24566. var INV_SBOX = [];
  24567. var SUB_MIX = [[], [], [], []];
  24568. var INV_SUB_MIX = [[], [], [], []];
  24569. // Walk GF(2^8)
  24570. var x = 0;
  24571. var xi = 0;
  24572. for (var i = 0; i < 256; ++i) {
  24573. // Compute sbox
  24574. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  24575. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  24576. SBOX[x] = sx;
  24577. INV_SBOX[sx] = x;
  24578. // Compute multiplication
  24579. var x2 = d[x];
  24580. var x4 = d[x2];
  24581. var x8 = d[x4];
  24582. // Compute sub bytes, mix columns tables
  24583. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  24584. SUB_MIX[0][x] = t << 24 | t >>> 8;
  24585. SUB_MIX[1][x] = t << 16 | t >>> 16;
  24586. SUB_MIX[2][x] = t << 8 | t >>> 24;
  24587. SUB_MIX[3][x] = t;
  24588. // Compute inv sub bytes, inv mix columns tables
  24589. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  24590. INV_SUB_MIX[0][sx] = t << 24 | t >>> 8;
  24591. INV_SUB_MIX[1][sx] = t << 16 | t >>> 16;
  24592. INV_SUB_MIX[2][sx] = t << 8 | t >>> 24;
  24593. INV_SUB_MIX[3][sx] = t;
  24594. if (x === 0) {
  24595. x = xi = 1;
  24596. } else {
  24597. x = x2 ^ d[d[d[x8 ^ x2]]];
  24598. xi ^= d[d[xi]];
  24599. }
  24600. }
  24601. return {
  24602. SBOX: SBOX,
  24603. INV_SBOX: INV_SBOX,
  24604. SUB_MIX: SUB_MIX,
  24605. INV_SUB_MIX: INV_SUB_MIX
  24606. };
  24607. }();
  24608. function AES(key) {
  24609. this._key = asUInt32Array(key);
  24610. this._reset();
  24611. }
  24612. AES.blockSize = 4 * 4;
  24613. AES.keySize = 256 / 8;
  24614. AES.prototype.blockSize = AES.blockSize;
  24615. AES.prototype.keySize = AES.keySize;
  24616. AES.prototype._reset = function () {
  24617. var keyWords = this._key;
  24618. var keySize = keyWords.length;
  24619. var nRounds = keySize + 6;
  24620. var ksRows = (nRounds + 1) * 4;
  24621. var keySchedule = [];
  24622. for (var k = 0; k < keySize; k++) {
  24623. keySchedule[k] = keyWords[k];
  24624. }
  24625. for (k = keySize; k < ksRows; k++) {
  24626. var t = keySchedule[k - 1];
  24627. if (k % keySize === 0) {
  24628. t = t << 8 | t >>> 24;
  24629. t = G.SBOX[t >>> 24] << 24 | G.SBOX[t >>> 16 & 0xff] << 16 | G.SBOX[t >>> 8 & 0xff] << 8 | G.SBOX[t & 0xff];
  24630. t ^= RCON[k / keySize | 0] << 24;
  24631. } else if (keySize > 6 && k % keySize === 4) {
  24632. t = G.SBOX[t >>> 24] << 24 | G.SBOX[t >>> 16 & 0xff] << 16 | G.SBOX[t >>> 8 & 0xff] << 8 | G.SBOX[t & 0xff];
  24633. }
  24634. keySchedule[k] = keySchedule[k - keySize] ^ t;
  24635. }
  24636. var invKeySchedule = [];
  24637. for (var ik = 0; ik < ksRows; ik++) {
  24638. var ksR = ksRows - ik;
  24639. var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)];
  24640. if (ik < 4 || ksR <= 4) {
  24641. invKeySchedule[ik] = tt;
  24642. } else {
  24643. invKeySchedule[ik] = G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[tt >>> 16 & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[tt >>> 8 & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]];
  24644. }
  24645. }
  24646. this._nRounds = nRounds;
  24647. this._keySchedule = keySchedule;
  24648. this._invKeySchedule = invKeySchedule;
  24649. };
  24650. AES.prototype.encryptBlockRaw = function (M) {
  24651. M = asUInt32Array(M);
  24652. return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds);
  24653. };
  24654. AES.prototype.encryptBlock = function (M) {
  24655. var out = this.encryptBlockRaw(M);
  24656. var buf = Buffer.allocUnsafe(16);
  24657. buf.writeUInt32BE(out[0], 0);
  24658. buf.writeUInt32BE(out[1], 4);
  24659. buf.writeUInt32BE(out[2], 8);
  24660. buf.writeUInt32BE(out[3], 12);
  24661. return buf;
  24662. };
  24663. AES.prototype.decryptBlock = function (M) {
  24664. M = asUInt32Array(M);
  24665. // swap
  24666. var m1 = M[1];
  24667. M[1] = M[3];
  24668. M[3] = m1;
  24669. var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds);
  24670. var buf = Buffer.allocUnsafe(16);
  24671. buf.writeUInt32BE(out[0], 0);
  24672. buf.writeUInt32BE(out[3], 4);
  24673. buf.writeUInt32BE(out[2], 8);
  24674. buf.writeUInt32BE(out[1], 12);
  24675. return buf;
  24676. };
  24677. AES.prototype.scrub = function () {
  24678. scrubVec(this._keySchedule);
  24679. scrubVec(this._invKeySchedule);
  24680. scrubVec(this._key);
  24681. };
  24682. module.exports.AES = AES;
  24683. },{"safe-buffer":332}],190:[function(require,module,exports){
  24684. "use strict";
  24685. var aes = require('./aes');
  24686. var Buffer = require('safe-buffer').Buffer;
  24687. var Transform = require('cipher-base');
  24688. var inherits = require('inherits');
  24689. var GHASH = require('./ghash');
  24690. var xor = require('buffer-xor');
  24691. var incr32 = require('./incr32');
  24692. function xorTest(a, b) {
  24693. var out = 0;
  24694. if (a.length !== b.length) out++;
  24695. var len = Math.min(a.length, b.length);
  24696. for (var i = 0; i < len; ++i) {
  24697. out += a[i] ^ b[i];
  24698. }
  24699. return out;
  24700. }
  24701. function calcIv(self, iv, ck) {
  24702. if (iv.length === 12) {
  24703. self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]);
  24704. return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]);
  24705. }
  24706. var ghash = new GHASH(ck);
  24707. var len = iv.length;
  24708. var toPad = len % 16;
  24709. ghash.update(iv);
  24710. if (toPad) {
  24711. toPad = 16 - toPad;
  24712. ghash.update(Buffer.alloc(toPad, 0));
  24713. }
  24714. ghash.update(Buffer.alloc(8, 0));
  24715. var ivBits = len * 8;
  24716. var tail = Buffer.alloc(8);
  24717. tail.writeUIntBE(ivBits, 0, 8);
  24718. ghash.update(tail);
  24719. self._finID = ghash.state;
  24720. var out = Buffer.from(self._finID);
  24721. incr32(out);
  24722. return out;
  24723. }
  24724. function StreamCipher(mode, key, iv, decrypt) {
  24725. Transform.call(this);
  24726. var h = Buffer.alloc(4, 0);
  24727. this._cipher = new aes.AES(key);
  24728. var ck = this._cipher.encryptBlock(h);
  24729. this._ghash = new GHASH(ck);
  24730. iv = calcIv(this, iv, ck);
  24731. this._prev = Buffer.from(iv);
  24732. this._cache = Buffer.allocUnsafe(0);
  24733. this._secCache = Buffer.allocUnsafe(0);
  24734. this._decrypt = decrypt;
  24735. this._alen = 0;
  24736. this._len = 0;
  24737. this._mode = mode;
  24738. this._authTag = null;
  24739. this._called = false;
  24740. }
  24741. inherits(StreamCipher, Transform);
  24742. StreamCipher.prototype._update = function (chunk) {
  24743. if (!this._called && this._alen) {
  24744. var rump = 16 - this._alen % 16;
  24745. if (rump < 16) {
  24746. rump = Buffer.alloc(rump, 0);
  24747. this._ghash.update(rump);
  24748. }
  24749. }
  24750. this._called = true;
  24751. var out = this._mode.encrypt(this, chunk);
  24752. if (this._decrypt) {
  24753. this._ghash.update(chunk);
  24754. } else {
  24755. this._ghash.update(out);
  24756. }
  24757. this._len += chunk.length;
  24758. return out;
  24759. };
  24760. StreamCipher.prototype._final = function () {
  24761. if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data');
  24762. var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID));
  24763. if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data');
  24764. this._authTag = tag;
  24765. this._cipher.scrub();
  24766. };
  24767. StreamCipher.prototype.getAuthTag = function getAuthTag() {
  24768. if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state');
  24769. return this._authTag;
  24770. };
  24771. StreamCipher.prototype.setAuthTag = function setAuthTag(tag) {
  24772. if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state');
  24773. this._authTag = tag;
  24774. };
  24775. StreamCipher.prototype.setAAD = function setAAD(buf) {
  24776. if (this._called) throw new Error('Attempting to set AAD in unsupported state');
  24777. this._ghash.update(buf);
  24778. this._alen += buf.length;
  24779. };
  24780. module.exports = StreamCipher;
  24781. },{"./aes":189,"./ghash":194,"./incr32":195,"buffer-xor":219,"cipher-base":221,"inherits":279,"safe-buffer":332}],191:[function(require,module,exports){
  24782. "use strict";
  24783. var ciphers = require('./encrypter');
  24784. var deciphers = require('./decrypter');
  24785. var modes = require('./modes/list.json');
  24786. function getCiphers() {
  24787. return Object.keys(modes);
  24788. }
  24789. exports.createCipher = exports.Cipher = ciphers.createCipher;
  24790. exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv;
  24791. exports.createDecipher = exports.Decipher = deciphers.createDecipher;
  24792. exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv;
  24793. exports.listCiphers = exports.getCiphers = getCiphers;
  24794. },{"./decrypter":192,"./encrypter":193,"./modes/list.json":203}],192:[function(require,module,exports){
  24795. "use strict";
  24796. var AuthCipher = require('./authCipher');
  24797. var Buffer = require('safe-buffer').Buffer;
  24798. var MODES = require('./modes');
  24799. var StreamCipher = require('./streamCipher');
  24800. var Transform = require('cipher-base');
  24801. var aes = require('./aes');
  24802. var ebtk = require('evp_bytestokey');
  24803. var inherits = require('inherits');
  24804. function Decipher(mode, key, iv) {
  24805. Transform.call(this);
  24806. this._cache = new Splitter();
  24807. this._last = void 0;
  24808. this._cipher = new aes.AES(key);
  24809. this._prev = Buffer.from(iv);
  24810. this._mode = mode;
  24811. this._autopadding = true;
  24812. }
  24813. inherits(Decipher, Transform);
  24814. Decipher.prototype._update = function (data) {
  24815. this._cache.add(data);
  24816. var chunk;
  24817. var thing;
  24818. var out = [];
  24819. while (chunk = this._cache.get(this._autopadding)) {
  24820. thing = this._mode.decrypt(this, chunk);
  24821. out.push(thing);
  24822. }
  24823. return Buffer.concat(out);
  24824. };
  24825. Decipher.prototype._final = function () {
  24826. var chunk = this._cache.flush();
  24827. if (this._autopadding) {
  24828. return unpad(this._mode.decrypt(this, chunk));
  24829. } else if (chunk) {
  24830. throw new Error('data not multiple of block length');
  24831. }
  24832. };
  24833. Decipher.prototype.setAutoPadding = function (setTo) {
  24834. this._autopadding = !!setTo;
  24835. return this;
  24836. };
  24837. function Splitter() {
  24838. this.cache = Buffer.allocUnsafe(0);
  24839. }
  24840. Splitter.prototype.add = function (data) {
  24841. this.cache = Buffer.concat([this.cache, data]);
  24842. };
  24843. Splitter.prototype.get = function (autoPadding) {
  24844. var out;
  24845. if (autoPadding) {
  24846. if (this.cache.length > 16) {
  24847. out = this.cache.slice(0, 16);
  24848. this.cache = this.cache.slice(16);
  24849. return out;
  24850. }
  24851. } else {
  24852. if (this.cache.length >= 16) {
  24853. out = this.cache.slice(0, 16);
  24854. this.cache = this.cache.slice(16);
  24855. return out;
  24856. }
  24857. }
  24858. return null;
  24859. };
  24860. Splitter.prototype.flush = function () {
  24861. if (this.cache.length) return this.cache;
  24862. };
  24863. function unpad(last) {
  24864. var padded = last[15];
  24865. if (padded < 1 || padded > 16) {
  24866. throw new Error('unable to decrypt data');
  24867. }
  24868. var i = -1;
  24869. while (++i < padded) {
  24870. if (last[i + (16 - padded)] !== padded) {
  24871. throw new Error('unable to decrypt data');
  24872. }
  24873. }
  24874. if (padded === 16) return;
  24875. return last.slice(0, 16 - padded);
  24876. }
  24877. function createDecipheriv(suite, password, iv) {
  24878. var config = MODES[suite.toLowerCase()];
  24879. if (!config) throw new TypeError('invalid suite type');
  24880. if (typeof iv === 'string') iv = Buffer.from(iv);
  24881. if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length);
  24882. if (typeof password === 'string') password = Buffer.from(password);
  24883. if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length);
  24884. if (config.type === 'stream') {
  24885. return new StreamCipher(config.module, password, iv, true);
  24886. } else if (config.type === 'auth') {
  24887. return new AuthCipher(config.module, password, iv, true);
  24888. }
  24889. return new Decipher(config.module, password, iv);
  24890. }
  24891. function createDecipher(suite, password) {
  24892. var config = MODES[suite.toLowerCase()];
  24893. if (!config) throw new TypeError('invalid suite type');
  24894. var keys = ebtk(password, false, config.key, config.iv);
  24895. return createDecipheriv(suite, keys.key, keys.iv);
  24896. }
  24897. exports.createDecipher = createDecipher;
  24898. exports.createDecipheriv = createDecipheriv;
  24899. },{"./aes":189,"./authCipher":190,"./modes":202,"./streamCipher":205,"cipher-base":221,"evp_bytestokey":262,"inherits":279,"safe-buffer":332}],193:[function(require,module,exports){
  24900. "use strict";
  24901. var MODES = require('./modes');
  24902. var AuthCipher = require('./authCipher');
  24903. var Buffer = require('safe-buffer').Buffer;
  24904. var StreamCipher = require('./streamCipher');
  24905. var Transform = require('cipher-base');
  24906. var aes = require('./aes');
  24907. var ebtk = require('evp_bytestokey');
  24908. var inherits = require('inherits');
  24909. function Cipher(mode, key, iv) {
  24910. Transform.call(this);
  24911. this._cache = new Splitter();
  24912. this._cipher = new aes.AES(key);
  24913. this._prev = Buffer.from(iv);
  24914. this._mode = mode;
  24915. this._autopadding = true;
  24916. }
  24917. inherits(Cipher, Transform);
  24918. Cipher.prototype._update = function (data) {
  24919. this._cache.add(data);
  24920. var chunk;
  24921. var thing;
  24922. var out = [];
  24923. while (chunk = this._cache.get()) {
  24924. thing = this._mode.encrypt(this, chunk);
  24925. out.push(thing);
  24926. }
  24927. return Buffer.concat(out);
  24928. };
  24929. var PADDING = Buffer.alloc(16, 0x10);
  24930. Cipher.prototype._final = function () {
  24931. var chunk = this._cache.flush();
  24932. if (this._autopadding) {
  24933. chunk = this._mode.encrypt(this, chunk);
  24934. this._cipher.scrub();
  24935. return chunk;
  24936. }
  24937. if (!chunk.equals(PADDING)) {
  24938. this._cipher.scrub();
  24939. throw new Error('data not multiple of block length');
  24940. }
  24941. };
  24942. Cipher.prototype.setAutoPadding = function (setTo) {
  24943. this._autopadding = !!setTo;
  24944. return this;
  24945. };
  24946. function Splitter() {
  24947. this.cache = Buffer.allocUnsafe(0);
  24948. }
  24949. Splitter.prototype.add = function (data) {
  24950. this.cache = Buffer.concat([this.cache, data]);
  24951. };
  24952. Splitter.prototype.get = function () {
  24953. if (this.cache.length > 15) {
  24954. var out = this.cache.slice(0, 16);
  24955. this.cache = this.cache.slice(16);
  24956. return out;
  24957. }
  24958. return null;
  24959. };
  24960. Splitter.prototype.flush = function () {
  24961. var len = 16 - this.cache.length;
  24962. var padBuff = Buffer.allocUnsafe(len);
  24963. var i = -1;
  24964. while (++i < len) {
  24965. padBuff.writeUInt8(len, i);
  24966. }
  24967. return Buffer.concat([this.cache, padBuff]);
  24968. };
  24969. function createCipheriv(suite, password, iv) {
  24970. var config = MODES[suite.toLowerCase()];
  24971. if (!config) throw new TypeError('invalid suite type');
  24972. if (typeof password === 'string') password = Buffer.from(password);
  24973. if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length);
  24974. if (typeof iv === 'string') iv = Buffer.from(iv);
  24975. if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length);
  24976. if (config.type === 'stream') {
  24977. return new StreamCipher(config.module, password, iv);
  24978. } else if (config.type === 'auth') {
  24979. return new AuthCipher(config.module, password, iv);
  24980. }
  24981. return new Cipher(config.module, password, iv);
  24982. }
  24983. function createCipher(suite, password) {
  24984. var config = MODES[suite.toLowerCase()];
  24985. if (!config) throw new TypeError('invalid suite type');
  24986. var keys = ebtk(password, false, config.key, config.iv);
  24987. return createCipheriv(suite, keys.key, keys.iv);
  24988. }
  24989. exports.createCipheriv = createCipheriv;
  24990. exports.createCipher = createCipher;
  24991. },{"./aes":189,"./authCipher":190,"./modes":202,"./streamCipher":205,"cipher-base":221,"evp_bytestokey":262,"inherits":279,"safe-buffer":332}],194:[function(require,module,exports){
  24992. "use strict";
  24993. var Buffer = require('safe-buffer').Buffer;
  24994. var ZEROES = Buffer.alloc(16, 0);
  24995. function toArray(buf) {
  24996. return [buf.readUInt32BE(0), buf.readUInt32BE(4), buf.readUInt32BE(8), buf.readUInt32BE(12)];
  24997. }
  24998. function fromArray(out) {
  24999. var buf = Buffer.allocUnsafe(16);
  25000. buf.writeUInt32BE(out[0] >>> 0, 0);
  25001. buf.writeUInt32BE(out[1] >>> 0, 4);
  25002. buf.writeUInt32BE(out[2] >>> 0, 8);
  25003. buf.writeUInt32BE(out[3] >>> 0, 12);
  25004. return buf;
  25005. }
  25006. function GHASH(key) {
  25007. this.h = key;
  25008. this.state = Buffer.alloc(16, 0);
  25009. this.cache = Buffer.allocUnsafe(0);
  25010. }
  25011. // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
  25012. // by Juho Vähä-Herttua
  25013. GHASH.prototype.ghash = function (block) {
  25014. var i = -1;
  25015. while (++i < block.length) {
  25016. this.state[i] ^= block[i];
  25017. }
  25018. this._multiply();
  25019. };
  25020. GHASH.prototype._multiply = function () {
  25021. var Vi = toArray(this.h);
  25022. var Zi = [0, 0, 0, 0];
  25023. var j, xi, lsbVi;
  25024. var i = -1;
  25025. while (++i < 128) {
  25026. xi = (this.state[~~(i / 8)] & 1 << 7 - i % 8) !== 0;
  25027. if (xi) {
  25028. // Z_i+1 = Z_i ^ V_i
  25029. Zi[0] ^= Vi[0];
  25030. Zi[1] ^= Vi[1];
  25031. Zi[2] ^= Vi[2];
  25032. Zi[3] ^= Vi[3];
  25033. }
  25034. // Store the value of LSB(V_i)
  25035. lsbVi = (Vi[3] & 1) !== 0;
  25036. // V_i+1 = V_i >> 1
  25037. for (j = 3; j > 0; j--) {
  25038. Vi[j] = Vi[j] >>> 1 | (Vi[j - 1] & 1) << 31;
  25039. }
  25040. Vi[0] = Vi[0] >>> 1;
  25041. // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
  25042. if (lsbVi) {
  25043. Vi[0] = Vi[0] ^ 0xe1 << 24;
  25044. }
  25045. }
  25046. this.state = fromArray(Zi);
  25047. };
  25048. GHASH.prototype.update = function (buf) {
  25049. this.cache = Buffer.concat([this.cache, buf]);
  25050. var chunk;
  25051. while (this.cache.length >= 16) {
  25052. chunk = this.cache.slice(0, 16);
  25053. this.cache = this.cache.slice(16);
  25054. this.ghash(chunk);
  25055. }
  25056. };
  25057. GHASH.prototype.final = function (abl, bl) {
  25058. if (this.cache.length) {
  25059. this.ghash(Buffer.concat([this.cache, ZEROES], 16));
  25060. }
  25061. this.ghash(fromArray([0, abl, 0, bl]));
  25062. return this.state;
  25063. };
  25064. module.exports = GHASH;
  25065. },{"safe-buffer":332}],195:[function(require,module,exports){
  25066. "use strict";
  25067. function incr32(iv) {
  25068. var len = iv.length;
  25069. var item;
  25070. while (len--) {
  25071. item = iv.readUInt8(len);
  25072. if (item === 255) {
  25073. iv.writeUInt8(0, len);
  25074. } else {
  25075. item++;
  25076. iv.writeUInt8(item, len);
  25077. break;
  25078. }
  25079. }
  25080. }
  25081. module.exports = incr32;
  25082. },{}],196:[function(require,module,exports){
  25083. "use strict";
  25084. var xor = require('buffer-xor');
  25085. exports.encrypt = function (self, block) {
  25086. var data = xor(block, self._prev);
  25087. self._prev = self._cipher.encryptBlock(data);
  25088. return self._prev;
  25089. };
  25090. exports.decrypt = function (self, block) {
  25091. var pad = self._prev;
  25092. self._prev = block;
  25093. var out = self._cipher.decryptBlock(block);
  25094. return xor(out, pad);
  25095. };
  25096. },{"buffer-xor":219}],197:[function(require,module,exports){
  25097. "use strict";
  25098. var Buffer = require('safe-buffer').Buffer;
  25099. var xor = require('buffer-xor');
  25100. function encryptStart(self, data, decrypt) {
  25101. var len = data.length;
  25102. var out = xor(data, self._cache);
  25103. self._cache = self._cache.slice(len);
  25104. self._prev = Buffer.concat([self._prev, decrypt ? data : out]);
  25105. return out;
  25106. }
  25107. exports.encrypt = function (self, data, decrypt) {
  25108. var out = Buffer.allocUnsafe(0);
  25109. var len;
  25110. while (data.length) {
  25111. if (self._cache.length === 0) {
  25112. self._cache = self._cipher.encryptBlock(self._prev);
  25113. self._prev = Buffer.allocUnsafe(0);
  25114. }
  25115. if (self._cache.length <= data.length) {
  25116. len = self._cache.length;
  25117. out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]);
  25118. data = data.slice(len);
  25119. } else {
  25120. out = Buffer.concat([out, encryptStart(self, data, decrypt)]);
  25121. break;
  25122. }
  25123. }
  25124. return out;
  25125. };
  25126. },{"buffer-xor":219,"safe-buffer":332}],198:[function(require,module,exports){
  25127. "use strict";
  25128. var Buffer = require('safe-buffer').Buffer;
  25129. function encryptByte(self, byteParam, decrypt) {
  25130. var pad;
  25131. var i = -1;
  25132. var len = 8;
  25133. var out = 0;
  25134. var bit, value;
  25135. while (++i < len) {
  25136. pad = self._cipher.encryptBlock(self._prev);
  25137. bit = byteParam & 1 << 7 - i ? 0x80 : 0;
  25138. value = pad[0] ^ bit;
  25139. out += (value & 0x80) >> i % 8;
  25140. self._prev = shiftIn(self._prev, decrypt ? bit : value);
  25141. }
  25142. return out;
  25143. }
  25144. function shiftIn(buffer, value) {
  25145. var len = buffer.length;
  25146. var i = -1;
  25147. var out = Buffer.allocUnsafe(buffer.length);
  25148. buffer = Buffer.concat([buffer, Buffer.from([value])]);
  25149. while (++i < len) {
  25150. out[i] = buffer[i] << 1 | buffer[i + 1] >> 7;
  25151. }
  25152. return out;
  25153. }
  25154. exports.encrypt = function (self, chunk, decrypt) {
  25155. var len = chunk.length;
  25156. var out = Buffer.allocUnsafe(len);
  25157. var i = -1;
  25158. while (++i < len) {
  25159. out[i] = encryptByte(self, chunk[i], decrypt);
  25160. }
  25161. return out;
  25162. };
  25163. },{"safe-buffer":332}],199:[function(require,module,exports){
  25164. "use strict";
  25165. var Buffer = require('safe-buffer').Buffer;
  25166. function encryptByte(self, byteParam, decrypt) {
  25167. var pad = self._cipher.encryptBlock(self._prev);
  25168. var out = pad[0] ^ byteParam;
  25169. self._prev = Buffer.concat([self._prev.slice(1), Buffer.from([decrypt ? byteParam : out])]);
  25170. return out;
  25171. }
  25172. exports.encrypt = function (self, chunk, decrypt) {
  25173. var len = chunk.length;
  25174. var out = Buffer.allocUnsafe(len);
  25175. var i = -1;
  25176. while (++i < len) {
  25177. out[i] = encryptByte(self, chunk[i], decrypt);
  25178. }
  25179. return out;
  25180. };
  25181. },{"safe-buffer":332}],200:[function(require,module,exports){
  25182. "use strict";
  25183. var xor = require('buffer-xor');
  25184. var Buffer = require('safe-buffer').Buffer;
  25185. var incr32 = require('../incr32');
  25186. function getBlock(self) {
  25187. var out = self._cipher.encryptBlockRaw(self._prev);
  25188. incr32(self._prev);
  25189. return out;
  25190. }
  25191. var blockSize = 16;
  25192. exports.encrypt = function (self, chunk) {
  25193. var chunkNum = Math.ceil(chunk.length / blockSize);
  25194. var start = self._cache.length;
  25195. self._cache = Buffer.concat([self._cache, Buffer.allocUnsafe(chunkNum * blockSize)]);
  25196. for (var i = 0; i < chunkNum; i++) {
  25197. var out = getBlock(self);
  25198. var offset = start + i * blockSize;
  25199. self._cache.writeUInt32BE(out[0], offset + 0);
  25200. self._cache.writeUInt32BE(out[1], offset + 4);
  25201. self._cache.writeUInt32BE(out[2], offset + 8);
  25202. self._cache.writeUInt32BE(out[3], offset + 12);
  25203. }
  25204. var pad = self._cache.slice(0, chunk.length);
  25205. self._cache = self._cache.slice(chunk.length);
  25206. return xor(chunk, pad);
  25207. };
  25208. },{"../incr32":195,"buffer-xor":219,"safe-buffer":332}],201:[function(require,module,exports){
  25209. "use strict";
  25210. exports.encrypt = function (self, block) {
  25211. return self._cipher.encryptBlock(block);
  25212. };
  25213. exports.decrypt = function (self, block) {
  25214. return self._cipher.decryptBlock(block);
  25215. };
  25216. },{}],202:[function(require,module,exports){
  25217. "use strict";
  25218. var modeModules = {
  25219. ECB: require('./ecb'),
  25220. CBC: require('./cbc'),
  25221. CFB: require('./cfb'),
  25222. CFB8: require('./cfb8'),
  25223. CFB1: require('./cfb1'),
  25224. OFB: require('./ofb'),
  25225. CTR: require('./ctr'),
  25226. GCM: require('./ctr')
  25227. };
  25228. var modes = require('./list.json');
  25229. for (var key in modes) {
  25230. modes[key].module = modeModules[modes[key].mode];
  25231. }
  25232. module.exports = modes;
  25233. },{"./cbc":196,"./cfb":197,"./cfb1":198,"./cfb8":199,"./ctr":200,"./ecb":201,"./list.json":203,"./ofb":204}],203:[function(require,module,exports){
  25234. module.exports={
  25235. "aes-128-ecb": {
  25236. "cipher": "AES",
  25237. "key": 128,
  25238. "iv": 0,
  25239. "mode": "ECB",
  25240. "type": "block"
  25241. },
  25242. "aes-192-ecb": {
  25243. "cipher": "AES",
  25244. "key": 192,
  25245. "iv": 0,
  25246. "mode": "ECB",
  25247. "type": "block"
  25248. },
  25249. "aes-256-ecb": {
  25250. "cipher": "AES",
  25251. "key": 256,
  25252. "iv": 0,
  25253. "mode": "ECB",
  25254. "type": "block"
  25255. },
  25256. "aes-128-cbc": {
  25257. "cipher": "AES",
  25258. "key": 128,
  25259. "iv": 16,
  25260. "mode": "CBC",
  25261. "type": "block"
  25262. },
  25263. "aes-192-cbc": {
  25264. "cipher": "AES",
  25265. "key": 192,
  25266. "iv": 16,
  25267. "mode": "CBC",
  25268. "type": "block"
  25269. },
  25270. "aes-256-cbc": {
  25271. "cipher": "AES",
  25272. "key": 256,
  25273. "iv": 16,
  25274. "mode": "CBC",
  25275. "type": "block"
  25276. },
  25277. "aes128": {
  25278. "cipher": "AES",
  25279. "key": 128,
  25280. "iv": 16,
  25281. "mode": "CBC",
  25282. "type": "block"
  25283. },
  25284. "aes192": {
  25285. "cipher": "AES",
  25286. "key": 192,
  25287. "iv": 16,
  25288. "mode": "CBC",
  25289. "type": "block"
  25290. },
  25291. "aes256": {
  25292. "cipher": "AES",
  25293. "key": 256,
  25294. "iv": 16,
  25295. "mode": "CBC",
  25296. "type": "block"
  25297. },
  25298. "aes-128-cfb": {
  25299. "cipher": "AES",
  25300. "key": 128,
  25301. "iv": 16,
  25302. "mode": "CFB",
  25303. "type": "stream"
  25304. },
  25305. "aes-192-cfb": {
  25306. "cipher": "AES",
  25307. "key": 192,
  25308. "iv": 16,
  25309. "mode": "CFB",
  25310. "type": "stream"
  25311. },
  25312. "aes-256-cfb": {
  25313. "cipher": "AES",
  25314. "key": 256,
  25315. "iv": 16,
  25316. "mode": "CFB",
  25317. "type": "stream"
  25318. },
  25319. "aes-128-cfb8": {
  25320. "cipher": "AES",
  25321. "key": 128,
  25322. "iv": 16,
  25323. "mode": "CFB8",
  25324. "type": "stream"
  25325. },
  25326. "aes-192-cfb8": {
  25327. "cipher": "AES",
  25328. "key": 192,
  25329. "iv": 16,
  25330. "mode": "CFB8",
  25331. "type": "stream"
  25332. },
  25333. "aes-256-cfb8": {
  25334. "cipher": "AES",
  25335. "key": 256,
  25336. "iv": 16,
  25337. "mode": "CFB8",
  25338. "type": "stream"
  25339. },
  25340. "aes-128-cfb1": {
  25341. "cipher": "AES",
  25342. "key": 128,
  25343. "iv": 16,
  25344. "mode": "CFB1",
  25345. "type": "stream"
  25346. },
  25347. "aes-192-cfb1": {
  25348. "cipher": "AES",
  25349. "key": 192,
  25350. "iv": 16,
  25351. "mode": "CFB1",
  25352. "type": "stream"
  25353. },
  25354. "aes-256-cfb1": {
  25355. "cipher": "AES",
  25356. "key": 256,
  25357. "iv": 16,
  25358. "mode": "CFB1",
  25359. "type": "stream"
  25360. },
  25361. "aes-128-ofb": {
  25362. "cipher": "AES",
  25363. "key": 128,
  25364. "iv": 16,
  25365. "mode": "OFB",
  25366. "type": "stream"
  25367. },
  25368. "aes-192-ofb": {
  25369. "cipher": "AES",
  25370. "key": 192,
  25371. "iv": 16,
  25372. "mode": "OFB",
  25373. "type": "stream"
  25374. },
  25375. "aes-256-ofb": {
  25376. "cipher": "AES",
  25377. "key": 256,
  25378. "iv": 16,
  25379. "mode": "OFB",
  25380. "type": "stream"
  25381. },
  25382. "aes-128-ctr": {
  25383. "cipher": "AES",
  25384. "key": 128,
  25385. "iv": 16,
  25386. "mode": "CTR",
  25387. "type": "stream"
  25388. },
  25389. "aes-192-ctr": {
  25390. "cipher": "AES",
  25391. "key": 192,
  25392. "iv": 16,
  25393. "mode": "CTR",
  25394. "type": "stream"
  25395. },
  25396. "aes-256-ctr": {
  25397. "cipher": "AES",
  25398. "key": 256,
  25399. "iv": 16,
  25400. "mode": "CTR",
  25401. "type": "stream"
  25402. },
  25403. "aes-128-gcm": {
  25404. "cipher": "AES",
  25405. "key": 128,
  25406. "iv": 12,
  25407. "mode": "GCM",
  25408. "type": "auth"
  25409. },
  25410. "aes-192-gcm": {
  25411. "cipher": "AES",
  25412. "key": 192,
  25413. "iv": 12,
  25414. "mode": "GCM",
  25415. "type": "auth"
  25416. },
  25417. "aes-256-gcm": {
  25418. "cipher": "AES",
  25419. "key": 256,
  25420. "iv": 12,
  25421. "mode": "GCM",
  25422. "type": "auth"
  25423. }
  25424. }
  25425. },{}],204:[function(require,module,exports){
  25426. (function (Buffer){(function (){
  25427. "use strict";
  25428. var xor = require('buffer-xor');
  25429. function getBlock(self) {
  25430. self._prev = self._cipher.encryptBlock(self._prev);
  25431. return self._prev;
  25432. }
  25433. exports.encrypt = function (self, chunk) {
  25434. while (self._cache.length < chunk.length) {
  25435. self._cache = Buffer.concat([self._cache, getBlock(self)]);
  25436. }
  25437. var pad = self._cache.slice(0, chunk.length);
  25438. self._cache = self._cache.slice(chunk.length);
  25439. return xor(chunk, pad);
  25440. };
  25441. }).call(this)}).call(this,require("buffer").Buffer)
  25442. },{"buffer":220,"buffer-xor":219}],205:[function(require,module,exports){
  25443. "use strict";
  25444. var aes = require('./aes');
  25445. var Buffer = require('safe-buffer').Buffer;
  25446. var Transform = require('cipher-base');
  25447. var inherits = require('inherits');
  25448. function StreamCipher(mode, key, iv, decrypt) {
  25449. Transform.call(this);
  25450. this._cipher = new aes.AES(key);
  25451. this._prev = Buffer.from(iv);
  25452. this._cache = Buffer.allocUnsafe(0);
  25453. this._secCache = Buffer.allocUnsafe(0);
  25454. this._decrypt = decrypt;
  25455. this._mode = mode;
  25456. }
  25457. inherits(StreamCipher, Transform);
  25458. StreamCipher.prototype._update = function (chunk) {
  25459. return this._mode.encrypt(this, chunk, this._decrypt);
  25460. };
  25461. StreamCipher.prototype._final = function () {
  25462. this._cipher.scrub();
  25463. };
  25464. module.exports = StreamCipher;
  25465. },{"./aes":189,"cipher-base":221,"inherits":279,"safe-buffer":332}],206:[function(require,module,exports){
  25466. "use strict";
  25467. var DES = require('browserify-des');
  25468. var aes = require('browserify-aes/browser');
  25469. var aesModes = require('browserify-aes/modes');
  25470. var desModes = require('browserify-des/modes');
  25471. var ebtk = require('evp_bytestokey');
  25472. function createCipher(suite, password) {
  25473. suite = suite.toLowerCase();
  25474. var keyLen, ivLen;
  25475. if (aesModes[suite]) {
  25476. keyLen = aesModes[suite].key;
  25477. ivLen = aesModes[suite].iv;
  25478. } else if (desModes[suite]) {
  25479. keyLen = desModes[suite].key * 8;
  25480. ivLen = desModes[suite].iv;
  25481. } else {
  25482. throw new TypeError('invalid suite type');
  25483. }
  25484. var keys = ebtk(password, false, keyLen, ivLen);
  25485. return createCipheriv(suite, keys.key, keys.iv);
  25486. }
  25487. function createDecipher(suite, password) {
  25488. suite = suite.toLowerCase();
  25489. var keyLen, ivLen;
  25490. if (aesModes[suite]) {
  25491. keyLen = aesModes[suite].key;
  25492. ivLen = aesModes[suite].iv;
  25493. } else if (desModes[suite]) {
  25494. keyLen = desModes[suite].key * 8;
  25495. ivLen = desModes[suite].iv;
  25496. } else {
  25497. throw new TypeError('invalid suite type');
  25498. }
  25499. var keys = ebtk(password, false, keyLen, ivLen);
  25500. return createDecipheriv(suite, keys.key, keys.iv);
  25501. }
  25502. function createCipheriv(suite, key, iv) {
  25503. suite = suite.toLowerCase();
  25504. if (aesModes[suite]) return aes.createCipheriv(suite, key, iv);
  25505. if (desModes[suite]) return new DES({
  25506. key: key,
  25507. iv: iv,
  25508. mode: suite
  25509. });
  25510. throw new TypeError('invalid suite type');
  25511. }
  25512. function createDecipheriv(suite, key, iv) {
  25513. suite = suite.toLowerCase();
  25514. if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv);
  25515. if (desModes[suite]) return new DES({
  25516. key: key,
  25517. iv: iv,
  25518. mode: suite,
  25519. decrypt: true
  25520. });
  25521. throw new TypeError('invalid suite type');
  25522. }
  25523. function getCiphers() {
  25524. return Object.keys(desModes).concat(aes.getCiphers());
  25525. }
  25526. exports.createCipher = exports.Cipher = createCipher;
  25527. exports.createCipheriv = exports.Cipheriv = createCipheriv;
  25528. exports.createDecipher = exports.Decipher = createDecipher;
  25529. exports.createDecipheriv = exports.Decipheriv = createDecipheriv;
  25530. exports.listCiphers = exports.getCiphers = getCiphers;
  25531. },{"browserify-aes/browser":191,"browserify-aes/modes":202,"browserify-des":207,"browserify-des/modes":208,"evp_bytestokey":262}],207:[function(require,module,exports){
  25532. "use strict";
  25533. var CipherBase = require('cipher-base');
  25534. var des = require('des.js');
  25535. var inherits = require('inherits');
  25536. var Buffer = require('safe-buffer').Buffer;
  25537. var modes = {
  25538. 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
  25539. 'des-ede3': des.EDE,
  25540. 'des-ede-cbc': des.CBC.instantiate(des.EDE),
  25541. 'des-ede': des.EDE,
  25542. 'des-cbc': des.CBC.instantiate(des.DES),
  25543. 'des-ecb': des.DES
  25544. };
  25545. modes.des = modes['des-cbc'];
  25546. modes.des3 = modes['des-ede3-cbc'];
  25547. module.exports = DES;
  25548. inherits(DES, CipherBase);
  25549. function DES(opts) {
  25550. CipherBase.call(this);
  25551. var modeName = opts.mode.toLowerCase();
  25552. var mode = modes[modeName];
  25553. var type;
  25554. if (opts.decrypt) {
  25555. type = 'decrypt';
  25556. } else {
  25557. type = 'encrypt';
  25558. }
  25559. var key = opts.key;
  25560. if (!Buffer.isBuffer(key)) {
  25561. key = Buffer.from(key);
  25562. }
  25563. if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
  25564. key = Buffer.concat([key, key.slice(0, 8)]);
  25565. }
  25566. var iv = opts.iv;
  25567. if (!Buffer.isBuffer(iv)) {
  25568. iv = Buffer.from(iv);
  25569. }
  25570. this._des = mode.create({
  25571. key: key,
  25572. iv: iv,
  25573. type: type
  25574. });
  25575. }
  25576. DES.prototype._update = function (data) {
  25577. return Buffer.from(this._des.update(data));
  25578. };
  25579. DES.prototype._final = function () {
  25580. return Buffer.from(this._des.final());
  25581. };
  25582. },{"cipher-base":221,"des.js":233,"inherits":279,"safe-buffer":332}],208:[function(require,module,exports){
  25583. "use strict";
  25584. exports['des-ecb'] = {
  25585. key: 8,
  25586. iv: 0
  25587. };
  25588. exports['des-cbc'] = exports.des = {
  25589. key: 8,
  25590. iv: 8
  25591. };
  25592. exports['des-ede3-cbc'] = exports.des3 = {
  25593. key: 24,
  25594. iv: 8
  25595. };
  25596. exports['des-ede3'] = {
  25597. key: 24,
  25598. iv: 0
  25599. };
  25600. exports['des-ede-cbc'] = {
  25601. key: 16,
  25602. iv: 8
  25603. };
  25604. exports['des-ede'] = {
  25605. key: 16,
  25606. iv: 0
  25607. };
  25608. },{}],209:[function(require,module,exports){
  25609. (function (Buffer){(function (){
  25610. "use strict";
  25611. var BN = require('bn.js');
  25612. var randomBytes = require('randombytes');
  25613. function blind(priv) {
  25614. var r = getr(priv);
  25615. var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed();
  25616. return {
  25617. blinder: blinder,
  25618. unblinder: r.invm(priv.modulus)
  25619. };
  25620. }
  25621. function getr(priv) {
  25622. var len = priv.modulus.byteLength();
  25623. var r;
  25624. do {
  25625. r = new BN(randomBytes(len));
  25626. } while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2));
  25627. return r;
  25628. }
  25629. function crt(msg, priv) {
  25630. var blinds = blind(priv);
  25631. var len = priv.modulus.byteLength();
  25632. var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus);
  25633. var c1 = blinded.toRed(BN.mont(priv.prime1));
  25634. var c2 = blinded.toRed(BN.mont(priv.prime2));
  25635. var qinv = priv.coefficient;
  25636. var p = priv.prime1;
  25637. var q = priv.prime2;
  25638. var m1 = c1.redPow(priv.exponent1).fromRed();
  25639. var m2 = c2.redPow(priv.exponent2).fromRed();
  25640. var h = m1.isub(m2).imul(qinv).umod(p).imul(q);
  25641. return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len);
  25642. }
  25643. crt.getr = getr;
  25644. module.exports = crt;
  25645. }).call(this)}).call(this,require("buffer").Buffer)
  25646. },{"bn.js":186,"buffer":220,"randombytes":314}],210:[function(require,module,exports){
  25647. "use strict";
  25648. module.exports = require('./browser/algorithms.json');
  25649. },{"./browser/algorithms.json":211}],211:[function(require,module,exports){
  25650. module.exports={
  25651. "sha224WithRSAEncryption": {
  25652. "sign": "rsa",
  25653. "hash": "sha224",
  25654. "id": "302d300d06096086480165030402040500041c"
  25655. },
  25656. "RSA-SHA224": {
  25657. "sign": "ecdsa/rsa",
  25658. "hash": "sha224",
  25659. "id": "302d300d06096086480165030402040500041c"
  25660. },
  25661. "sha256WithRSAEncryption": {
  25662. "sign": "rsa",
  25663. "hash": "sha256",
  25664. "id": "3031300d060960864801650304020105000420"
  25665. },
  25666. "RSA-SHA256": {
  25667. "sign": "ecdsa/rsa",
  25668. "hash": "sha256",
  25669. "id": "3031300d060960864801650304020105000420"
  25670. },
  25671. "sha384WithRSAEncryption": {
  25672. "sign": "rsa",
  25673. "hash": "sha384",
  25674. "id": "3041300d060960864801650304020205000430"
  25675. },
  25676. "RSA-SHA384": {
  25677. "sign": "ecdsa/rsa",
  25678. "hash": "sha384",
  25679. "id": "3041300d060960864801650304020205000430"
  25680. },
  25681. "sha512WithRSAEncryption": {
  25682. "sign": "rsa",
  25683. "hash": "sha512",
  25684. "id": "3051300d060960864801650304020305000440"
  25685. },
  25686. "RSA-SHA512": {
  25687. "sign": "ecdsa/rsa",
  25688. "hash": "sha512",
  25689. "id": "3051300d060960864801650304020305000440"
  25690. },
  25691. "RSA-SHA1": {
  25692. "sign": "rsa",
  25693. "hash": "sha1",
  25694. "id": "3021300906052b0e03021a05000414"
  25695. },
  25696. "ecdsa-with-SHA1": {
  25697. "sign": "ecdsa",
  25698. "hash": "sha1",
  25699. "id": ""
  25700. },
  25701. "sha256": {
  25702. "sign": "ecdsa",
  25703. "hash": "sha256",
  25704. "id": ""
  25705. },
  25706. "sha224": {
  25707. "sign": "ecdsa",
  25708. "hash": "sha224",
  25709. "id": ""
  25710. },
  25711. "sha384": {
  25712. "sign": "ecdsa",
  25713. "hash": "sha384",
  25714. "id": ""
  25715. },
  25716. "sha512": {
  25717. "sign": "ecdsa",
  25718. "hash": "sha512",
  25719. "id": ""
  25720. },
  25721. "DSA-SHA": {
  25722. "sign": "dsa",
  25723. "hash": "sha1",
  25724. "id": ""
  25725. },
  25726. "DSA-SHA1": {
  25727. "sign": "dsa",
  25728. "hash": "sha1",
  25729. "id": ""
  25730. },
  25731. "DSA": {
  25732. "sign": "dsa",
  25733. "hash": "sha1",
  25734. "id": ""
  25735. },
  25736. "DSA-WITH-SHA224": {
  25737. "sign": "dsa",
  25738. "hash": "sha224",
  25739. "id": ""
  25740. },
  25741. "DSA-SHA224": {
  25742. "sign": "dsa",
  25743. "hash": "sha224",
  25744. "id": ""
  25745. },
  25746. "DSA-WITH-SHA256": {
  25747. "sign": "dsa",
  25748. "hash": "sha256",
  25749. "id": ""
  25750. },
  25751. "DSA-SHA256": {
  25752. "sign": "dsa",
  25753. "hash": "sha256",
  25754. "id": ""
  25755. },
  25756. "DSA-WITH-SHA384": {
  25757. "sign": "dsa",
  25758. "hash": "sha384",
  25759. "id": ""
  25760. },
  25761. "DSA-SHA384": {
  25762. "sign": "dsa",
  25763. "hash": "sha384",
  25764. "id": ""
  25765. },
  25766. "DSA-WITH-SHA512": {
  25767. "sign": "dsa",
  25768. "hash": "sha512",
  25769. "id": ""
  25770. },
  25771. "DSA-SHA512": {
  25772. "sign": "dsa",
  25773. "hash": "sha512",
  25774. "id": ""
  25775. },
  25776. "DSA-RIPEMD160": {
  25777. "sign": "dsa",
  25778. "hash": "rmd160",
  25779. "id": ""
  25780. },
  25781. "ripemd160WithRSA": {
  25782. "sign": "rsa",
  25783. "hash": "rmd160",
  25784. "id": "3021300906052b2403020105000414"
  25785. },
  25786. "RSA-RIPEMD160": {
  25787. "sign": "rsa",
  25788. "hash": "rmd160",
  25789. "id": "3021300906052b2403020105000414"
  25790. },
  25791. "md5WithRSAEncryption": {
  25792. "sign": "rsa",
  25793. "hash": "md5",
  25794. "id": "3020300c06082a864886f70d020505000410"
  25795. },
  25796. "RSA-MD5": {
  25797. "sign": "rsa",
  25798. "hash": "md5",
  25799. "id": "3020300c06082a864886f70d020505000410"
  25800. }
  25801. }
  25802. },{}],212:[function(require,module,exports){
  25803. module.exports={
  25804. "1.3.132.0.10": "secp256k1",
  25805. "1.3.132.0.33": "p224",
  25806. "1.2.840.10045.3.1.1": "p192",
  25807. "1.2.840.10045.3.1.7": "p256",
  25808. "1.3.132.0.34": "p384",
  25809. "1.3.132.0.35": "p521"
  25810. }
  25811. },{}],213:[function(require,module,exports){
  25812. "use strict";
  25813. var Buffer = require('safe-buffer').Buffer;
  25814. var createHash = require('create-hash');
  25815. var stream = require('readable-stream');
  25816. var inherits = require('inherits');
  25817. var sign = require('./sign');
  25818. var verify = require('./verify');
  25819. var algorithms = require('./algorithms.json');
  25820. Object.keys(algorithms).forEach(function (key) {
  25821. algorithms[key].id = Buffer.from(algorithms[key].id, 'hex');
  25822. algorithms[key.toLowerCase()] = algorithms[key];
  25823. });
  25824. function Sign(algorithm) {
  25825. stream.Writable.call(this);
  25826. var data = algorithms[algorithm];
  25827. if (!data) throw new Error('Unknown message digest');
  25828. this._hashType = data.hash;
  25829. this._hash = createHash(data.hash);
  25830. this._tag = data.id;
  25831. this._signType = data.sign;
  25832. }
  25833. inherits(Sign, stream.Writable);
  25834. Sign.prototype._write = function _write(data, _, done) {
  25835. this._hash.update(data);
  25836. done();
  25837. };
  25838. Sign.prototype.update = function update(data, enc) {
  25839. if (typeof data === 'string') data = Buffer.from(data, enc);
  25840. this._hash.update(data);
  25841. return this;
  25842. };
  25843. Sign.prototype.sign = function signMethod(key, enc) {
  25844. this.end();
  25845. var hash = this._hash.digest();
  25846. var sig = sign(hash, key, this._hashType, this._signType, this._tag);
  25847. return enc ? sig.toString(enc) : sig;
  25848. };
  25849. function Verify(algorithm) {
  25850. stream.Writable.call(this);
  25851. var data = algorithms[algorithm];
  25852. if (!data) throw new Error('Unknown message digest');
  25853. this._hash = createHash(data.hash);
  25854. this._tag = data.id;
  25855. this._signType = data.sign;
  25856. }
  25857. inherits(Verify, stream.Writable);
  25858. Verify.prototype._write = function _write(data, _, done) {
  25859. this._hash.update(data);
  25860. done();
  25861. };
  25862. Verify.prototype.update = function update(data, enc) {
  25863. if (typeof data === 'string') data = Buffer.from(data, enc);
  25864. this._hash.update(data);
  25865. return this;
  25866. };
  25867. Verify.prototype.verify = function verifyMethod(key, sig, enc) {
  25868. if (typeof sig === 'string') sig = Buffer.from(sig, enc);
  25869. this.end();
  25870. var hash = this._hash.digest();
  25871. return verify(sig, hash, key, this._signType, this._tag);
  25872. };
  25873. function createSign(algorithm) {
  25874. return new Sign(algorithm);
  25875. }
  25876. function createVerify(algorithm) {
  25877. return new Verify(algorithm);
  25878. }
  25879. module.exports = {
  25880. Sign: createSign,
  25881. Verify: createVerify,
  25882. createSign: createSign,
  25883. createVerify: createVerify
  25884. };
  25885. },{"./algorithms.json":211,"./sign":214,"./verify":215,"create-hash":225,"inherits":279,"readable-stream":330,"safe-buffer":332}],214:[function(require,module,exports){
  25886. "use strict";
  25887. // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
  25888. var Buffer = require('safe-buffer').Buffer;
  25889. var createHmac = require('create-hmac');
  25890. var crt = require('browserify-rsa');
  25891. var EC = require('elliptic').ec;
  25892. var BN = require('bn.js');
  25893. var parseKeys = require('parse-asn1');
  25894. var curves = require('./curves.json');
  25895. function sign(hash, key, hashType, signType, tag) {
  25896. var priv = parseKeys(key);
  25897. if (priv.curve) {
  25898. // rsa keys can be interpreted as ecdsa ones in openssl
  25899. if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type');
  25900. return ecSign(hash, priv);
  25901. } else if (priv.type === 'dsa') {
  25902. if (signType !== 'dsa') throw new Error('wrong private key type');
  25903. return dsaSign(hash, priv, hashType);
  25904. } else {
  25905. if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type');
  25906. }
  25907. hash = Buffer.concat([tag, hash]);
  25908. var len = priv.modulus.byteLength();
  25909. var pad = [0, 1];
  25910. while (hash.length + pad.length + 1 < len) pad.push(0xff);
  25911. pad.push(0x00);
  25912. var i = -1;
  25913. while (++i < hash.length) pad.push(hash[i]);
  25914. var out = crt(pad, priv);
  25915. return out;
  25916. }
  25917. function ecSign(hash, priv) {
  25918. var curveId = curves[priv.curve.join('.')];
  25919. if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'));
  25920. var curve = new EC(curveId);
  25921. var key = curve.keyFromPrivate(priv.privateKey);
  25922. var out = key.sign(hash);
  25923. return Buffer.from(out.toDER());
  25924. }
  25925. function dsaSign(hash, priv, algo) {
  25926. var x = priv.params.priv_key;
  25927. var p = priv.params.p;
  25928. var q = priv.params.q;
  25929. var g = priv.params.g;
  25930. var r = new BN(0);
  25931. var k;
  25932. var H = bits2int(hash, q).mod(q);
  25933. var s = false;
  25934. var kv = getKey(x, q, hash, algo);
  25935. while (s === false) {
  25936. k = makeKey(q, kv, algo);
  25937. r = makeR(g, k, p, q);
  25938. s = k.invm(q).imul(H.add(x.mul(r))).mod(q);
  25939. if (s.cmpn(0) === 0) {
  25940. s = false;
  25941. r = new BN(0);
  25942. }
  25943. }
  25944. return toDER(r, s);
  25945. }
  25946. function toDER(r, s) {
  25947. r = r.toArray();
  25948. s = s.toArray();
  25949. // Pad values
  25950. if (r[0] & 0x80) r = [0].concat(r);
  25951. if (s[0] & 0x80) s = [0].concat(s);
  25952. var total = r.length + s.length + 4;
  25953. var res = [0x30, total, 0x02, r.length];
  25954. res = res.concat(r, [0x02, s.length], s);
  25955. return Buffer.from(res);
  25956. }
  25957. function getKey(x, q, hash, algo) {
  25958. x = Buffer.from(x.toArray());
  25959. if (x.length < q.byteLength()) {
  25960. var zeros = Buffer.alloc(q.byteLength() - x.length);
  25961. x = Buffer.concat([zeros, x]);
  25962. }
  25963. var hlen = hash.length;
  25964. var hbits = bits2octets(hash, q);
  25965. var v = Buffer.alloc(hlen);
  25966. v.fill(1);
  25967. var k = Buffer.alloc(hlen);
  25968. k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest();
  25969. v = createHmac(algo, k).update(v).digest();
  25970. k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest();
  25971. v = createHmac(algo, k).update(v).digest();
  25972. return {
  25973. k: k,
  25974. v: v
  25975. };
  25976. }
  25977. function bits2int(obits, q) {
  25978. var bits = new BN(obits);
  25979. var shift = (obits.length << 3) - q.bitLength();
  25980. if (shift > 0) bits.ishrn(shift);
  25981. return bits;
  25982. }
  25983. function bits2octets(bits, q) {
  25984. bits = bits2int(bits, q);
  25985. bits = bits.mod(q);
  25986. var out = Buffer.from(bits.toArray());
  25987. if (out.length < q.byteLength()) {
  25988. var zeros = Buffer.alloc(q.byteLength() - out.length);
  25989. out = Buffer.concat([zeros, out]);
  25990. }
  25991. return out;
  25992. }
  25993. function makeKey(q, kv, algo) {
  25994. var t;
  25995. var k;
  25996. do {
  25997. t = Buffer.alloc(0);
  25998. while (t.length * 8 < q.bitLength()) {
  25999. kv.v = createHmac(algo, kv.k).update(kv.v).digest();
  26000. t = Buffer.concat([t, kv.v]);
  26001. }
  26002. k = bits2int(t, q);
  26003. kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest();
  26004. kv.v = createHmac(algo, kv.k).update(kv.v).digest();
  26005. } while (k.cmp(q) !== -1);
  26006. return k;
  26007. }
  26008. function makeR(g, k, p, q) {
  26009. return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q);
  26010. }
  26011. module.exports = sign;
  26012. module.exports.getKey = getKey;
  26013. module.exports.makeKey = makeKey;
  26014. },{"./curves.json":212,"bn.js":186,"browserify-rsa":209,"create-hmac":227,"elliptic":244,"parse-asn1":298,"safe-buffer":332}],215:[function(require,module,exports){
  26015. "use strict";
  26016. // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
  26017. var Buffer = require('safe-buffer').Buffer;
  26018. var BN = require('bn.js');
  26019. var EC = require('elliptic').ec;
  26020. var parseKeys = require('parse-asn1');
  26021. var curves = require('./curves.json');
  26022. function verify(sig, hash, key, signType, tag) {
  26023. var pub = parseKeys(key);
  26024. if (pub.type === 'ec') {
  26025. // rsa keys can be interpreted as ecdsa ones in openssl
  26026. if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type');
  26027. return ecVerify(sig, hash, pub);
  26028. } else if (pub.type === 'dsa') {
  26029. if (signType !== 'dsa') throw new Error('wrong public key type');
  26030. return dsaVerify(sig, hash, pub);
  26031. } else {
  26032. if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type');
  26033. }
  26034. hash = Buffer.concat([tag, hash]);
  26035. var len = pub.modulus.byteLength();
  26036. var pad = [1];
  26037. var padNum = 0;
  26038. while (hash.length + pad.length + 2 < len) {
  26039. pad.push(0xff);
  26040. padNum++;
  26041. }
  26042. pad.push(0x00);
  26043. var i = -1;
  26044. while (++i < hash.length) {
  26045. pad.push(hash[i]);
  26046. }
  26047. pad = Buffer.from(pad);
  26048. var red = BN.mont(pub.modulus);
  26049. sig = new BN(sig).toRed(red);
  26050. sig = sig.redPow(new BN(pub.publicExponent));
  26051. sig = Buffer.from(sig.fromRed().toArray());
  26052. var out = padNum < 8 ? 1 : 0;
  26053. len = Math.min(sig.length, pad.length);
  26054. if (sig.length !== pad.length) out = 1;
  26055. i = -1;
  26056. while (++i < len) out |= sig[i] ^ pad[i];
  26057. return out === 0;
  26058. }
  26059. function ecVerify(sig, hash, pub) {
  26060. var curveId = curves[pub.data.algorithm.curve.join('.')];
  26061. if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'));
  26062. var curve = new EC(curveId);
  26063. var pubkey = pub.data.subjectPrivateKey.data;
  26064. return curve.verify(hash, sig, pubkey);
  26065. }
  26066. function dsaVerify(sig, hash, pub) {
  26067. var p = pub.data.p;
  26068. var q = pub.data.q;
  26069. var g = pub.data.g;
  26070. var y = pub.data.pub_key;
  26071. var unpacked = parseKeys.signature.decode(sig, 'der');
  26072. var s = unpacked.s;
  26073. var r = unpacked.r;
  26074. checkValue(s, q);
  26075. checkValue(r, q);
  26076. var montp = BN.mont(p);
  26077. var w = s.invm(q);
  26078. var v = g.toRed(montp).redPow(new BN(hash).mul(w).mod(q)).fromRed().mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()).mod(p).mod(q);
  26079. return v.cmp(r) === 0;
  26080. }
  26081. function checkValue(b, q) {
  26082. if (b.cmpn(0) <= 0) throw new Error('invalid sig');
  26083. if (b.cmp(q) >= q) throw new Error('invalid sig');
  26084. }
  26085. module.exports = verify;
  26086. },{"./curves.json":212,"bn.js":186,"elliptic":244,"parse-asn1":298,"safe-buffer":332}],216:[function(require,module,exports){
  26087. "use strict";
  26088. },{}],217:[function(require,module,exports){
  26089. "use strict";
  26090. /* eslint-disable node/no-deprecated-api */
  26091. var buffer = require('buffer');
  26092. var Buffer = buffer.Buffer;
  26093. // alternative to using Object.keys for old browsers
  26094. function copyProps(src, dst) {
  26095. for (var key in src) {
  26096. dst[key] = src[key];
  26097. }
  26098. }
  26099. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  26100. module.exports = buffer;
  26101. } else {
  26102. // Copy properties from require('buffer')
  26103. copyProps(buffer, exports);
  26104. exports.Buffer = SafeBuffer;
  26105. }
  26106. function SafeBuffer(arg, encodingOrOffset, length) {
  26107. return Buffer(arg, encodingOrOffset, length);
  26108. }
  26109. // Copy static methods from Buffer
  26110. copyProps(Buffer, SafeBuffer);
  26111. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  26112. if (typeof arg === 'number') {
  26113. throw new TypeError('Argument must not be a number');
  26114. }
  26115. return Buffer(arg, encodingOrOffset, length);
  26116. };
  26117. SafeBuffer.alloc = function (size, fill, encoding) {
  26118. if (typeof size !== 'number') {
  26119. throw new TypeError('Argument must be a number');
  26120. }
  26121. var buf = Buffer(size);
  26122. if (fill !== undefined) {
  26123. if (typeof encoding === 'string') {
  26124. buf.fill(fill, encoding);
  26125. } else {
  26126. buf.fill(fill);
  26127. }
  26128. } else {
  26129. buf.fill(0);
  26130. }
  26131. return buf;
  26132. };
  26133. SafeBuffer.allocUnsafe = function (size) {
  26134. if (typeof size !== 'number') {
  26135. throw new TypeError('Argument must be a number');
  26136. }
  26137. return Buffer(size);
  26138. };
  26139. SafeBuffer.allocUnsafeSlow = function (size) {
  26140. if (typeof size !== 'number') {
  26141. throw new TypeError('Argument must be a number');
  26142. }
  26143. return buffer.SlowBuffer(size);
  26144. };
  26145. },{"buffer":220}],218:[function(require,module,exports){
  26146. // Copyright Joyent, Inc. and other Node contributors.
  26147. //
  26148. // Permission is hereby granted, free of charge, to any person obtaining a
  26149. // copy of this software and associated documentation files (the
  26150. // "Software"), to deal in the Software without restriction, including
  26151. // without limitation the rights to use, copy, modify, merge, publish,
  26152. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26153. // persons to whom the Software is furnished to do so, subject to the
  26154. // following conditions:
  26155. //
  26156. // The above copyright notice and this permission notice shall be included
  26157. // in all copies or substantial portions of the Software.
  26158. //
  26159. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26160. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26161. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26162. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26163. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26164. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26165. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26166. 'use strict';
  26167. /*<replacement>*/
  26168. var Buffer = require('safe-buffer').Buffer;
  26169. /*</replacement>*/
  26170. var isEncoding = Buffer.isEncoding || function (encoding) {
  26171. encoding = '' + encoding;
  26172. switch (encoding && encoding.toLowerCase()) {
  26173. case 'hex':
  26174. case 'utf8':
  26175. case 'utf-8':
  26176. case 'ascii':
  26177. case 'binary':
  26178. case 'base64':
  26179. case 'ucs2':
  26180. case 'ucs-2':
  26181. case 'utf16le':
  26182. case 'utf-16le':
  26183. case 'raw':
  26184. return true;
  26185. default:
  26186. return false;
  26187. }
  26188. };
  26189. function _normalizeEncoding(enc) {
  26190. if (!enc) return 'utf8';
  26191. var retried;
  26192. while (true) {
  26193. switch (enc) {
  26194. case 'utf8':
  26195. case 'utf-8':
  26196. return 'utf8';
  26197. case 'ucs2':
  26198. case 'ucs-2':
  26199. case 'utf16le':
  26200. case 'utf-16le':
  26201. return 'utf16le';
  26202. case 'latin1':
  26203. case 'binary':
  26204. return 'latin1';
  26205. case 'base64':
  26206. case 'ascii':
  26207. case 'hex':
  26208. return enc;
  26209. default:
  26210. if (retried) return; // undefined
  26211. enc = ('' + enc).toLowerCase();
  26212. retried = true;
  26213. }
  26214. }
  26215. }
  26216. ;
  26217. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  26218. // modules monkey-patch it to support additional encodings
  26219. function normalizeEncoding(enc) {
  26220. var nenc = _normalizeEncoding(enc);
  26221. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  26222. return nenc || enc;
  26223. }
  26224. // StringDecoder provides an interface for efficiently splitting a series of
  26225. // buffers into a series of JS strings without breaking apart multi-byte
  26226. // characters.
  26227. exports.StringDecoder = StringDecoder;
  26228. function StringDecoder(encoding) {
  26229. this.encoding = normalizeEncoding(encoding);
  26230. var nb;
  26231. switch (this.encoding) {
  26232. case 'utf16le':
  26233. this.text = utf16Text;
  26234. this.end = utf16End;
  26235. nb = 4;
  26236. break;
  26237. case 'utf8':
  26238. this.fillLast = utf8FillLast;
  26239. nb = 4;
  26240. break;
  26241. case 'base64':
  26242. this.text = base64Text;
  26243. this.end = base64End;
  26244. nb = 3;
  26245. break;
  26246. default:
  26247. this.write = simpleWrite;
  26248. this.end = simpleEnd;
  26249. return;
  26250. }
  26251. this.lastNeed = 0;
  26252. this.lastTotal = 0;
  26253. this.lastChar = Buffer.allocUnsafe(nb);
  26254. }
  26255. StringDecoder.prototype.write = function (buf) {
  26256. if (buf.length === 0) return '';
  26257. var r;
  26258. var i;
  26259. if (this.lastNeed) {
  26260. r = this.fillLast(buf);
  26261. if (r === undefined) return '';
  26262. i = this.lastNeed;
  26263. this.lastNeed = 0;
  26264. } else {
  26265. i = 0;
  26266. }
  26267. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  26268. return r || '';
  26269. };
  26270. StringDecoder.prototype.end = utf8End;
  26271. // Returns only complete characters in a Buffer
  26272. StringDecoder.prototype.text = utf8Text;
  26273. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  26274. StringDecoder.prototype.fillLast = function (buf) {
  26275. if (this.lastNeed <= buf.length) {
  26276. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  26277. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  26278. }
  26279. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  26280. this.lastNeed -= buf.length;
  26281. };
  26282. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  26283. // continuation byte. If an invalid byte is detected, -2 is returned.
  26284. function utf8CheckByte(byte) {
  26285. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  26286. return byte >> 6 === 0x02 ? -1 : -2;
  26287. }
  26288. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  26289. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  26290. // needed to complete the UTF-8 character (if applicable) are returned.
  26291. function utf8CheckIncomplete(self, buf, i) {
  26292. var j = buf.length - 1;
  26293. if (j < i) return 0;
  26294. var nb = utf8CheckByte(buf[j]);
  26295. if (nb >= 0) {
  26296. if (nb > 0) self.lastNeed = nb - 1;
  26297. return nb;
  26298. }
  26299. if (--j < i || nb === -2) return 0;
  26300. nb = utf8CheckByte(buf[j]);
  26301. if (nb >= 0) {
  26302. if (nb > 0) self.lastNeed = nb - 2;
  26303. return nb;
  26304. }
  26305. if (--j < i || nb === -2) return 0;
  26306. nb = utf8CheckByte(buf[j]);
  26307. if (nb >= 0) {
  26308. if (nb > 0) {
  26309. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  26310. }
  26311. return nb;
  26312. }
  26313. return 0;
  26314. }
  26315. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  26316. // needed or are available. If we see a non-continuation byte where we expect
  26317. // one, we "replace" the validated continuation bytes we've seen so far with
  26318. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  26319. // behavior. The continuation byte check is included three times in the case
  26320. // where all of the continuation bytes for a character exist in the same buffer.
  26321. // It is also done this way as a slight performance increase instead of using a
  26322. // loop.
  26323. function utf8CheckExtraBytes(self, buf, p) {
  26324. if ((buf[0] & 0xC0) !== 0x80) {
  26325. self.lastNeed = 0;
  26326. return '\ufffd';
  26327. }
  26328. if (self.lastNeed > 1 && buf.length > 1) {
  26329. if ((buf[1] & 0xC0) !== 0x80) {
  26330. self.lastNeed = 1;
  26331. return '\ufffd';
  26332. }
  26333. if (self.lastNeed > 2 && buf.length > 2) {
  26334. if ((buf[2] & 0xC0) !== 0x80) {
  26335. self.lastNeed = 2;
  26336. return '\ufffd';
  26337. }
  26338. }
  26339. }
  26340. }
  26341. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  26342. function utf8FillLast(buf) {
  26343. var p = this.lastTotal - this.lastNeed;
  26344. var r = utf8CheckExtraBytes(this, buf, p);
  26345. if (r !== undefined) return r;
  26346. if (this.lastNeed <= buf.length) {
  26347. buf.copy(this.lastChar, p, 0, this.lastNeed);
  26348. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  26349. }
  26350. buf.copy(this.lastChar, p, 0, buf.length);
  26351. this.lastNeed -= buf.length;
  26352. }
  26353. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  26354. // partial character, the character's bytes are buffered until the required
  26355. // number of bytes are available.
  26356. function utf8Text(buf, i) {
  26357. var total = utf8CheckIncomplete(this, buf, i);
  26358. if (!this.lastNeed) return buf.toString('utf8', i);
  26359. this.lastTotal = total;
  26360. var end = buf.length - (total - this.lastNeed);
  26361. buf.copy(this.lastChar, 0, end);
  26362. return buf.toString('utf8', i, end);
  26363. }
  26364. // For UTF-8, a replacement character is added when ending on a partial
  26365. // character.
  26366. function utf8End(buf) {
  26367. var r = buf && buf.length ? this.write(buf) : '';
  26368. if (this.lastNeed) return r + '\ufffd';
  26369. return r;
  26370. }
  26371. // UTF-16LE typically needs two bytes per character, but even if we have an even
  26372. // number of bytes available, we need to check if we end on a leading/high
  26373. // surrogate. In that case, we need to wait for the next two bytes in order to
  26374. // decode the last character properly.
  26375. function utf16Text(buf, i) {
  26376. if ((buf.length - i) % 2 === 0) {
  26377. var r = buf.toString('utf16le', i);
  26378. if (r) {
  26379. var c = r.charCodeAt(r.length - 1);
  26380. if (c >= 0xD800 && c <= 0xDBFF) {
  26381. this.lastNeed = 2;
  26382. this.lastTotal = 4;
  26383. this.lastChar[0] = buf[buf.length - 2];
  26384. this.lastChar[1] = buf[buf.length - 1];
  26385. return r.slice(0, -1);
  26386. }
  26387. }
  26388. return r;
  26389. }
  26390. this.lastNeed = 1;
  26391. this.lastTotal = 2;
  26392. this.lastChar[0] = buf[buf.length - 1];
  26393. return buf.toString('utf16le', i, buf.length - 1);
  26394. }
  26395. // For UTF-16LE we do not explicitly append special replacement characters if we
  26396. // end on a partial character, we simply let v8 handle that.
  26397. function utf16End(buf) {
  26398. var r = buf && buf.length ? this.write(buf) : '';
  26399. if (this.lastNeed) {
  26400. var end = this.lastTotal - this.lastNeed;
  26401. return r + this.lastChar.toString('utf16le', 0, end);
  26402. }
  26403. return r;
  26404. }
  26405. function base64Text(buf, i) {
  26406. var n = (buf.length - i) % 3;
  26407. if (n === 0) return buf.toString('base64', i);
  26408. this.lastNeed = 3 - n;
  26409. this.lastTotal = 3;
  26410. if (n === 1) {
  26411. this.lastChar[0] = buf[buf.length - 1];
  26412. } else {
  26413. this.lastChar[0] = buf[buf.length - 2];
  26414. this.lastChar[1] = buf[buf.length - 1];
  26415. }
  26416. return buf.toString('base64', i, buf.length - n);
  26417. }
  26418. function base64End(buf) {
  26419. var r = buf && buf.length ? this.write(buf) : '';
  26420. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  26421. return r;
  26422. }
  26423. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  26424. function simpleWrite(buf) {
  26425. return buf.toString(this.encoding);
  26426. }
  26427. function simpleEnd(buf) {
  26428. return buf && buf.length ? this.write(buf) : '';
  26429. }
  26430. },{"safe-buffer":217}],219:[function(require,module,exports){
  26431. (function (Buffer){(function (){
  26432. "use strict";
  26433. module.exports = function xor(a, b) {
  26434. var length = Math.min(a.length, b.length);
  26435. var buffer = new Buffer(length);
  26436. for (var i = 0; i < length; ++i) {
  26437. buffer[i] = a[i] ^ b[i];
  26438. }
  26439. return buffer;
  26440. };
  26441. }).call(this)}).call(this,require("buffer").Buffer)
  26442. },{"buffer":220}],220:[function(require,module,exports){
  26443. (function (Buffer){(function (){
  26444. /*!
  26445. * The buffer module from node.js, for the browser.
  26446. *
  26447. * @author Feross Aboukhadijeh <https://feross.org>
  26448. * @license MIT
  26449. */
  26450. /* eslint-disable no-proto */
  26451. 'use strict';
  26452. var base64 = require('base64-js');
  26453. var ieee754 = require('ieee754');
  26454. exports.Buffer = Buffer;
  26455. exports.SlowBuffer = SlowBuffer;
  26456. exports.INSPECT_MAX_BYTES = 50;
  26457. var K_MAX_LENGTH = 0x7fffffff;
  26458. exports.kMaxLength = K_MAX_LENGTH;
  26459. /**
  26460. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  26461. * === true Use Uint8Array implementation (fastest)
  26462. * === false Print warning and recommend using `buffer` v4.x which has an Object
  26463. * implementation (most compatible, even IE6)
  26464. *
  26465. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  26466. * Opera 11.6+, iOS 4.2+.
  26467. *
  26468. * We report that the browser does not support typed arrays if the are not subclassable
  26469. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  26470. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  26471. * for __proto__ and has a buggy typed array implementation.
  26472. */
  26473. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
  26474. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') {
  26475. console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.');
  26476. }
  26477. function typedArraySupport() {
  26478. // Can typed array instances can be augmented?
  26479. try {
  26480. var arr = new Uint8Array(1);
  26481. arr.__proto__ = {
  26482. __proto__: Uint8Array.prototype,
  26483. foo: function () {
  26484. return 42;
  26485. }
  26486. };
  26487. return arr.foo() === 42;
  26488. } catch (e) {
  26489. return false;
  26490. }
  26491. }
  26492. Object.defineProperty(Buffer.prototype, 'parent', {
  26493. enumerable: true,
  26494. get: function () {
  26495. if (!Buffer.isBuffer(this)) return undefined;
  26496. return this.buffer;
  26497. }
  26498. });
  26499. Object.defineProperty(Buffer.prototype, 'offset', {
  26500. enumerable: true,
  26501. get: function () {
  26502. if (!Buffer.isBuffer(this)) return undefined;
  26503. return this.byteOffset;
  26504. }
  26505. });
  26506. function createBuffer(length) {
  26507. if (length > K_MAX_LENGTH) {
  26508. throw new RangeError('The value "' + length + '" is invalid for option "size"');
  26509. }
  26510. // Return an augmented `Uint8Array` instance
  26511. var buf = new Uint8Array(length);
  26512. buf.__proto__ = Buffer.prototype;
  26513. return buf;
  26514. }
  26515. /**
  26516. * The Buffer constructor returns instances of `Uint8Array` that have their
  26517. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  26518. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  26519. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  26520. * returns a single octet.
  26521. *
  26522. * The `Uint8Array` prototype remains unmodified.
  26523. */
  26524. function Buffer(arg, encodingOrOffset, length) {
  26525. // Common case.
  26526. if (typeof arg === 'number') {
  26527. if (typeof encodingOrOffset === 'string') {
  26528. throw new TypeError('The "string" argument must be of type string. Received type number');
  26529. }
  26530. return allocUnsafe(arg);
  26531. }
  26532. return from(arg, encodingOrOffset, length);
  26533. }
  26534. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  26535. if (typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer) {
  26536. Object.defineProperty(Buffer, Symbol.species, {
  26537. value: null,
  26538. configurable: true,
  26539. enumerable: false,
  26540. writable: false
  26541. });
  26542. }
  26543. Buffer.poolSize = 8192; // not used by this implementation
  26544. function from(value, encodingOrOffset, length) {
  26545. if (typeof value === 'string') {
  26546. return fromString(value, encodingOrOffset);
  26547. }
  26548. if (ArrayBuffer.isView(value)) {
  26549. return fromArrayLike(value);
  26550. }
  26551. if (value == null) {
  26552. throw TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + typeof value);
  26553. }
  26554. if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
  26555. return fromArrayBuffer(value, encodingOrOffset, length);
  26556. }
  26557. if (typeof value === 'number') {
  26558. throw new TypeError('The "value" argument must not be of type number. Received type number');
  26559. }
  26560. var valueOf = value.valueOf && value.valueOf();
  26561. if (valueOf != null && valueOf !== value) {
  26562. return Buffer.from(valueOf, encodingOrOffset, length);
  26563. }
  26564. var b = fromObject(value);
  26565. if (b) return b;
  26566. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') {
  26567. return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length);
  26568. }
  26569. throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + typeof value);
  26570. }
  26571. /**
  26572. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  26573. * if value is a number.
  26574. * Buffer.from(str[, encoding])
  26575. * Buffer.from(array)
  26576. * Buffer.from(buffer)
  26577. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  26578. **/
  26579. Buffer.from = function (value, encodingOrOffset, length) {
  26580. return from(value, encodingOrOffset, length);
  26581. };
  26582. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  26583. // https://github.com/feross/buffer/pull/148
  26584. Buffer.prototype.__proto__ = Uint8Array.prototype;
  26585. Buffer.__proto__ = Uint8Array;
  26586. function assertSize(size) {
  26587. if (typeof size !== 'number') {
  26588. throw new TypeError('"size" argument must be of type number');
  26589. } else if (size < 0) {
  26590. throw new RangeError('The value "' + size + '" is invalid for option "size"');
  26591. }
  26592. }
  26593. function alloc(size, fill, encoding) {
  26594. assertSize(size);
  26595. if (size <= 0) {
  26596. return createBuffer(size);
  26597. }
  26598. if (fill !== undefined) {
  26599. // Only pay attention to encoding if it's a string. This
  26600. // prevents accidentally sending in a number that would
  26601. // be interpretted as a start offset.
  26602. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
  26603. }
  26604. return createBuffer(size);
  26605. }
  26606. /**
  26607. * Creates a new filled Buffer instance.
  26608. * alloc(size[, fill[, encoding]])
  26609. **/
  26610. Buffer.alloc = function (size, fill, encoding) {
  26611. return alloc(size, fill, encoding);
  26612. };
  26613. function allocUnsafe(size) {
  26614. assertSize(size);
  26615. return createBuffer(size < 0 ? 0 : checked(size) | 0);
  26616. }
  26617. /**
  26618. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  26619. * */
  26620. Buffer.allocUnsafe = function (size) {
  26621. return allocUnsafe(size);
  26622. };
  26623. /**
  26624. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  26625. */
  26626. Buffer.allocUnsafeSlow = function (size) {
  26627. return allocUnsafe(size);
  26628. };
  26629. function fromString(string, encoding) {
  26630. if (typeof encoding !== 'string' || encoding === '') {
  26631. encoding = 'utf8';
  26632. }
  26633. if (!Buffer.isEncoding(encoding)) {
  26634. throw new TypeError('Unknown encoding: ' + encoding);
  26635. }
  26636. var length = byteLength(string, encoding) | 0;
  26637. var buf = createBuffer(length);
  26638. var actual = buf.write(string, encoding);
  26639. if (actual !== length) {
  26640. // Writing a hex string, for example, that contains invalid characters will
  26641. // cause everything after the first invalid character to be ignored. (e.g.
  26642. // 'abxxcd' will be treated as 'ab')
  26643. buf = buf.slice(0, actual);
  26644. }
  26645. return buf;
  26646. }
  26647. function fromArrayLike(array) {
  26648. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  26649. var buf = createBuffer(length);
  26650. for (var i = 0; i < length; i += 1) {
  26651. buf[i] = array[i] & 255;
  26652. }
  26653. return buf;
  26654. }
  26655. function fromArrayBuffer(array, byteOffset, length) {
  26656. if (byteOffset < 0 || array.byteLength < byteOffset) {
  26657. throw new RangeError('"offset" is outside of buffer bounds');
  26658. }
  26659. if (array.byteLength < byteOffset + (length || 0)) {
  26660. throw new RangeError('"length" is outside of buffer bounds');
  26661. }
  26662. var buf;
  26663. if (byteOffset === undefined && length === undefined) {
  26664. buf = new Uint8Array(array);
  26665. } else if (length === undefined) {
  26666. buf = new Uint8Array(array, byteOffset);
  26667. } else {
  26668. buf = new Uint8Array(array, byteOffset, length);
  26669. }
  26670. // Return an augmented `Uint8Array` instance
  26671. buf.__proto__ = Buffer.prototype;
  26672. return buf;
  26673. }
  26674. function fromObject(obj) {
  26675. if (Buffer.isBuffer(obj)) {
  26676. var len = checked(obj.length) | 0;
  26677. var buf = createBuffer(len);
  26678. if (buf.length === 0) {
  26679. return buf;
  26680. }
  26681. obj.copy(buf, 0, 0, len);
  26682. return buf;
  26683. }
  26684. if (obj.length !== undefined) {
  26685. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  26686. return createBuffer(0);
  26687. }
  26688. return fromArrayLike(obj);
  26689. }
  26690. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  26691. return fromArrayLike(obj.data);
  26692. }
  26693. }
  26694. function checked(length) {
  26695. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  26696. // length is NaN (which is otherwise coerced to zero.)
  26697. if (length >= K_MAX_LENGTH) {
  26698. throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes');
  26699. }
  26700. return length | 0;
  26701. }
  26702. function SlowBuffer(length) {
  26703. if (+length != length) {
  26704. // eslint-disable-line eqeqeq
  26705. length = 0;
  26706. }
  26707. return Buffer.alloc(+length);
  26708. }
  26709. Buffer.isBuffer = function isBuffer(b) {
  26710. return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false
  26711. };
  26712. Buffer.compare = function compare(a, b) {
  26713. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
  26714. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
  26715. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  26716. throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
  26717. }
  26718. if (a === b) return 0;
  26719. var x = a.length;
  26720. var y = b.length;
  26721. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  26722. if (a[i] !== b[i]) {
  26723. x = a[i];
  26724. y = b[i];
  26725. break;
  26726. }
  26727. }
  26728. if (x < y) return -1;
  26729. if (y < x) return 1;
  26730. return 0;
  26731. };
  26732. Buffer.isEncoding = function isEncoding(encoding) {
  26733. switch (String(encoding).toLowerCase()) {
  26734. case 'hex':
  26735. case 'utf8':
  26736. case 'utf-8':
  26737. case 'ascii':
  26738. case 'latin1':
  26739. case 'binary':
  26740. case 'base64':
  26741. case 'ucs2':
  26742. case 'ucs-2':
  26743. case 'utf16le':
  26744. case 'utf-16le':
  26745. return true;
  26746. default:
  26747. return false;
  26748. }
  26749. };
  26750. Buffer.concat = function concat(list, length) {
  26751. if (!Array.isArray(list)) {
  26752. throw new TypeError('"list" argument must be an Array of Buffers');
  26753. }
  26754. if (list.length === 0) {
  26755. return Buffer.alloc(0);
  26756. }
  26757. var i;
  26758. if (length === undefined) {
  26759. length = 0;
  26760. for (i = 0; i < list.length; ++i) {
  26761. length += list[i].length;
  26762. }
  26763. }
  26764. var buffer = Buffer.allocUnsafe(length);
  26765. var pos = 0;
  26766. for (i = 0; i < list.length; ++i) {
  26767. var buf = list[i];
  26768. if (isInstance(buf, Uint8Array)) {
  26769. buf = Buffer.from(buf);
  26770. }
  26771. if (!Buffer.isBuffer(buf)) {
  26772. throw new TypeError('"list" argument must be an Array of Buffers');
  26773. }
  26774. buf.copy(buffer, pos);
  26775. pos += buf.length;
  26776. }
  26777. return buffer;
  26778. };
  26779. function byteLength(string, encoding) {
  26780. if (Buffer.isBuffer(string)) {
  26781. return string.length;
  26782. }
  26783. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  26784. return string.byteLength;
  26785. }
  26786. if (typeof string !== 'string') {
  26787. throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string);
  26788. }
  26789. var len = string.length;
  26790. var mustMatch = arguments.length > 2 && arguments[2] === true;
  26791. if (!mustMatch && len === 0) return 0;
  26792. // Use a for loop to avoid recursion
  26793. var loweredCase = false;
  26794. for (;;) {
  26795. switch (encoding) {
  26796. case 'ascii':
  26797. case 'latin1':
  26798. case 'binary':
  26799. return len;
  26800. case 'utf8':
  26801. case 'utf-8':
  26802. return utf8ToBytes(string).length;
  26803. case 'ucs2':
  26804. case 'ucs-2':
  26805. case 'utf16le':
  26806. case 'utf-16le':
  26807. return len * 2;
  26808. case 'hex':
  26809. return len >>> 1;
  26810. case 'base64':
  26811. return base64ToBytes(string).length;
  26812. default:
  26813. if (loweredCase) {
  26814. return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8
  26815. }
  26816. encoding = ('' + encoding).toLowerCase();
  26817. loweredCase = true;
  26818. }
  26819. }
  26820. }
  26821. Buffer.byteLength = byteLength;
  26822. function slowToString(encoding, start, end) {
  26823. var loweredCase = false;
  26824. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  26825. // property of a typed array.
  26826. // This behaves neither like String nor Uint8Array in that we set start/end
  26827. // to their upper/lower bounds if the value passed is out of range.
  26828. // undefined is handled specially as per ECMA-262 6th Edition,
  26829. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  26830. if (start === undefined || start < 0) {
  26831. start = 0;
  26832. }
  26833. // Return early if start > this.length. Done here to prevent potential uint32
  26834. // coercion fail below.
  26835. if (start > this.length) {
  26836. return '';
  26837. }
  26838. if (end === undefined || end > this.length) {
  26839. end = this.length;
  26840. }
  26841. if (end <= 0) {
  26842. return '';
  26843. }
  26844. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  26845. end >>>= 0;
  26846. start >>>= 0;
  26847. if (end <= start) {
  26848. return '';
  26849. }
  26850. if (!encoding) encoding = 'utf8';
  26851. while (true) {
  26852. switch (encoding) {
  26853. case 'hex':
  26854. return hexSlice(this, start, end);
  26855. case 'utf8':
  26856. case 'utf-8':
  26857. return utf8Slice(this, start, end);
  26858. case 'ascii':
  26859. return asciiSlice(this, start, end);
  26860. case 'latin1':
  26861. case 'binary':
  26862. return latin1Slice(this, start, end);
  26863. case 'base64':
  26864. return base64Slice(this, start, end);
  26865. case 'ucs2':
  26866. case 'ucs-2':
  26867. case 'utf16le':
  26868. case 'utf-16le':
  26869. return utf16leSlice(this, start, end);
  26870. default:
  26871. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
  26872. encoding = (encoding + '').toLowerCase();
  26873. loweredCase = true;
  26874. }
  26875. }
  26876. }
  26877. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  26878. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  26879. // reliably in a browserify context because there could be multiple different
  26880. // copies of the 'buffer' package in use. This method works even for Buffer
  26881. // instances that were created from another copy of the `buffer` package.
  26882. // See: https://github.com/feross/buffer/issues/154
  26883. Buffer.prototype._isBuffer = true;
  26884. function swap(b, n, m) {
  26885. var i = b[n];
  26886. b[n] = b[m];
  26887. b[m] = i;
  26888. }
  26889. Buffer.prototype.swap16 = function swap16() {
  26890. var len = this.length;
  26891. if (len % 2 !== 0) {
  26892. throw new RangeError('Buffer size must be a multiple of 16-bits');
  26893. }
  26894. for (var i = 0; i < len; i += 2) {
  26895. swap(this, i, i + 1);
  26896. }
  26897. return this;
  26898. };
  26899. Buffer.prototype.swap32 = function swap32() {
  26900. var len = this.length;
  26901. if (len % 4 !== 0) {
  26902. throw new RangeError('Buffer size must be a multiple of 32-bits');
  26903. }
  26904. for (var i = 0; i < len; i += 4) {
  26905. swap(this, i, i + 3);
  26906. swap(this, i + 1, i + 2);
  26907. }
  26908. return this;
  26909. };
  26910. Buffer.prototype.swap64 = function swap64() {
  26911. var len = this.length;
  26912. if (len % 8 !== 0) {
  26913. throw new RangeError('Buffer size must be a multiple of 64-bits');
  26914. }
  26915. for (var i = 0; i < len; i += 8) {
  26916. swap(this, i, i + 7);
  26917. swap(this, i + 1, i + 6);
  26918. swap(this, i + 2, i + 5);
  26919. swap(this, i + 3, i + 4);
  26920. }
  26921. return this;
  26922. };
  26923. Buffer.prototype.toString = function toString() {
  26924. var length = this.length;
  26925. if (length === 0) return '';
  26926. if (arguments.length === 0) return utf8Slice(this, 0, length);
  26927. return slowToString.apply(this, arguments);
  26928. };
  26929. Buffer.prototype.toLocaleString = Buffer.prototype.toString;
  26930. Buffer.prototype.equals = function equals(b) {
  26931. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer');
  26932. if (this === b) return true;
  26933. return Buffer.compare(this, b) === 0;
  26934. };
  26935. Buffer.prototype.inspect = function inspect() {
  26936. var str = '';
  26937. var max = exports.INSPECT_MAX_BYTES;
  26938. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
  26939. if (this.length > max) str += ' ... ';
  26940. return '<Buffer ' + str + '>';
  26941. };
  26942. Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
  26943. if (isInstance(target, Uint8Array)) {
  26944. target = Buffer.from(target, target.offset, target.byteLength);
  26945. }
  26946. if (!Buffer.isBuffer(target)) {
  26947. throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + typeof target);
  26948. }
  26949. if (start === undefined) {
  26950. start = 0;
  26951. }
  26952. if (end === undefined) {
  26953. end = target ? target.length : 0;
  26954. }
  26955. if (thisStart === undefined) {
  26956. thisStart = 0;
  26957. }
  26958. if (thisEnd === undefined) {
  26959. thisEnd = this.length;
  26960. }
  26961. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  26962. throw new RangeError('out of range index');
  26963. }
  26964. if (thisStart >= thisEnd && start >= end) {
  26965. return 0;
  26966. }
  26967. if (thisStart >= thisEnd) {
  26968. return -1;
  26969. }
  26970. if (start >= end) {
  26971. return 1;
  26972. }
  26973. start >>>= 0;
  26974. end >>>= 0;
  26975. thisStart >>>= 0;
  26976. thisEnd >>>= 0;
  26977. if (this === target) return 0;
  26978. var x = thisEnd - thisStart;
  26979. var y = end - start;
  26980. var len = Math.min(x, y);
  26981. var thisCopy = this.slice(thisStart, thisEnd);
  26982. var targetCopy = target.slice(start, end);
  26983. for (var i = 0; i < len; ++i) {
  26984. if (thisCopy[i] !== targetCopy[i]) {
  26985. x = thisCopy[i];
  26986. y = targetCopy[i];
  26987. break;
  26988. }
  26989. }
  26990. if (x < y) return -1;
  26991. if (y < x) return 1;
  26992. return 0;
  26993. };
  26994. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  26995. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  26996. //
  26997. // Arguments:
  26998. // - buffer - a Buffer to search
  26999. // - val - a string, Buffer, or number
  27000. // - byteOffset - an index into `buffer`; will be clamped to an int32
  27001. // - encoding - an optional encoding, relevant is val is a string
  27002. // - dir - true for indexOf, false for lastIndexOf
  27003. function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  27004. // Empty buffer means no match
  27005. if (buffer.length === 0) return -1;
  27006. // Normalize byteOffset
  27007. if (typeof byteOffset === 'string') {
  27008. encoding = byteOffset;
  27009. byteOffset = 0;
  27010. } else if (byteOffset > 0x7fffffff) {
  27011. byteOffset = 0x7fffffff;
  27012. } else if (byteOffset < -0x80000000) {
  27013. byteOffset = -0x80000000;
  27014. }
  27015. byteOffset = +byteOffset; // Coerce to Number.
  27016. if (numberIsNaN(byteOffset)) {
  27017. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  27018. byteOffset = dir ? 0 : buffer.length - 1;
  27019. }
  27020. // Normalize byteOffset: negative offsets start from the end of the buffer
  27021. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  27022. if (byteOffset >= buffer.length) {
  27023. if (dir) return -1;else byteOffset = buffer.length - 1;
  27024. } else if (byteOffset < 0) {
  27025. if (dir) byteOffset = 0;else return -1;
  27026. }
  27027. // Normalize val
  27028. if (typeof val === 'string') {
  27029. val = Buffer.from(val, encoding);
  27030. }
  27031. // Finally, search either indexOf (if dir is true) or lastIndexOf
  27032. if (Buffer.isBuffer(val)) {
  27033. // Special case: looking for empty string/buffer always fails
  27034. if (val.length === 0) {
  27035. return -1;
  27036. }
  27037. return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
  27038. } else if (typeof val === 'number') {
  27039. val = val & 0xFF; // Search for a byte value [0-255]
  27040. if (typeof Uint8Array.prototype.indexOf === 'function') {
  27041. if (dir) {
  27042. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
  27043. } else {
  27044. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
  27045. }
  27046. }
  27047. return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
  27048. }
  27049. throw new TypeError('val must be string, number or Buffer');
  27050. }
  27051. function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  27052. var indexSize = 1;
  27053. var arrLength = arr.length;
  27054. var valLength = val.length;
  27055. if (encoding !== undefined) {
  27056. encoding = String(encoding).toLowerCase();
  27057. if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
  27058. if (arr.length < 2 || val.length < 2) {
  27059. return -1;
  27060. }
  27061. indexSize = 2;
  27062. arrLength /= 2;
  27063. valLength /= 2;
  27064. byteOffset /= 2;
  27065. }
  27066. }
  27067. function read(buf, i) {
  27068. if (indexSize === 1) {
  27069. return buf[i];
  27070. } else {
  27071. return buf.readUInt16BE(i * indexSize);
  27072. }
  27073. }
  27074. var i;
  27075. if (dir) {
  27076. var foundIndex = -1;
  27077. for (i = byteOffset; i < arrLength; i++) {
  27078. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  27079. if (foundIndex === -1) foundIndex = i;
  27080. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
  27081. } else {
  27082. if (foundIndex !== -1) i -= i - foundIndex;
  27083. foundIndex = -1;
  27084. }
  27085. }
  27086. } else {
  27087. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  27088. for (i = byteOffset; i >= 0; i--) {
  27089. var found = true;
  27090. for (var j = 0; j < valLength; j++) {
  27091. if (read(arr, i + j) !== read(val, j)) {
  27092. found = false;
  27093. break;
  27094. }
  27095. }
  27096. if (found) return i;
  27097. }
  27098. }
  27099. return -1;
  27100. }
  27101. Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
  27102. return this.indexOf(val, byteOffset, encoding) !== -1;
  27103. };
  27104. Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
  27105. return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
  27106. };
  27107. Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
  27108. return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
  27109. };
  27110. function hexWrite(buf, string, offset, length) {
  27111. offset = Number(offset) || 0;
  27112. var remaining = buf.length - offset;
  27113. if (!length) {
  27114. length = remaining;
  27115. } else {
  27116. length = Number(length);
  27117. if (length > remaining) {
  27118. length = remaining;
  27119. }
  27120. }
  27121. var strLen = string.length;
  27122. if (length > strLen / 2) {
  27123. length = strLen / 2;
  27124. }
  27125. for (var i = 0; i < length; ++i) {
  27126. var parsed = parseInt(string.substr(i * 2, 2), 16);
  27127. if (numberIsNaN(parsed)) return i;
  27128. buf[offset + i] = parsed;
  27129. }
  27130. return i;
  27131. }
  27132. function utf8Write(buf, string, offset, length) {
  27133. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
  27134. }
  27135. function asciiWrite(buf, string, offset, length) {
  27136. return blitBuffer(asciiToBytes(string), buf, offset, length);
  27137. }
  27138. function latin1Write(buf, string, offset, length) {
  27139. return asciiWrite(buf, string, offset, length);
  27140. }
  27141. function base64Write(buf, string, offset, length) {
  27142. return blitBuffer(base64ToBytes(string), buf, offset, length);
  27143. }
  27144. function ucs2Write(buf, string, offset, length) {
  27145. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
  27146. }
  27147. Buffer.prototype.write = function write(string, offset, length, encoding) {
  27148. // Buffer#write(string)
  27149. if (offset === undefined) {
  27150. encoding = 'utf8';
  27151. length = this.length;
  27152. offset = 0;
  27153. // Buffer#write(string, encoding)
  27154. } else if (length === undefined && typeof offset === 'string') {
  27155. encoding = offset;
  27156. length = this.length;
  27157. offset = 0;
  27158. // Buffer#write(string, offset[, length][, encoding])
  27159. } else if (isFinite(offset)) {
  27160. offset = offset >>> 0;
  27161. if (isFinite(length)) {
  27162. length = length >>> 0;
  27163. if (encoding === undefined) encoding = 'utf8';
  27164. } else {
  27165. encoding = length;
  27166. length = undefined;
  27167. }
  27168. } else {
  27169. throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
  27170. }
  27171. var remaining = this.length - offset;
  27172. if (length === undefined || length > remaining) length = remaining;
  27173. if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
  27174. throw new RangeError('Attempt to write outside buffer bounds');
  27175. }
  27176. if (!encoding) encoding = 'utf8';
  27177. var loweredCase = false;
  27178. for (;;) {
  27179. switch (encoding) {
  27180. case 'hex':
  27181. return hexWrite(this, string, offset, length);
  27182. case 'utf8':
  27183. case 'utf-8':
  27184. return utf8Write(this, string, offset, length);
  27185. case 'ascii':
  27186. return asciiWrite(this, string, offset, length);
  27187. case 'latin1':
  27188. case 'binary':
  27189. return latin1Write(this, string, offset, length);
  27190. case 'base64':
  27191. // Warning: maxLength not taken into account in base64Write
  27192. return base64Write(this, string, offset, length);
  27193. case 'ucs2':
  27194. case 'ucs-2':
  27195. case 'utf16le':
  27196. case 'utf-16le':
  27197. return ucs2Write(this, string, offset, length);
  27198. default:
  27199. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
  27200. encoding = ('' + encoding).toLowerCase();
  27201. loweredCase = true;
  27202. }
  27203. }
  27204. };
  27205. Buffer.prototype.toJSON = function toJSON() {
  27206. return {
  27207. type: 'Buffer',
  27208. data: Array.prototype.slice.call(this._arr || this, 0)
  27209. };
  27210. };
  27211. function base64Slice(buf, start, end) {
  27212. if (start === 0 && end === buf.length) {
  27213. return base64.fromByteArray(buf);
  27214. } else {
  27215. return base64.fromByteArray(buf.slice(start, end));
  27216. }
  27217. }
  27218. function utf8Slice(buf, start, end) {
  27219. end = Math.min(buf.length, end);
  27220. var res = [];
  27221. var i = start;
  27222. while (i < end) {
  27223. var firstByte = buf[i];
  27224. var codePoint = null;
  27225. var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
  27226. if (i + bytesPerSequence <= end) {
  27227. var secondByte, thirdByte, fourthByte, tempCodePoint;
  27228. switch (bytesPerSequence) {
  27229. case 1:
  27230. if (firstByte < 0x80) {
  27231. codePoint = firstByte;
  27232. }
  27233. break;
  27234. case 2:
  27235. secondByte = buf[i + 1];
  27236. if ((secondByte & 0xC0) === 0x80) {
  27237. tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
  27238. if (tempCodePoint > 0x7F) {
  27239. codePoint = tempCodePoint;
  27240. }
  27241. }
  27242. break;
  27243. case 3:
  27244. secondByte = buf[i + 1];
  27245. thirdByte = buf[i + 2];
  27246. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  27247. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
  27248. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  27249. codePoint = tempCodePoint;
  27250. }
  27251. }
  27252. break;
  27253. case 4:
  27254. secondByte = buf[i + 1];
  27255. thirdByte = buf[i + 2];
  27256. fourthByte = buf[i + 3];
  27257. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  27258. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
  27259. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  27260. codePoint = tempCodePoint;
  27261. }
  27262. }
  27263. }
  27264. }
  27265. if (codePoint === null) {
  27266. // we did not generate a valid codePoint so insert a
  27267. // replacement char (U+FFFD) and advance only 1 byte
  27268. codePoint = 0xFFFD;
  27269. bytesPerSequence = 1;
  27270. } else if (codePoint > 0xFFFF) {
  27271. // encode to utf16 (surrogate pair dance)
  27272. codePoint -= 0x10000;
  27273. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  27274. codePoint = 0xDC00 | codePoint & 0x3FF;
  27275. }
  27276. res.push(codePoint);
  27277. i += bytesPerSequence;
  27278. }
  27279. return decodeCodePointsArray(res);
  27280. }
  27281. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  27282. // the lowest limit is Chrome, with 0x10000 args.
  27283. // We go 1 magnitude less, for safety
  27284. var MAX_ARGUMENTS_LENGTH = 0x1000;
  27285. function decodeCodePointsArray(codePoints) {
  27286. var len = codePoints.length;
  27287. if (len <= MAX_ARGUMENTS_LENGTH) {
  27288. return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
  27289. }
  27290. // Decode in chunks to avoid "call stack size exceeded".
  27291. var res = '';
  27292. var i = 0;
  27293. while (i < len) {
  27294. res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
  27295. }
  27296. return res;
  27297. }
  27298. function asciiSlice(buf, start, end) {
  27299. var ret = '';
  27300. end = Math.min(buf.length, end);
  27301. for (var i = start; i < end; ++i) {
  27302. ret += String.fromCharCode(buf[i] & 0x7F);
  27303. }
  27304. return ret;
  27305. }
  27306. function latin1Slice(buf, start, end) {
  27307. var ret = '';
  27308. end = Math.min(buf.length, end);
  27309. for (var i = start; i < end; ++i) {
  27310. ret += String.fromCharCode(buf[i]);
  27311. }
  27312. return ret;
  27313. }
  27314. function hexSlice(buf, start, end) {
  27315. var len = buf.length;
  27316. if (!start || start < 0) start = 0;
  27317. if (!end || end < 0 || end > len) end = len;
  27318. var out = '';
  27319. for (var i = start; i < end; ++i) {
  27320. out += toHex(buf[i]);
  27321. }
  27322. return out;
  27323. }
  27324. function utf16leSlice(buf, start, end) {
  27325. var bytes = buf.slice(start, end);
  27326. var res = '';
  27327. for (var i = 0; i < bytes.length; i += 2) {
  27328. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  27329. }
  27330. return res;
  27331. }
  27332. Buffer.prototype.slice = function slice(start, end) {
  27333. var len = this.length;
  27334. start = ~~start;
  27335. end = end === undefined ? len : ~~end;
  27336. if (start < 0) {
  27337. start += len;
  27338. if (start < 0) start = 0;
  27339. } else if (start > len) {
  27340. start = len;
  27341. }
  27342. if (end < 0) {
  27343. end += len;
  27344. if (end < 0) end = 0;
  27345. } else if (end > len) {
  27346. end = len;
  27347. }
  27348. if (end < start) end = start;
  27349. var newBuf = this.subarray(start, end);
  27350. // Return an augmented `Uint8Array` instance
  27351. newBuf.__proto__ = Buffer.prototype;
  27352. return newBuf;
  27353. };
  27354. /*
  27355. * Need to make sure that buffer isn't trying to write out of bounds.
  27356. */
  27357. function checkOffset(offset, ext, length) {
  27358. if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
  27359. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
  27360. }
  27361. Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
  27362. offset = offset >>> 0;
  27363. byteLength = byteLength >>> 0;
  27364. if (!noAssert) checkOffset(offset, byteLength, this.length);
  27365. var val = this[offset];
  27366. var mul = 1;
  27367. var i = 0;
  27368. while (++i < byteLength && (mul *= 0x100)) {
  27369. val += this[offset + i] * mul;
  27370. }
  27371. return val;
  27372. };
  27373. Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
  27374. offset = offset >>> 0;
  27375. byteLength = byteLength >>> 0;
  27376. if (!noAssert) {
  27377. checkOffset(offset, byteLength, this.length);
  27378. }
  27379. var val = this[offset + --byteLength];
  27380. var mul = 1;
  27381. while (byteLength > 0 && (mul *= 0x100)) {
  27382. val += this[offset + --byteLength] * mul;
  27383. }
  27384. return val;
  27385. };
  27386. Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
  27387. offset = offset >>> 0;
  27388. if (!noAssert) checkOffset(offset, 1, this.length);
  27389. return this[offset];
  27390. };
  27391. Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
  27392. offset = offset >>> 0;
  27393. if (!noAssert) checkOffset(offset, 2, this.length);
  27394. return this[offset] | this[offset + 1] << 8;
  27395. };
  27396. Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
  27397. offset = offset >>> 0;
  27398. if (!noAssert) checkOffset(offset, 2, this.length);
  27399. return this[offset] << 8 | this[offset + 1];
  27400. };
  27401. Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
  27402. offset = offset >>> 0;
  27403. if (!noAssert) checkOffset(offset, 4, this.length);
  27404. return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
  27405. };
  27406. Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
  27407. offset = offset >>> 0;
  27408. if (!noAssert) checkOffset(offset, 4, this.length);
  27409. return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
  27410. };
  27411. Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
  27412. offset = offset >>> 0;
  27413. byteLength = byteLength >>> 0;
  27414. if (!noAssert) checkOffset(offset, byteLength, this.length);
  27415. var val = this[offset];
  27416. var mul = 1;
  27417. var i = 0;
  27418. while (++i < byteLength && (mul *= 0x100)) {
  27419. val += this[offset + i] * mul;
  27420. }
  27421. mul *= 0x80;
  27422. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  27423. return val;
  27424. };
  27425. Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
  27426. offset = offset >>> 0;
  27427. byteLength = byteLength >>> 0;
  27428. if (!noAssert) checkOffset(offset, byteLength, this.length);
  27429. var i = byteLength;
  27430. var mul = 1;
  27431. var val = this[offset + --i];
  27432. while (i > 0 && (mul *= 0x100)) {
  27433. val += this[offset + --i] * mul;
  27434. }
  27435. mul *= 0x80;
  27436. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  27437. return val;
  27438. };
  27439. Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
  27440. offset = offset >>> 0;
  27441. if (!noAssert) checkOffset(offset, 1, this.length);
  27442. if (!(this[offset] & 0x80)) return this[offset];
  27443. return (0xff - this[offset] + 1) * -1;
  27444. };
  27445. Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
  27446. offset = offset >>> 0;
  27447. if (!noAssert) checkOffset(offset, 2, this.length);
  27448. var val = this[offset] | this[offset + 1] << 8;
  27449. return val & 0x8000 ? val | 0xFFFF0000 : val;
  27450. };
  27451. Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
  27452. offset = offset >>> 0;
  27453. if (!noAssert) checkOffset(offset, 2, this.length);
  27454. var val = this[offset + 1] | this[offset] << 8;
  27455. return val & 0x8000 ? val | 0xFFFF0000 : val;
  27456. };
  27457. Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
  27458. offset = offset >>> 0;
  27459. if (!noAssert) checkOffset(offset, 4, this.length);
  27460. return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
  27461. };
  27462. Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
  27463. offset = offset >>> 0;
  27464. if (!noAssert) checkOffset(offset, 4, this.length);
  27465. return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
  27466. };
  27467. Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
  27468. offset = offset >>> 0;
  27469. if (!noAssert) checkOffset(offset, 4, this.length);
  27470. return ieee754.read(this, offset, true, 23, 4);
  27471. };
  27472. Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
  27473. offset = offset >>> 0;
  27474. if (!noAssert) checkOffset(offset, 4, this.length);
  27475. return ieee754.read(this, offset, false, 23, 4);
  27476. };
  27477. Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
  27478. offset = offset >>> 0;
  27479. if (!noAssert) checkOffset(offset, 8, this.length);
  27480. return ieee754.read(this, offset, true, 52, 8);
  27481. };
  27482. Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
  27483. offset = offset >>> 0;
  27484. if (!noAssert) checkOffset(offset, 8, this.length);
  27485. return ieee754.read(this, offset, false, 52, 8);
  27486. };
  27487. function checkInt(buf, value, offset, ext, max, min) {
  27488. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
  27489. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
  27490. if (offset + ext > buf.length) throw new RangeError('Index out of range');
  27491. }
  27492. Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
  27493. value = +value;
  27494. offset = offset >>> 0;
  27495. byteLength = byteLength >>> 0;
  27496. if (!noAssert) {
  27497. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  27498. checkInt(this, value, offset, byteLength, maxBytes, 0);
  27499. }
  27500. var mul = 1;
  27501. var i = 0;
  27502. this[offset] = value & 0xFF;
  27503. while (++i < byteLength && (mul *= 0x100)) {
  27504. this[offset + i] = value / mul & 0xFF;
  27505. }
  27506. return offset + byteLength;
  27507. };
  27508. Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
  27509. value = +value;
  27510. offset = offset >>> 0;
  27511. byteLength = byteLength >>> 0;
  27512. if (!noAssert) {
  27513. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  27514. checkInt(this, value, offset, byteLength, maxBytes, 0);
  27515. }
  27516. var i = byteLength - 1;
  27517. var mul = 1;
  27518. this[offset + i] = value & 0xFF;
  27519. while (--i >= 0 && (mul *= 0x100)) {
  27520. this[offset + i] = value / mul & 0xFF;
  27521. }
  27522. return offset + byteLength;
  27523. };
  27524. Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
  27525. value = +value;
  27526. offset = offset >>> 0;
  27527. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  27528. this[offset] = value & 0xff;
  27529. return offset + 1;
  27530. };
  27531. Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
  27532. value = +value;
  27533. offset = offset >>> 0;
  27534. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  27535. this[offset] = value & 0xff;
  27536. this[offset + 1] = value >>> 8;
  27537. return offset + 2;
  27538. };
  27539. Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
  27540. value = +value;
  27541. offset = offset >>> 0;
  27542. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  27543. this[offset] = value >>> 8;
  27544. this[offset + 1] = value & 0xff;
  27545. return offset + 2;
  27546. };
  27547. Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
  27548. value = +value;
  27549. offset = offset >>> 0;
  27550. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  27551. this[offset + 3] = value >>> 24;
  27552. this[offset + 2] = value >>> 16;
  27553. this[offset + 1] = value >>> 8;
  27554. this[offset] = value & 0xff;
  27555. return offset + 4;
  27556. };
  27557. Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
  27558. value = +value;
  27559. offset = offset >>> 0;
  27560. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  27561. this[offset] = value >>> 24;
  27562. this[offset + 1] = value >>> 16;
  27563. this[offset + 2] = value >>> 8;
  27564. this[offset + 3] = value & 0xff;
  27565. return offset + 4;
  27566. };
  27567. Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
  27568. value = +value;
  27569. offset = offset >>> 0;
  27570. if (!noAssert) {
  27571. var limit = Math.pow(2, 8 * byteLength - 1);
  27572. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  27573. }
  27574. var i = 0;
  27575. var mul = 1;
  27576. var sub = 0;
  27577. this[offset] = value & 0xFF;
  27578. while (++i < byteLength && (mul *= 0x100)) {
  27579. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  27580. sub = 1;
  27581. }
  27582. this[offset + i] = (value / mul >> 0) - sub & 0xFF;
  27583. }
  27584. return offset + byteLength;
  27585. };
  27586. Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
  27587. value = +value;
  27588. offset = offset >>> 0;
  27589. if (!noAssert) {
  27590. var limit = Math.pow(2, 8 * byteLength - 1);
  27591. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  27592. }
  27593. var i = byteLength - 1;
  27594. var mul = 1;
  27595. var sub = 0;
  27596. this[offset + i] = value & 0xFF;
  27597. while (--i >= 0 && (mul *= 0x100)) {
  27598. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  27599. sub = 1;
  27600. }
  27601. this[offset + i] = (value / mul >> 0) - sub & 0xFF;
  27602. }
  27603. return offset + byteLength;
  27604. };
  27605. Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
  27606. value = +value;
  27607. offset = offset >>> 0;
  27608. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  27609. if (value < 0) value = 0xff + value + 1;
  27610. this[offset] = value & 0xff;
  27611. return offset + 1;
  27612. };
  27613. Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
  27614. value = +value;
  27615. offset = offset >>> 0;
  27616. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  27617. this[offset] = value & 0xff;
  27618. this[offset + 1] = value >>> 8;
  27619. return offset + 2;
  27620. };
  27621. Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
  27622. value = +value;
  27623. offset = offset >>> 0;
  27624. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  27625. this[offset] = value >>> 8;
  27626. this[offset + 1] = value & 0xff;
  27627. return offset + 2;
  27628. };
  27629. Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
  27630. value = +value;
  27631. offset = offset >>> 0;
  27632. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  27633. this[offset] = value & 0xff;
  27634. this[offset + 1] = value >>> 8;
  27635. this[offset + 2] = value >>> 16;
  27636. this[offset + 3] = value >>> 24;
  27637. return offset + 4;
  27638. };
  27639. Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
  27640. value = +value;
  27641. offset = offset >>> 0;
  27642. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  27643. if (value < 0) value = 0xffffffff + value + 1;
  27644. this[offset] = value >>> 24;
  27645. this[offset + 1] = value >>> 16;
  27646. this[offset + 2] = value >>> 8;
  27647. this[offset + 3] = value & 0xff;
  27648. return offset + 4;
  27649. };
  27650. function checkIEEE754(buf, value, offset, ext, max, min) {
  27651. if (offset + ext > buf.length) throw new RangeError('Index out of range');
  27652. if (offset < 0) throw new RangeError('Index out of range');
  27653. }
  27654. function writeFloat(buf, value, offset, littleEndian, noAssert) {
  27655. value = +value;
  27656. offset = offset >>> 0;
  27657. if (!noAssert) {
  27658. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38);
  27659. }
  27660. ieee754.write(buf, value, offset, littleEndian, 23, 4);
  27661. return offset + 4;
  27662. }
  27663. Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
  27664. return writeFloat(this, value, offset, true, noAssert);
  27665. };
  27666. Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
  27667. return writeFloat(this, value, offset, false, noAssert);
  27668. };
  27669. function writeDouble(buf, value, offset, littleEndian, noAssert) {
  27670. value = +value;
  27671. offset = offset >>> 0;
  27672. if (!noAssert) {
  27673. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308);
  27674. }
  27675. ieee754.write(buf, value, offset, littleEndian, 52, 8);
  27676. return offset + 8;
  27677. }
  27678. Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
  27679. return writeDouble(this, value, offset, true, noAssert);
  27680. };
  27681. Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
  27682. return writeDouble(this, value, offset, false, noAssert);
  27683. };
  27684. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  27685. Buffer.prototype.copy = function copy(target, targetStart, start, end) {
  27686. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer');
  27687. if (!start) start = 0;
  27688. if (!end && end !== 0) end = this.length;
  27689. if (targetStart >= target.length) targetStart = target.length;
  27690. if (!targetStart) targetStart = 0;
  27691. if (end > 0 && end < start) end = start;
  27692. // Copy 0 bytes; we're done
  27693. if (end === start) return 0;
  27694. if (target.length === 0 || this.length === 0) return 0;
  27695. // Fatal error conditions
  27696. if (targetStart < 0) {
  27697. throw new RangeError('targetStart out of bounds');
  27698. }
  27699. if (start < 0 || start >= this.length) throw new RangeError('Index out of range');
  27700. if (end < 0) throw new RangeError('sourceEnd out of bounds');
  27701. // Are we oob?
  27702. if (end > this.length) end = this.length;
  27703. if (target.length - targetStart < end - start) {
  27704. end = target.length - targetStart + start;
  27705. }
  27706. var len = end - start;
  27707. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  27708. // Use built-in when available, missing from IE11
  27709. this.copyWithin(targetStart, start, end);
  27710. } else if (this === target && start < targetStart && targetStart < end) {
  27711. // descending copy from end
  27712. for (var i = len - 1; i >= 0; --i) {
  27713. target[i + targetStart] = this[i + start];
  27714. }
  27715. } else {
  27716. Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
  27717. }
  27718. return len;
  27719. };
  27720. // Usage:
  27721. // buffer.fill(number[, offset[, end]])
  27722. // buffer.fill(buffer[, offset[, end]])
  27723. // buffer.fill(string[, offset[, end]][, encoding])
  27724. Buffer.prototype.fill = function fill(val, start, end, encoding) {
  27725. // Handle string cases:
  27726. if (typeof val === 'string') {
  27727. if (typeof start === 'string') {
  27728. encoding = start;
  27729. start = 0;
  27730. end = this.length;
  27731. } else if (typeof end === 'string') {
  27732. encoding = end;
  27733. end = this.length;
  27734. }
  27735. if (encoding !== undefined && typeof encoding !== 'string') {
  27736. throw new TypeError('encoding must be a string');
  27737. }
  27738. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  27739. throw new TypeError('Unknown encoding: ' + encoding);
  27740. }
  27741. if (val.length === 1) {
  27742. var code = val.charCodeAt(0);
  27743. if (encoding === 'utf8' && code < 128 || encoding === 'latin1') {
  27744. // Fast path: If `val` fits into a single byte, use that numeric value.
  27745. val = code;
  27746. }
  27747. }
  27748. } else if (typeof val === 'number') {
  27749. val = val & 255;
  27750. }
  27751. // Invalid ranges are not set to a default, so can range check early.
  27752. if (start < 0 || this.length < start || this.length < end) {
  27753. throw new RangeError('Out of range index');
  27754. }
  27755. if (end <= start) {
  27756. return this;
  27757. }
  27758. start = start >>> 0;
  27759. end = end === undefined ? this.length : end >>> 0;
  27760. if (!val) val = 0;
  27761. var i;
  27762. if (typeof val === 'number') {
  27763. for (i = start; i < end; ++i) {
  27764. this[i] = val;
  27765. }
  27766. } else {
  27767. var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding);
  27768. var len = bytes.length;
  27769. if (len === 0) {
  27770. throw new TypeError('The value "' + val + '" is invalid for argument "value"');
  27771. }
  27772. for (i = 0; i < end - start; ++i) {
  27773. this[i + start] = bytes[i % len];
  27774. }
  27775. }
  27776. return this;
  27777. };
  27778. // HELPER FUNCTIONS
  27779. // ================
  27780. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
  27781. function base64clean(str) {
  27782. // Node takes equal signs as end of the Base64 encoding
  27783. str = str.split('=')[0];
  27784. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  27785. str = str.trim().replace(INVALID_BASE64_RE, '');
  27786. // Node converts strings with length < 2 to ''
  27787. if (str.length < 2) return '';
  27788. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  27789. while (str.length % 4 !== 0) {
  27790. str = str + '=';
  27791. }
  27792. return str;
  27793. }
  27794. function toHex(n) {
  27795. if (n < 16) return '0' + n.toString(16);
  27796. return n.toString(16);
  27797. }
  27798. function utf8ToBytes(string, units) {
  27799. units = units || Infinity;
  27800. var codePoint;
  27801. var length = string.length;
  27802. var leadSurrogate = null;
  27803. var bytes = [];
  27804. for (var i = 0; i < length; ++i) {
  27805. codePoint = string.charCodeAt(i);
  27806. // is surrogate component
  27807. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  27808. // last char was a lead
  27809. if (!leadSurrogate) {
  27810. // no lead yet
  27811. if (codePoint > 0xDBFF) {
  27812. // unexpected trail
  27813. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  27814. continue;
  27815. } else if (i + 1 === length) {
  27816. // unpaired lead
  27817. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  27818. continue;
  27819. }
  27820. // valid lead
  27821. leadSurrogate = codePoint;
  27822. continue;
  27823. }
  27824. // 2 leads in a row
  27825. if (codePoint < 0xDC00) {
  27826. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  27827. leadSurrogate = codePoint;
  27828. continue;
  27829. }
  27830. // valid surrogate pair
  27831. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  27832. } else if (leadSurrogate) {
  27833. // valid bmp char, but last char was a lead
  27834. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  27835. }
  27836. leadSurrogate = null;
  27837. // encode utf8
  27838. if (codePoint < 0x80) {
  27839. if ((units -= 1) < 0) break;
  27840. bytes.push(codePoint);
  27841. } else if (codePoint < 0x800) {
  27842. if ((units -= 2) < 0) break;
  27843. bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
  27844. } else if (codePoint < 0x10000) {
  27845. if ((units -= 3) < 0) break;
  27846. bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
  27847. } else if (codePoint < 0x110000) {
  27848. if ((units -= 4) < 0) break;
  27849. bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
  27850. } else {
  27851. throw new Error('Invalid code point');
  27852. }
  27853. }
  27854. return bytes;
  27855. }
  27856. function asciiToBytes(str) {
  27857. var byteArray = [];
  27858. for (var i = 0; i < str.length; ++i) {
  27859. // Node's code seems to be doing this and not & 0x7F..
  27860. byteArray.push(str.charCodeAt(i) & 0xFF);
  27861. }
  27862. return byteArray;
  27863. }
  27864. function utf16leToBytes(str, units) {
  27865. var c, hi, lo;
  27866. var byteArray = [];
  27867. for (var i = 0; i < str.length; ++i) {
  27868. if ((units -= 2) < 0) break;
  27869. c = str.charCodeAt(i);
  27870. hi = c >> 8;
  27871. lo = c % 256;
  27872. byteArray.push(lo);
  27873. byteArray.push(hi);
  27874. }
  27875. return byteArray;
  27876. }
  27877. function base64ToBytes(str) {
  27878. return base64.toByteArray(base64clean(str));
  27879. }
  27880. function blitBuffer(src, dst, offset, length) {
  27881. for (var i = 0; i < length; ++i) {
  27882. if (i + offset >= dst.length || i >= src.length) break;
  27883. dst[i + offset] = src[i];
  27884. }
  27885. return i;
  27886. }
  27887. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  27888. // the `instanceof` check but they should be treated as of that type.
  27889. // See: https://github.com/feross/buffer/issues/166
  27890. function isInstance(obj, type) {
  27891. return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
  27892. }
  27893. function numberIsNaN(obj) {
  27894. // For IE11 support
  27895. return obj !== obj; // eslint-disable-line no-self-compare
  27896. }
  27897. }).call(this)}).call(this,require("buffer").Buffer)
  27898. },{"base64-js":185,"buffer":220,"ieee754":278}],221:[function(require,module,exports){
  27899. "use strict";
  27900. var Buffer = require('safe-buffer').Buffer;
  27901. var Transform = require('stream').Transform;
  27902. var StringDecoder = require('string_decoder').StringDecoder;
  27903. var inherits = require('inherits');
  27904. function CipherBase(hashMode) {
  27905. Transform.call(this);
  27906. this.hashMode = typeof hashMode === 'string';
  27907. if (this.hashMode) {
  27908. this[hashMode] = this._finalOrDigest;
  27909. } else {
  27910. this.final = this._finalOrDigest;
  27911. }
  27912. if (this._final) {
  27913. this.__final = this._final;
  27914. this._final = null;
  27915. }
  27916. this._decoder = null;
  27917. this._encoding = null;
  27918. }
  27919. inherits(CipherBase, Transform);
  27920. CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
  27921. if (typeof data === 'string') {
  27922. data = Buffer.from(data, inputEnc);
  27923. }
  27924. var outData = this._update(data);
  27925. if (this.hashMode) return this;
  27926. if (outputEnc) {
  27927. outData = this._toString(outData, outputEnc);
  27928. }
  27929. return outData;
  27930. };
  27931. CipherBase.prototype.setAutoPadding = function () {};
  27932. CipherBase.prototype.getAuthTag = function () {
  27933. throw new Error('trying to get auth tag in unsupported state');
  27934. };
  27935. CipherBase.prototype.setAuthTag = function () {
  27936. throw new Error('trying to set auth tag in unsupported state');
  27937. };
  27938. CipherBase.prototype.setAAD = function () {
  27939. throw new Error('trying to set aad in unsupported state');
  27940. };
  27941. CipherBase.prototype._transform = function (data, _, next) {
  27942. var err;
  27943. try {
  27944. if (this.hashMode) {
  27945. this._update(data);
  27946. } else {
  27947. this.push(this._update(data));
  27948. }
  27949. } catch (e) {
  27950. err = e;
  27951. } finally {
  27952. next(err);
  27953. }
  27954. };
  27955. CipherBase.prototype._flush = function (done) {
  27956. var err;
  27957. try {
  27958. this.push(this.__final());
  27959. } catch (e) {
  27960. err = e;
  27961. }
  27962. done(err);
  27963. };
  27964. CipherBase.prototype._finalOrDigest = function (outputEnc) {
  27965. var outData = this.__final() || Buffer.alloc(0);
  27966. if (outputEnc) {
  27967. outData = this._toString(outData, outputEnc, true);
  27968. }
  27969. return outData;
  27970. };
  27971. CipherBase.prototype._toString = function (value, enc, fin) {
  27972. if (!this._decoder) {
  27973. this._decoder = new StringDecoder(enc);
  27974. this._encoding = enc;
  27975. }
  27976. if (this._encoding !== enc) throw new Error('can\'t switch encodings');
  27977. var out = this._decoder.write(value);
  27978. if (fin) {
  27979. out += this._decoder.end();
  27980. }
  27981. return out;
  27982. };
  27983. module.exports = CipherBase;
  27984. },{"inherits":279,"safe-buffer":332,"stream":343,"string_decoder":218}],222:[function(require,module,exports){
  27985. "use strict";
  27986. // Copyright Joyent, Inc. and other Node contributors.
  27987. //
  27988. // Permission is hereby granted, free of charge, to any person obtaining a
  27989. // copy of this software and associated documentation files (the
  27990. // "Software"), to deal in the Software without restriction, including
  27991. // without limitation the rights to use, copy, modify, merge, publish,
  27992. // distribute, sublicense, and/or sell copies of the Software, and to permit
  27993. // persons to whom the Software is furnished to do so, subject to the
  27994. // following conditions:
  27995. //
  27996. // The above copyright notice and this permission notice shall be included
  27997. // in all copies or substantial portions of the Software.
  27998. //
  27999. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  28000. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28001. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  28002. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  28003. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  28004. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  28005. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  28006. // NOTE: These type checking functions intentionally don't use `instanceof`
  28007. // because it is fragile and can be easily faked with `Object.create()`.
  28008. function isArray(arg) {
  28009. if (Array.isArray) {
  28010. return Array.isArray(arg);
  28011. }
  28012. return objectToString(arg) === '[object Array]';
  28013. }
  28014. exports.isArray = isArray;
  28015. function isBoolean(arg) {
  28016. return typeof arg === 'boolean';
  28017. }
  28018. exports.isBoolean = isBoolean;
  28019. function isNull(arg) {
  28020. return arg === null;
  28021. }
  28022. exports.isNull = isNull;
  28023. function isNullOrUndefined(arg) {
  28024. return arg == null;
  28025. }
  28026. exports.isNullOrUndefined = isNullOrUndefined;
  28027. function isNumber(arg) {
  28028. return typeof arg === 'number';
  28029. }
  28030. exports.isNumber = isNumber;
  28031. function isString(arg) {
  28032. return typeof arg === 'string';
  28033. }
  28034. exports.isString = isString;
  28035. function isSymbol(arg) {
  28036. return typeof arg === 'symbol';
  28037. }
  28038. exports.isSymbol = isSymbol;
  28039. function isUndefined(arg) {
  28040. return arg === void 0;
  28041. }
  28042. exports.isUndefined = isUndefined;
  28043. function isRegExp(re) {
  28044. return objectToString(re) === '[object RegExp]';
  28045. }
  28046. exports.isRegExp = isRegExp;
  28047. function isObject(arg) {
  28048. return typeof arg === 'object' && arg !== null;
  28049. }
  28050. exports.isObject = isObject;
  28051. function isDate(d) {
  28052. return objectToString(d) === '[object Date]';
  28053. }
  28054. exports.isDate = isDate;
  28055. function isError(e) {
  28056. return objectToString(e) === '[object Error]' || e instanceof Error;
  28057. }
  28058. exports.isError = isError;
  28059. function isFunction(arg) {
  28060. return typeof arg === 'function';
  28061. }
  28062. exports.isFunction = isFunction;
  28063. function isPrimitive(arg) {
  28064. return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' ||
  28065. // ES6 symbol
  28066. typeof arg === 'undefined';
  28067. }
  28068. exports.isPrimitive = isPrimitive;
  28069. exports.isBuffer = require('buffer').Buffer.isBuffer;
  28070. function objectToString(o) {
  28071. return Object.prototype.toString.call(o);
  28072. }
  28073. },{"buffer":220}],223:[function(require,module,exports){
  28074. (function (Buffer){(function (){
  28075. "use strict";
  28076. var elliptic = require('elliptic');
  28077. var BN = require('bn.js');
  28078. module.exports = function createECDH(curve) {
  28079. return new ECDH(curve);
  28080. };
  28081. var aliases = {
  28082. secp256k1: {
  28083. name: 'secp256k1',
  28084. byteLength: 32
  28085. },
  28086. secp224r1: {
  28087. name: 'p224',
  28088. byteLength: 28
  28089. },
  28090. prime256v1: {
  28091. name: 'p256',
  28092. byteLength: 32
  28093. },
  28094. prime192v1: {
  28095. name: 'p192',
  28096. byteLength: 24
  28097. },
  28098. ed25519: {
  28099. name: 'ed25519',
  28100. byteLength: 32
  28101. },
  28102. secp384r1: {
  28103. name: 'p384',
  28104. byteLength: 48
  28105. },
  28106. secp521r1: {
  28107. name: 'p521',
  28108. byteLength: 66
  28109. }
  28110. };
  28111. aliases.p224 = aliases.secp224r1;
  28112. aliases.p256 = aliases.secp256r1 = aliases.prime256v1;
  28113. aliases.p192 = aliases.secp192r1 = aliases.prime192v1;
  28114. aliases.p384 = aliases.secp384r1;
  28115. aliases.p521 = aliases.secp521r1;
  28116. function ECDH(curve) {
  28117. this.curveType = aliases[curve];
  28118. if (!this.curveType) {
  28119. this.curveType = {
  28120. name: curve
  28121. };
  28122. }
  28123. this.curve = new elliptic.ec(this.curveType.name); // eslint-disable-line new-cap
  28124. this.keys = void 0;
  28125. }
  28126. ECDH.prototype.generateKeys = function (enc, format) {
  28127. this.keys = this.curve.genKeyPair();
  28128. return this.getPublicKey(enc, format);
  28129. };
  28130. ECDH.prototype.computeSecret = function (other, inenc, enc) {
  28131. inenc = inenc || 'utf8';
  28132. if (!Buffer.isBuffer(other)) {
  28133. other = new Buffer(other, inenc);
  28134. }
  28135. var otherPub = this.curve.keyFromPublic(other).getPublic();
  28136. var out = otherPub.mul(this.keys.getPrivate()).getX();
  28137. return formatReturnValue(out, enc, this.curveType.byteLength);
  28138. };
  28139. ECDH.prototype.getPublicKey = function (enc, format) {
  28140. var key = this.keys.getPublic(format === 'compressed', true);
  28141. if (format === 'hybrid') {
  28142. if (key[key.length - 1] % 2) {
  28143. key[0] = 7;
  28144. } else {
  28145. key[0] = 6;
  28146. }
  28147. }
  28148. return formatReturnValue(key, enc);
  28149. };
  28150. ECDH.prototype.getPrivateKey = function (enc) {
  28151. return formatReturnValue(this.keys.getPrivate(), enc);
  28152. };
  28153. ECDH.prototype.setPublicKey = function (pub, enc) {
  28154. enc = enc || 'utf8';
  28155. if (!Buffer.isBuffer(pub)) {
  28156. pub = new Buffer(pub, enc);
  28157. }
  28158. this.keys._importPublic(pub);
  28159. return this;
  28160. };
  28161. ECDH.prototype.setPrivateKey = function (priv, enc) {
  28162. enc = enc || 'utf8';
  28163. if (!Buffer.isBuffer(priv)) {
  28164. priv = new Buffer(priv, enc);
  28165. }
  28166. var _priv = new BN(priv);
  28167. _priv = _priv.toString(16);
  28168. this.keys = this.curve.genKeyPair();
  28169. this.keys._importPrivate(_priv);
  28170. return this;
  28171. };
  28172. function formatReturnValue(bn, enc, len) {
  28173. if (!Array.isArray(bn)) {
  28174. bn = bn.toArray();
  28175. }
  28176. var buf = new Buffer(bn);
  28177. if (len && buf.length < len) {
  28178. var zeros = new Buffer(len - buf.length);
  28179. zeros.fill(0);
  28180. buf = Buffer.concat([zeros, buf]);
  28181. }
  28182. if (!enc) {
  28183. return buf;
  28184. } else {
  28185. return buf.toString(enc);
  28186. }
  28187. }
  28188. }).call(this)}).call(this,require("buffer").Buffer)
  28189. },{"bn.js":224,"buffer":220,"elliptic":244}],224:[function(require,module,exports){
  28190. arguments[4][184][0].apply(exports,arguments)
  28191. },{"buffer":188,"dup":184}],225:[function(require,module,exports){
  28192. 'use strict';
  28193. var inherits = require('inherits');
  28194. var MD5 = require('md5.js');
  28195. var RIPEMD160 = require('ripemd160');
  28196. var sha = require('sha.js');
  28197. var Base = require('cipher-base');
  28198. function Hash(hash) {
  28199. Base.call(this, 'digest');
  28200. this._hash = hash;
  28201. }
  28202. inherits(Hash, Base);
  28203. Hash.prototype._update = function (data) {
  28204. this._hash.update(data);
  28205. };
  28206. Hash.prototype._final = function () {
  28207. return this._hash.digest();
  28208. };
  28209. module.exports = function createHash(alg) {
  28210. alg = alg.toLowerCase();
  28211. if (alg === 'md5') return new MD5();
  28212. if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160();
  28213. return new Hash(sha(alg));
  28214. };
  28215. },{"cipher-base":221,"inherits":279,"md5.js":289,"ripemd160":331,"sha.js":336}],226:[function(require,module,exports){
  28216. "use strict";
  28217. var MD5 = require('md5.js');
  28218. module.exports = function (buffer) {
  28219. return new MD5().update(buffer).digest();
  28220. };
  28221. },{"md5.js":289}],227:[function(require,module,exports){
  28222. 'use strict';
  28223. var inherits = require('inherits');
  28224. var Legacy = require('./legacy');
  28225. var Base = require('cipher-base');
  28226. var Buffer = require('safe-buffer').Buffer;
  28227. var md5 = require('create-hash/md5');
  28228. var RIPEMD160 = require('ripemd160');
  28229. var sha = require('sha.js');
  28230. var ZEROS = Buffer.alloc(128);
  28231. function Hmac(alg, key) {
  28232. Base.call(this, 'digest');
  28233. if (typeof key === 'string') {
  28234. key = Buffer.from(key);
  28235. }
  28236. var blocksize = alg === 'sha512' || alg === 'sha384' ? 128 : 64;
  28237. this._alg = alg;
  28238. this._key = key;
  28239. if (key.length > blocksize) {
  28240. var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg);
  28241. key = hash.update(key).digest();
  28242. } else if (key.length < blocksize) {
  28243. key = Buffer.concat([key, ZEROS], blocksize);
  28244. }
  28245. var ipad = this._ipad = Buffer.allocUnsafe(blocksize);
  28246. var opad = this._opad = Buffer.allocUnsafe(blocksize);
  28247. for (var i = 0; i < blocksize; i++) {
  28248. ipad[i] = key[i] ^ 0x36;
  28249. opad[i] = key[i] ^ 0x5C;
  28250. }
  28251. this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg);
  28252. this._hash.update(ipad);
  28253. }
  28254. inherits(Hmac, Base);
  28255. Hmac.prototype._update = function (data) {
  28256. this._hash.update(data);
  28257. };
  28258. Hmac.prototype._final = function () {
  28259. var h = this._hash.digest();
  28260. var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg);
  28261. return hash.update(this._opad).update(h).digest();
  28262. };
  28263. module.exports = function createHmac(alg, key) {
  28264. alg = alg.toLowerCase();
  28265. if (alg === 'rmd160' || alg === 'ripemd160') {
  28266. return new Hmac('rmd160', key);
  28267. }
  28268. if (alg === 'md5') {
  28269. return new Legacy(md5, key);
  28270. }
  28271. return new Hmac(alg, key);
  28272. };
  28273. },{"./legacy":228,"cipher-base":221,"create-hash/md5":226,"inherits":279,"ripemd160":331,"safe-buffer":332,"sha.js":336}],228:[function(require,module,exports){
  28274. 'use strict';
  28275. var inherits = require('inherits');
  28276. var Buffer = require('safe-buffer').Buffer;
  28277. var Base = require('cipher-base');
  28278. var ZEROS = Buffer.alloc(128);
  28279. var blocksize = 64;
  28280. function Hmac(alg, key) {
  28281. Base.call(this, 'digest');
  28282. if (typeof key === 'string') {
  28283. key = Buffer.from(key);
  28284. }
  28285. this._alg = alg;
  28286. this._key = key;
  28287. if (key.length > blocksize) {
  28288. key = alg(key);
  28289. } else if (key.length < blocksize) {
  28290. key = Buffer.concat([key, ZEROS], blocksize);
  28291. }
  28292. var ipad = this._ipad = Buffer.allocUnsafe(blocksize);
  28293. var opad = this._opad = Buffer.allocUnsafe(blocksize);
  28294. for (var i = 0; i < blocksize; i++) {
  28295. ipad[i] = key[i] ^ 0x36;
  28296. opad[i] = key[i] ^ 0x5C;
  28297. }
  28298. this._hash = [ipad];
  28299. }
  28300. inherits(Hmac, Base);
  28301. Hmac.prototype._update = function (data) {
  28302. this._hash.push(data);
  28303. };
  28304. Hmac.prototype._final = function () {
  28305. var h = this._alg(Buffer.concat(this._hash));
  28306. return this._alg(Buffer.concat([this._opad, h]));
  28307. };
  28308. module.exports = Hmac;
  28309. },{"cipher-base":221,"inherits":279,"safe-buffer":332}],229:[function(require,module,exports){
  28310. 'use strict';
  28311. exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes');
  28312. exports.createHash = exports.Hash = require('create-hash');
  28313. exports.createHmac = exports.Hmac = require('create-hmac');
  28314. var algos = require('browserify-sign/algos');
  28315. var algoKeys = Object.keys(algos);
  28316. var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys);
  28317. exports.getHashes = function () {
  28318. return hashes;
  28319. };
  28320. var p = require('pbkdf2');
  28321. exports.pbkdf2 = p.pbkdf2;
  28322. exports.pbkdf2Sync = p.pbkdf2Sync;
  28323. var aes = require('browserify-cipher');
  28324. exports.Cipher = aes.Cipher;
  28325. exports.createCipher = aes.createCipher;
  28326. exports.Cipheriv = aes.Cipheriv;
  28327. exports.createCipheriv = aes.createCipheriv;
  28328. exports.Decipher = aes.Decipher;
  28329. exports.createDecipher = aes.createDecipher;
  28330. exports.Decipheriv = aes.Decipheriv;
  28331. exports.createDecipheriv = aes.createDecipheriv;
  28332. exports.getCiphers = aes.getCiphers;
  28333. exports.listCiphers = aes.listCiphers;
  28334. var dh = require('diffie-hellman');
  28335. exports.DiffieHellmanGroup = dh.DiffieHellmanGroup;
  28336. exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup;
  28337. exports.getDiffieHellman = dh.getDiffieHellman;
  28338. exports.createDiffieHellman = dh.createDiffieHellman;
  28339. exports.DiffieHellman = dh.DiffieHellman;
  28340. var sign = require('browserify-sign');
  28341. exports.createSign = sign.createSign;
  28342. exports.Sign = sign.Sign;
  28343. exports.createVerify = sign.createVerify;
  28344. exports.Verify = sign.Verify;
  28345. exports.createECDH = require('create-ecdh');
  28346. var publicEncrypt = require('public-encrypt');
  28347. exports.publicEncrypt = publicEncrypt.publicEncrypt;
  28348. exports.privateEncrypt = publicEncrypt.privateEncrypt;
  28349. exports.publicDecrypt = publicEncrypt.publicDecrypt;
  28350. exports.privateDecrypt = publicEncrypt.privateDecrypt;
  28351. // the least I can do is make error messages for the rest of the node.js/crypto api.
  28352. // ;[
  28353. // 'createCredentials'
  28354. // ].forEach(function (name) {
  28355. // exports[name] = function () {
  28356. // throw new Error([
  28357. // 'sorry, ' + name + ' is not implemented yet',
  28358. // 'we accept pull requests',
  28359. // 'https://github.com/crypto-browserify/crypto-browserify'
  28360. // ].join('\n'))
  28361. // }
  28362. // })
  28363. var rf = require('randomfill');
  28364. exports.randomFill = rf.randomFill;
  28365. exports.randomFillSync = rf.randomFillSync;
  28366. exports.createCredentials = function () {
  28367. throw new Error(['sorry, createCredentials is not implemented yet', 'we accept pull requests', 'https://github.com/crypto-browserify/crypto-browserify'].join('\n'));
  28368. };
  28369. exports.constants = {
  28370. 'DH_CHECK_P_NOT_SAFE_PRIME': 2,
  28371. 'DH_CHECK_P_NOT_PRIME': 1,
  28372. 'DH_UNABLE_TO_CHECK_GENERATOR': 4,
  28373. 'DH_NOT_SUITABLE_GENERATOR': 8,
  28374. 'NPN_ENABLED': 1,
  28375. 'ALPN_ENABLED': 1,
  28376. 'RSA_PKCS1_PADDING': 1,
  28377. 'RSA_SSLV23_PADDING': 2,
  28378. 'RSA_NO_PADDING': 3,
  28379. 'RSA_PKCS1_OAEP_PADDING': 4,
  28380. 'RSA_X931_PADDING': 5,
  28381. 'RSA_PKCS1_PSS_PADDING': 6,
  28382. 'POINT_CONVERSION_COMPRESSED': 2,
  28383. 'POINT_CONVERSION_UNCOMPRESSED': 4,
  28384. 'POINT_CONVERSION_HYBRID': 6
  28385. };
  28386. },{"browserify-cipher":206,"browserify-sign":213,"browserify-sign/algos":210,"create-ecdh":223,"create-hash":225,"create-hmac":227,"diffie-hellman":239,"pbkdf2":299,"public-encrypt":307,"randombytes":314,"randomfill":315}],230:[function(require,module,exports){
  28387. "use strict";
  28388. !function (t, e) {
  28389. "object" == typeof exports && "undefined" != typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = "undefined" != typeof globalThis ? globalThis : t || self).dayjs = e();
  28390. }(void 0, function () {
  28391. "use strict";
  28392. var t = 1e3,
  28393. e = 6e4,
  28394. n = 36e5,
  28395. r = "millisecond",
  28396. i = "second",
  28397. s = "minute",
  28398. u = "hour",
  28399. a = "day",
  28400. o = "week",
  28401. c = "month",
  28402. f = "quarter",
  28403. h = "year",
  28404. d = "date",
  28405. l = "Invalid Date",
  28406. $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,
  28407. y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,
  28408. M = {
  28409. name: "en",
  28410. weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  28411. months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  28412. ordinal: function (t) {
  28413. var e = ["th", "st", "nd", "rd"],
  28414. n = t % 100;
  28415. return "[" + t + (e[(n - 20) % 10] || e[n] || e[0]) + "]";
  28416. }
  28417. },
  28418. m = function (t, e, n) {
  28419. var r = String(t);
  28420. return !r || r.length >= e ? t : "" + Array(e + 1 - r.length).join(n) + t;
  28421. },
  28422. v = {
  28423. s: m,
  28424. z: function (t) {
  28425. var e = -t.utcOffset(),
  28426. n = Math.abs(e),
  28427. r = Math.floor(n / 60),
  28428. i = n % 60;
  28429. return (e <= 0 ? "+" : "-") + m(r, 2, "0") + ":" + m(i, 2, "0");
  28430. },
  28431. m: function t(e, n) {
  28432. if (e.date() < n.date()) return -t(n, e);
  28433. var r = 12 * (n.year() - e.year()) + (n.month() - e.month()),
  28434. i = e.clone().add(r, c),
  28435. s = n - i < 0,
  28436. u = e.clone().add(r + (s ? -1 : 1), c);
  28437. return +(-(r + (n - i) / (s ? i - u : u - i)) || 0);
  28438. },
  28439. a: function (t) {
  28440. return t < 0 ? Math.ceil(t) || 0 : Math.floor(t);
  28441. },
  28442. p: function (t) {
  28443. return {
  28444. M: c,
  28445. y: h,
  28446. w: o,
  28447. d: a,
  28448. D: d,
  28449. h: u,
  28450. m: s,
  28451. s: i,
  28452. ms: r,
  28453. Q: f
  28454. }[t] || String(t || "").toLowerCase().replace(/s$/, "");
  28455. },
  28456. u: function (t) {
  28457. return void 0 === t;
  28458. }
  28459. },
  28460. g = "en",
  28461. D = {};
  28462. D[g] = M;
  28463. var p = "$isDayjsObject",
  28464. S = function (t) {
  28465. return t instanceof _ || !(!t || !t[p]);
  28466. },
  28467. w = function t(e, n, r) {
  28468. var i;
  28469. if (!e) return g;
  28470. if ("string" == typeof e) {
  28471. var s = e.toLowerCase();
  28472. D[s] && (i = s), n && (D[s] = n, i = s);
  28473. var u = e.split("-");
  28474. if (!i && u.length > 1) return t(u[0]);
  28475. } else {
  28476. var a = e.name;
  28477. D[a] = e, i = a;
  28478. }
  28479. return !r && i && (g = i), i || !r && g;
  28480. },
  28481. O = function (t, e) {
  28482. if (S(t)) return t.clone();
  28483. var n = "object" == typeof e ? e : {};
  28484. return n.date = t, n.args = arguments, new _(n);
  28485. },
  28486. b = v;
  28487. b.l = w, b.i = S, b.w = function (t, e) {
  28488. return O(t, {
  28489. locale: e.$L,
  28490. utc: e.$u,
  28491. x: e.$x,
  28492. $offset: e.$offset
  28493. });
  28494. };
  28495. var _ = function () {
  28496. function M(t) {
  28497. this.$L = w(t.locale, null, !0), this.parse(t), this.$x = this.$x || t.x || {}, this[p] = !0;
  28498. }
  28499. var m = M.prototype;
  28500. return m.parse = function (t) {
  28501. this.$d = function (t) {
  28502. var e = t.date,
  28503. n = t.utc;
  28504. if (null === e) return new Date(NaN);
  28505. if (b.u(e)) return new Date();
  28506. if (e instanceof Date) return new Date(e);
  28507. if ("string" == typeof e && !/Z$/i.test(e)) {
  28508. var r = e.match($);
  28509. if (r) {
  28510. var i = r[2] - 1 || 0,
  28511. s = (r[7] || "0").substring(0, 3);
  28512. return n ? new Date(Date.UTC(r[1], i, r[3] || 1, r[4] || 0, r[5] || 0, r[6] || 0, s)) : new Date(r[1], i, r[3] || 1, r[4] || 0, r[5] || 0, r[6] || 0, s);
  28513. }
  28514. }
  28515. return new Date(e);
  28516. }(t), this.init();
  28517. }, m.init = function () {
  28518. var t = this.$d;
  28519. this.$y = t.getFullYear(), this.$M = t.getMonth(), this.$D = t.getDate(), this.$W = t.getDay(), this.$H = t.getHours(), this.$m = t.getMinutes(), this.$s = t.getSeconds(), this.$ms = t.getMilliseconds();
  28520. }, m.$utils = function () {
  28521. return b;
  28522. }, m.isValid = function () {
  28523. return !(this.$d.toString() === l);
  28524. }, m.isSame = function (t, e) {
  28525. var n = O(t);
  28526. return this.startOf(e) <= n && n <= this.endOf(e);
  28527. }, m.isAfter = function (t, e) {
  28528. return O(t) < this.startOf(e);
  28529. }, m.isBefore = function (t, e) {
  28530. return this.endOf(e) < O(t);
  28531. }, m.$g = function (t, e, n) {
  28532. return b.u(t) ? this[e] : this.set(n, t);
  28533. }, m.unix = function () {
  28534. return Math.floor(this.valueOf() / 1e3);
  28535. }, m.valueOf = function () {
  28536. return this.$d.getTime();
  28537. }, m.startOf = function (t, e) {
  28538. var n = this,
  28539. r = !!b.u(e) || e,
  28540. f = b.p(t),
  28541. l = function (t, e) {
  28542. var i = b.w(n.$u ? Date.UTC(n.$y, e, t) : new Date(n.$y, e, t), n);
  28543. return r ? i : i.endOf(a);
  28544. },
  28545. $ = function (t, e) {
  28546. return b.w(n.toDate()[t].apply(n.toDate("s"), (r ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e)), n);
  28547. },
  28548. y = this.$W,
  28549. M = this.$M,
  28550. m = this.$D,
  28551. v = "set" + (this.$u ? "UTC" : "");
  28552. switch (f) {
  28553. case h:
  28554. return r ? l(1, 0) : l(31, 11);
  28555. case c:
  28556. return r ? l(1, M) : l(0, M + 1);
  28557. case o:
  28558. var g = this.$locale().weekStart || 0,
  28559. D = (y < g ? y + 7 : y) - g;
  28560. return l(r ? m - D : m + (6 - D), M);
  28561. case a:
  28562. case d:
  28563. return $(v + "Hours", 0);
  28564. case u:
  28565. return $(v + "Minutes", 1);
  28566. case s:
  28567. return $(v + "Seconds", 2);
  28568. case i:
  28569. return $(v + "Milliseconds", 3);
  28570. default:
  28571. return this.clone();
  28572. }
  28573. }, m.endOf = function (t) {
  28574. return this.startOf(t, !1);
  28575. }, m.$set = function (t, e) {
  28576. var n,
  28577. o = b.p(t),
  28578. f = "set" + (this.$u ? "UTC" : ""),
  28579. l = (n = {}, n[a] = f + "Date", n[d] = f + "Date", n[c] = f + "Month", n[h] = f + "FullYear", n[u] = f + "Hours", n[s] = f + "Minutes", n[i] = f + "Seconds", n[r] = f + "Milliseconds", n)[o],
  28580. $ = o === a ? this.$D + (e - this.$W) : e;
  28581. if (o === c || o === h) {
  28582. var y = this.clone().set(d, 1);
  28583. y.$d[l]($), y.init(), this.$d = y.set(d, Math.min(this.$D, y.daysInMonth())).$d;
  28584. } else l && this.$d[l]($);
  28585. return this.init(), this;
  28586. }, m.set = function (t, e) {
  28587. return this.clone().$set(t, e);
  28588. }, m.get = function (t) {
  28589. return this[b.p(t)]();
  28590. }, m.add = function (r, f) {
  28591. var d,
  28592. l = this;
  28593. r = Number(r);
  28594. var $ = b.p(f),
  28595. y = function (t) {
  28596. var e = O(l);
  28597. return b.w(e.date(e.date() + Math.round(t * r)), l);
  28598. };
  28599. if ($ === c) return this.set(c, this.$M + r);
  28600. if ($ === h) return this.set(h, this.$y + r);
  28601. if ($ === a) return y(1);
  28602. if ($ === o) return y(7);
  28603. var M = (d = {}, d[s] = e, d[u] = n, d[i] = t, d)[$] || 1,
  28604. m = this.$d.getTime() + r * M;
  28605. return b.w(m, this);
  28606. }, m.subtract = function (t, e) {
  28607. return this.add(-1 * t, e);
  28608. }, m.format = function (t) {
  28609. var e = this,
  28610. n = this.$locale();
  28611. if (!this.isValid()) return n.invalidDate || l;
  28612. var r = t || "YYYY-MM-DDTHH:mm:ssZ",
  28613. i = b.z(this),
  28614. s = this.$H,
  28615. u = this.$m,
  28616. a = this.$M,
  28617. o = n.weekdays,
  28618. c = n.months,
  28619. f = n.meridiem,
  28620. h = function (t, n, i, s) {
  28621. return t && (t[n] || t(e, r)) || i[n].slice(0, s);
  28622. },
  28623. d = function (t) {
  28624. return b.s(s % 12 || 12, t, "0");
  28625. },
  28626. $ = f || function (t, e, n) {
  28627. var r = t < 12 ? "AM" : "PM";
  28628. return n ? r.toLowerCase() : r;
  28629. };
  28630. return r.replace(y, function (t, r) {
  28631. return r || function (t) {
  28632. switch (t) {
  28633. case "YY":
  28634. return String(e.$y).slice(-2);
  28635. case "YYYY":
  28636. return b.s(e.$y, 4, "0");
  28637. case "M":
  28638. return a + 1;
  28639. case "MM":
  28640. return b.s(a + 1, 2, "0");
  28641. case "MMM":
  28642. return h(n.monthsShort, a, c, 3);
  28643. case "MMMM":
  28644. return h(c, a);
  28645. case "D":
  28646. return e.$D;
  28647. case "DD":
  28648. return b.s(e.$D, 2, "0");
  28649. case "d":
  28650. return String(e.$W);
  28651. case "dd":
  28652. return h(n.weekdaysMin, e.$W, o, 2);
  28653. case "ddd":
  28654. return h(n.weekdaysShort, e.$W, o, 3);
  28655. case "dddd":
  28656. return o[e.$W];
  28657. case "H":
  28658. return String(s);
  28659. case "HH":
  28660. return b.s(s, 2, "0");
  28661. case "h":
  28662. return d(1);
  28663. case "hh":
  28664. return d(2);
  28665. case "a":
  28666. return $(s, u, !0);
  28667. case "A":
  28668. return $(s, u, !1);
  28669. case "m":
  28670. return String(u);
  28671. case "mm":
  28672. return b.s(u, 2, "0");
  28673. case "s":
  28674. return String(e.$s);
  28675. case "ss":
  28676. return b.s(e.$s, 2, "0");
  28677. case "SSS":
  28678. return b.s(e.$ms, 3, "0");
  28679. case "Z":
  28680. return i;
  28681. }
  28682. return null;
  28683. }(t) || i.replace(":", "");
  28684. });
  28685. }, m.utcOffset = function () {
  28686. return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
  28687. }, m.diff = function (r, d, l) {
  28688. var $,
  28689. y = this,
  28690. M = b.p(d),
  28691. m = O(r),
  28692. v = (m.utcOffset() - this.utcOffset()) * e,
  28693. g = this - m,
  28694. D = function () {
  28695. return b.m(y, m);
  28696. };
  28697. switch (M) {
  28698. case h:
  28699. $ = D() / 12;
  28700. break;
  28701. case c:
  28702. $ = D();
  28703. break;
  28704. case f:
  28705. $ = D() / 3;
  28706. break;
  28707. case o:
  28708. $ = (g - v) / 6048e5;
  28709. break;
  28710. case a:
  28711. $ = (g - v) / 864e5;
  28712. break;
  28713. case u:
  28714. $ = g / n;
  28715. break;
  28716. case s:
  28717. $ = g / e;
  28718. break;
  28719. case i:
  28720. $ = g / t;
  28721. break;
  28722. default:
  28723. $ = g;
  28724. }
  28725. return l ? $ : b.a($);
  28726. }, m.daysInMonth = function () {
  28727. return this.endOf(c).$D;
  28728. }, m.$locale = function () {
  28729. return D[this.$L];
  28730. }, m.locale = function (t, e) {
  28731. if (!t) return this.$L;
  28732. var n = this.clone(),
  28733. r = w(t, e, !0);
  28734. return r && (n.$L = r), n;
  28735. }, m.clone = function () {
  28736. return b.w(this.$d, this);
  28737. }, m.toDate = function () {
  28738. return new Date(this.valueOf());
  28739. }, m.toJSON = function () {
  28740. return this.isValid() ? this.toISOString() : null;
  28741. }, m.toISOString = function () {
  28742. return this.$d.toISOString();
  28743. }, m.toString = function () {
  28744. return this.$d.toUTCString();
  28745. }, M;
  28746. }(),
  28747. k = _.prototype;
  28748. return O.prototype = k, [["$ms", r], ["$s", i], ["$m", s], ["$H", u], ["$W", a], ["$M", c], ["$y", h], ["$D", d]].forEach(function (t) {
  28749. k[t[1]] = function (e) {
  28750. return this.$g(e, t[0], t[1]);
  28751. };
  28752. }), O.extend = function (t, e) {
  28753. return t.$i || (t(e, _, O), t.$i = !0), O;
  28754. }, O.locale = w, O.isDayjs = S, O.unix = function (t) {
  28755. return O(1e3 * t);
  28756. }, O.en = D[g], O.Ls = D, O.p = {}, O;
  28757. });
  28758. },{}],231:[function(require,module,exports){
  28759. "use strict";
  28760. !function (e, t) {
  28761. "object" == typeof exports && "undefined" != typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define(t) : (e = "undefined" != typeof globalThis ? globalThis : e || self).dayjs_plugin_customParseFormat = t();
  28762. }(void 0, function () {
  28763. "use strict";
  28764. var e = {
  28765. LTS: "h:mm:ss A",
  28766. LT: "h:mm A",
  28767. L: "MM/DD/YYYY",
  28768. LL: "MMMM D, YYYY",
  28769. LLL: "MMMM D, YYYY h:mm A",
  28770. LLLL: "dddd, MMMM D, YYYY h:mm A"
  28771. },
  28772. t = /(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|YYYY|YY?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,
  28773. n = /\d\d/,
  28774. r = /\d\d?/,
  28775. i = /\d*[^-_:/,()\s\d]+/,
  28776. o = {},
  28777. s = function (e) {
  28778. return (e = +e) + (e > 68 ? 1900 : 2e3);
  28779. };
  28780. var a = function (e) {
  28781. return function (t) {
  28782. this[e] = +t;
  28783. };
  28784. },
  28785. f = [/[+-]\d\d:?(\d\d)?|Z/, function (e) {
  28786. (this.zone || (this.zone = {})).offset = function (e) {
  28787. if (!e) return 0;
  28788. if ("Z" === e) return 0;
  28789. var t = e.match(/([+-]|\d\d)/g),
  28790. n = 60 * t[1] + (+t[2] || 0);
  28791. return 0 === n ? 0 : "+" === t[0] ? -n : n;
  28792. }(e);
  28793. }],
  28794. h = function (e) {
  28795. var t = o[e];
  28796. return t && (t.indexOf ? t : t.s.concat(t.f));
  28797. },
  28798. u = function (e, t) {
  28799. var n,
  28800. r = o.meridiem;
  28801. if (r) {
  28802. for (var i = 1; i <= 24; i += 1) if (e.indexOf(r(i, 0, t)) > -1) {
  28803. n = i > 12;
  28804. break;
  28805. }
  28806. } else n = e === (t ? "pm" : "PM");
  28807. return n;
  28808. },
  28809. d = {
  28810. A: [i, function (e) {
  28811. this.afternoon = u(e, !1);
  28812. }],
  28813. a: [i, function (e) {
  28814. this.afternoon = u(e, !0);
  28815. }],
  28816. S: [/\d/, function (e) {
  28817. this.milliseconds = 100 * +e;
  28818. }],
  28819. SS: [n, function (e) {
  28820. this.milliseconds = 10 * +e;
  28821. }],
  28822. SSS: [/\d{3}/, function (e) {
  28823. this.milliseconds = +e;
  28824. }],
  28825. s: [r, a("seconds")],
  28826. ss: [r, a("seconds")],
  28827. m: [r, a("minutes")],
  28828. mm: [r, a("minutes")],
  28829. H: [r, a("hours")],
  28830. h: [r, a("hours")],
  28831. HH: [r, a("hours")],
  28832. hh: [r, a("hours")],
  28833. D: [r, a("day")],
  28834. DD: [n, a("day")],
  28835. Do: [i, function (e) {
  28836. var t = o.ordinal,
  28837. n = e.match(/\d+/);
  28838. if (this.day = n[0], t) for (var r = 1; r <= 31; r += 1) t(r).replace(/\[|\]/g, "") === e && (this.day = r);
  28839. }],
  28840. M: [r, a("month")],
  28841. MM: [n, a("month")],
  28842. MMM: [i, function (e) {
  28843. var t = h("months"),
  28844. n = (h("monthsShort") || t.map(function (e) {
  28845. return e.slice(0, 3);
  28846. })).indexOf(e) + 1;
  28847. if (n < 1) throw new Error();
  28848. this.month = n % 12 || n;
  28849. }],
  28850. MMMM: [i, function (e) {
  28851. var t = h("months").indexOf(e) + 1;
  28852. if (t < 1) throw new Error();
  28853. this.month = t % 12 || t;
  28854. }],
  28855. Y: [/[+-]?\d+/, a("year")],
  28856. YY: [n, function (e) {
  28857. this.year = s(e);
  28858. }],
  28859. YYYY: [/\d{4}/, a("year")],
  28860. Z: f,
  28861. ZZ: f
  28862. };
  28863. function c(n) {
  28864. var r, i;
  28865. r = n, i = o && o.formats;
  28866. for (var s = (n = r.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g, function (t, n, r) {
  28867. var o = r && r.toUpperCase();
  28868. return n || i[r] || e[r] || i[o].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g, function (e, t, n) {
  28869. return t || n.slice(1);
  28870. });
  28871. })).match(t), a = s.length, f = 0; f < a; f += 1) {
  28872. var h = s[f],
  28873. u = d[h],
  28874. c = u && u[0],
  28875. l = u && u[1];
  28876. s[f] = l ? {
  28877. regex: c,
  28878. parser: l
  28879. } : h.replace(/^\[|\]$/g, "");
  28880. }
  28881. return function (e) {
  28882. for (var t = {}, n = 0, r = 0; n < a; n += 1) {
  28883. var i = s[n];
  28884. if ("string" == typeof i) r += i.length;else {
  28885. var o = i.regex,
  28886. f = i.parser,
  28887. h = e.slice(r),
  28888. u = o.exec(h)[0];
  28889. f.call(t, u), e = e.replace(u, "");
  28890. }
  28891. }
  28892. return function (e) {
  28893. var t = e.afternoon;
  28894. if (void 0 !== t) {
  28895. var n = e.hours;
  28896. t ? n < 12 && (e.hours += 12) : 12 === n && (e.hours = 0), delete e.afternoon;
  28897. }
  28898. }(t), t;
  28899. };
  28900. }
  28901. return function (e, t, n) {
  28902. n.p.customParseFormat = !0, e && e.parseTwoDigitYear && (s = e.parseTwoDigitYear);
  28903. var r = t.prototype,
  28904. i = r.parse;
  28905. r.parse = function (e) {
  28906. var t = e.date,
  28907. r = e.utc,
  28908. s = e.args;
  28909. this.$u = r;
  28910. var a = s[1];
  28911. if ("string" == typeof a) {
  28912. var f = !0 === s[2],
  28913. h = !0 === s[3],
  28914. u = f || h,
  28915. d = s[2];
  28916. h && (d = s[2]), o = this.$locale(), !f && d && (o = n.Ls[d]), this.$d = function (e, t, n) {
  28917. try {
  28918. if (["x", "X"].indexOf(t) > -1) return new Date(("X" === t ? 1e3 : 1) * e);
  28919. var r = c(t)(e),
  28920. i = r.year,
  28921. o = r.month,
  28922. s = r.day,
  28923. a = r.hours,
  28924. f = r.minutes,
  28925. h = r.seconds,
  28926. u = r.milliseconds,
  28927. d = r.zone,
  28928. l = new Date(),
  28929. m = s || (i || o ? 1 : l.getDate()),
  28930. M = i || l.getFullYear(),
  28931. Y = 0;
  28932. i && !o || (Y = o > 0 ? o - 1 : l.getMonth());
  28933. var p = a || 0,
  28934. v = f || 0,
  28935. D = h || 0,
  28936. g = u || 0;
  28937. return d ? new Date(Date.UTC(M, Y, m, p, v, D, g + 60 * d.offset * 1e3)) : n ? new Date(Date.UTC(M, Y, m, p, v, D, g)) : new Date(M, Y, m, p, v, D, g);
  28938. } catch (e) {
  28939. return new Date("");
  28940. }
  28941. }(t, a, r), this.init(), d && !0 !== d && (this.$L = this.locale(d).$L), u && t != this.format(a) && (this.$d = new Date("")), o = {};
  28942. } else if (a instanceof Array) for (var l = a.length, m = 1; m <= l; m += 1) {
  28943. s[1] = a[m - 1];
  28944. var M = n.apply(this, s);
  28945. if (M.isValid()) {
  28946. this.$d = M.$d, this.$L = M.$L, this.init();
  28947. break;
  28948. }
  28949. m === l && (this.$d = new Date(""));
  28950. } else i.call(this, e);
  28951. };
  28952. };
  28953. });
  28954. },{}],232:[function(require,module,exports){
  28955. "use strict";
  28956. !function (t, i) {
  28957. "object" == typeof exports && "undefined" != typeof module ? module.exports = i() : "function" == typeof define && define.amd ? define(i) : (t = "undefined" != typeof globalThis ? globalThis : t || self).dayjs_plugin_utc = i();
  28958. }(void 0, function () {
  28959. "use strict";
  28960. var t = "minute",
  28961. i = /[+-]\d\d(?::?\d\d)?/g,
  28962. e = /([+-]|\d\d)/g;
  28963. return function (s, f, n) {
  28964. var u = f.prototype;
  28965. n.utc = function (t) {
  28966. var i = {
  28967. date: t,
  28968. utc: !0,
  28969. args: arguments
  28970. };
  28971. return new f(i);
  28972. }, u.utc = function (i) {
  28973. var e = n(this.toDate(), {
  28974. locale: this.$L,
  28975. utc: !0
  28976. });
  28977. return i ? e.add(this.utcOffset(), t) : e;
  28978. }, u.local = function () {
  28979. return n(this.toDate(), {
  28980. locale: this.$L,
  28981. utc: !1
  28982. });
  28983. };
  28984. var o = u.parse;
  28985. u.parse = function (t) {
  28986. t.utc && (this.$u = !0), this.$utils().u(t.$offset) || (this.$offset = t.$offset), o.call(this, t);
  28987. };
  28988. var r = u.init;
  28989. u.init = function () {
  28990. if (this.$u) {
  28991. var t = this.$d;
  28992. this.$y = t.getUTCFullYear(), this.$M = t.getUTCMonth(), this.$D = t.getUTCDate(), this.$W = t.getUTCDay(), this.$H = t.getUTCHours(), this.$m = t.getUTCMinutes(), this.$s = t.getUTCSeconds(), this.$ms = t.getUTCMilliseconds();
  28993. } else r.call(this);
  28994. };
  28995. var a = u.utcOffset;
  28996. u.utcOffset = function (s, f) {
  28997. var n = this.$utils().u;
  28998. if (n(s)) return this.$u ? 0 : n(this.$offset) ? a.call(this) : this.$offset;
  28999. if ("string" == typeof s && (s = function (t) {
  29000. void 0 === t && (t = "");
  29001. var s = t.match(i);
  29002. if (!s) return null;
  29003. var f = ("" + s[0]).match(e) || ["-", 0, 0],
  29004. n = f[0],
  29005. u = 60 * +f[1] + +f[2];
  29006. return 0 === u ? 0 : "+" === n ? u : -u;
  29007. }(s), null === s)) return this;
  29008. var u = Math.abs(s) <= 16 ? 60 * s : s,
  29009. o = this;
  29010. if (f) return o.$offset = u, o.$u = 0 === s, o;
  29011. if (0 !== s) {
  29012. var r = this.$u ? this.toDate().getTimezoneOffset() : -1 * this.utcOffset();
  29013. (o = this.local().add(u + r, t)).$offset = u, o.$x.$localOffset = r;
  29014. } else o = this.utc();
  29015. return o;
  29016. };
  29017. var h = u.format;
  29018. u.format = function (t) {
  29019. var i = t || (this.$u ? "YYYY-MM-DDTHH:mm:ss[Z]" : "");
  29020. return h.call(this, i);
  29021. }, u.valueOf = function () {
  29022. var t = this.$utils().u(this.$offset) ? 0 : this.$offset + (this.$x.$localOffset || this.$d.getTimezoneOffset());
  29023. return this.$d.valueOf() - 6e4 * t;
  29024. }, u.isUTC = function () {
  29025. return !!this.$u;
  29026. }, u.toISOString = function () {
  29027. return this.toDate().toISOString();
  29028. }, u.toString = function () {
  29029. return this.toDate().toUTCString();
  29030. };
  29031. var l = u.toDate;
  29032. u.toDate = function (t) {
  29033. return "s" === t && this.$offset ? n(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate() : l.call(this);
  29034. };
  29035. var c = u.diff;
  29036. u.diff = function (t, i, e) {
  29037. if (t && this.$u === t.$u) return c.call(this, t, i, e);
  29038. var s = this.local(),
  29039. f = n(t).local();
  29040. return c.call(s, f, i, e);
  29041. };
  29042. };
  29043. });
  29044. },{}],233:[function(require,module,exports){
  29045. 'use strict';
  29046. exports.utils = require('./des/utils');
  29047. exports.Cipher = require('./des/cipher');
  29048. exports.DES = require('./des/des');
  29049. exports.CBC = require('./des/cbc');
  29050. exports.EDE = require('./des/ede');
  29051. },{"./des/cbc":234,"./des/cipher":235,"./des/des":236,"./des/ede":237,"./des/utils":238}],234:[function(require,module,exports){
  29052. 'use strict';
  29053. var assert = require('minimalistic-assert');
  29054. var inherits = require('inherits');
  29055. var proto = {};
  29056. function CBCState(iv) {
  29057. assert.equal(iv.length, 8, 'Invalid IV length');
  29058. this.iv = new Array(8);
  29059. for (var i = 0; i < this.iv.length; i++) this.iv[i] = iv[i];
  29060. }
  29061. function instantiate(Base) {
  29062. function CBC(options) {
  29063. Base.call(this, options);
  29064. this._cbcInit();
  29065. }
  29066. inherits(CBC, Base);
  29067. var keys = Object.keys(proto);
  29068. for (var i = 0; i < keys.length; i++) {
  29069. var key = keys[i];
  29070. CBC.prototype[key] = proto[key];
  29071. }
  29072. CBC.create = function create(options) {
  29073. return new CBC(options);
  29074. };
  29075. return CBC;
  29076. }
  29077. exports.instantiate = instantiate;
  29078. proto._cbcInit = function _cbcInit() {
  29079. var state = new CBCState(this.options.iv);
  29080. this._cbcState = state;
  29081. };
  29082. proto._update = function _update(inp, inOff, out, outOff) {
  29083. var state = this._cbcState;
  29084. var superProto = this.constructor.super_.prototype;
  29085. var iv = state.iv;
  29086. if (this.type === 'encrypt') {
  29087. for (var i = 0; i < this.blockSize; i++) iv[i] ^= inp[inOff + i];
  29088. superProto._update.call(this, iv, 0, out, outOff);
  29089. for (var i = 0; i < this.blockSize; i++) iv[i] = out[outOff + i];
  29090. } else {
  29091. superProto._update.call(this, inp, inOff, out, outOff);
  29092. for (var i = 0; i < this.blockSize; i++) out[outOff + i] ^= iv[i];
  29093. for (var i = 0; i < this.blockSize; i++) iv[i] = inp[inOff + i];
  29094. }
  29095. };
  29096. },{"inherits":279,"minimalistic-assert":292}],235:[function(require,module,exports){
  29097. 'use strict';
  29098. var assert = require('minimalistic-assert');
  29099. function Cipher(options) {
  29100. this.options = options;
  29101. this.type = this.options.type;
  29102. this.blockSize = 8;
  29103. this._init();
  29104. this.buffer = new Array(this.blockSize);
  29105. this.bufferOff = 0;
  29106. this.padding = options.padding !== false;
  29107. }
  29108. module.exports = Cipher;
  29109. Cipher.prototype._init = function _init() {
  29110. // Might be overrided
  29111. };
  29112. Cipher.prototype.update = function update(data) {
  29113. if (data.length === 0) return [];
  29114. if (this.type === 'decrypt') return this._updateDecrypt(data);else return this._updateEncrypt(data);
  29115. };
  29116. Cipher.prototype._buffer = function _buffer(data, off) {
  29117. // Append data to buffer
  29118. var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
  29119. for (var i = 0; i < min; i++) this.buffer[this.bufferOff + i] = data[off + i];
  29120. this.bufferOff += min;
  29121. // Shift next
  29122. return min;
  29123. };
  29124. Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
  29125. this._update(this.buffer, 0, out, off);
  29126. this.bufferOff = 0;
  29127. return this.blockSize;
  29128. };
  29129. Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
  29130. var inputOff = 0;
  29131. var outputOff = 0;
  29132. var count = (this.bufferOff + data.length) / this.blockSize | 0;
  29133. var out = new Array(count * this.blockSize);
  29134. if (this.bufferOff !== 0) {
  29135. inputOff += this._buffer(data, inputOff);
  29136. if (this.bufferOff === this.buffer.length) outputOff += this._flushBuffer(out, outputOff);
  29137. }
  29138. // Write blocks
  29139. var max = data.length - (data.length - inputOff) % this.blockSize;
  29140. for (; inputOff < max; inputOff += this.blockSize) {
  29141. this._update(data, inputOff, out, outputOff);
  29142. outputOff += this.blockSize;
  29143. }
  29144. // Queue rest
  29145. for (; inputOff < data.length; inputOff++, this.bufferOff++) this.buffer[this.bufferOff] = data[inputOff];
  29146. return out;
  29147. };
  29148. Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
  29149. var inputOff = 0;
  29150. var outputOff = 0;
  29151. var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
  29152. var out = new Array(count * this.blockSize);
  29153. // TODO(indutny): optimize it, this is far from optimal
  29154. for (; count > 0; count--) {
  29155. inputOff += this._buffer(data, inputOff);
  29156. outputOff += this._flushBuffer(out, outputOff);
  29157. }
  29158. // Buffer rest of the input
  29159. inputOff += this._buffer(data, inputOff);
  29160. return out;
  29161. };
  29162. Cipher.prototype.final = function final(buffer) {
  29163. var first;
  29164. if (buffer) first = this.update(buffer);
  29165. var last;
  29166. if (this.type === 'encrypt') last = this._finalEncrypt();else last = this._finalDecrypt();
  29167. if (first) return first.concat(last);else return last;
  29168. };
  29169. Cipher.prototype._pad = function _pad(buffer, off) {
  29170. if (off === 0) return false;
  29171. while (off < buffer.length) buffer[off++] = 0;
  29172. return true;
  29173. };
  29174. Cipher.prototype._finalEncrypt = function _finalEncrypt() {
  29175. if (!this._pad(this.buffer, this.bufferOff)) return [];
  29176. var out = new Array(this.blockSize);
  29177. this._update(this.buffer, 0, out, 0);
  29178. return out;
  29179. };
  29180. Cipher.prototype._unpad = function _unpad(buffer) {
  29181. return buffer;
  29182. };
  29183. Cipher.prototype._finalDecrypt = function _finalDecrypt() {
  29184. assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
  29185. var out = new Array(this.blockSize);
  29186. this._flushBuffer(out, 0);
  29187. return this._unpad(out);
  29188. };
  29189. },{"minimalistic-assert":292}],236:[function(require,module,exports){
  29190. 'use strict';
  29191. var assert = require('minimalistic-assert');
  29192. var inherits = require('inherits');
  29193. var utils = require('./utils');
  29194. var Cipher = require('./cipher');
  29195. function DESState() {
  29196. this.tmp = new Array(2);
  29197. this.keys = null;
  29198. }
  29199. function DES(options) {
  29200. Cipher.call(this, options);
  29201. var state = new DESState();
  29202. this._desState = state;
  29203. this.deriveKeys(state, options.key);
  29204. }
  29205. inherits(DES, Cipher);
  29206. module.exports = DES;
  29207. DES.create = function create(options) {
  29208. return new DES(options);
  29209. };
  29210. var shiftTable = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1];
  29211. DES.prototype.deriveKeys = function deriveKeys(state, key) {
  29212. state.keys = new Array(16 * 2);
  29213. assert.equal(key.length, this.blockSize, 'Invalid key length');
  29214. var kL = utils.readUInt32BE(key, 0);
  29215. var kR = utils.readUInt32BE(key, 4);
  29216. utils.pc1(kL, kR, state.tmp, 0);
  29217. kL = state.tmp[0];
  29218. kR = state.tmp[1];
  29219. for (var i = 0; i < state.keys.length; i += 2) {
  29220. var shift = shiftTable[i >>> 1];
  29221. kL = utils.r28shl(kL, shift);
  29222. kR = utils.r28shl(kR, shift);
  29223. utils.pc2(kL, kR, state.keys, i);
  29224. }
  29225. };
  29226. DES.prototype._update = function _update(inp, inOff, out, outOff) {
  29227. var state = this._desState;
  29228. var l = utils.readUInt32BE(inp, inOff);
  29229. var r = utils.readUInt32BE(inp, inOff + 4);
  29230. // Initial Permutation
  29231. utils.ip(l, r, state.tmp, 0);
  29232. l = state.tmp[0];
  29233. r = state.tmp[1];
  29234. if (this.type === 'encrypt') this._encrypt(state, l, r, state.tmp, 0);else this._decrypt(state, l, r, state.tmp, 0);
  29235. l = state.tmp[0];
  29236. r = state.tmp[1];
  29237. utils.writeUInt32BE(out, l, outOff);
  29238. utils.writeUInt32BE(out, r, outOff + 4);
  29239. };
  29240. DES.prototype._pad = function _pad(buffer, off) {
  29241. if (this.padding === false) {
  29242. return false;
  29243. }
  29244. var value = buffer.length - off;
  29245. for (var i = off; i < buffer.length; i++) buffer[i] = value;
  29246. return true;
  29247. };
  29248. DES.prototype._unpad = function _unpad(buffer) {
  29249. if (this.padding === false) {
  29250. return buffer;
  29251. }
  29252. var pad = buffer[buffer.length - 1];
  29253. for (var i = buffer.length - pad; i < buffer.length; i++) assert.equal(buffer[i], pad);
  29254. return buffer.slice(0, buffer.length - pad);
  29255. };
  29256. DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
  29257. var l = lStart;
  29258. var r = rStart;
  29259. // Apply f() x16 times
  29260. for (var i = 0; i < state.keys.length; i += 2) {
  29261. var keyL = state.keys[i];
  29262. var keyR = state.keys[i + 1];
  29263. // f(r, k)
  29264. utils.expand(r, state.tmp, 0);
  29265. keyL ^= state.tmp[0];
  29266. keyR ^= state.tmp[1];
  29267. var s = utils.substitute(keyL, keyR);
  29268. var f = utils.permute(s);
  29269. var t = r;
  29270. r = (l ^ f) >>> 0;
  29271. l = t;
  29272. }
  29273. // Reverse Initial Permutation
  29274. utils.rip(r, l, out, off);
  29275. };
  29276. DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
  29277. var l = rStart;
  29278. var r = lStart;
  29279. // Apply f() x16 times
  29280. for (var i = state.keys.length - 2; i >= 0; i -= 2) {
  29281. var keyL = state.keys[i];
  29282. var keyR = state.keys[i + 1];
  29283. // f(r, k)
  29284. utils.expand(l, state.tmp, 0);
  29285. keyL ^= state.tmp[0];
  29286. keyR ^= state.tmp[1];
  29287. var s = utils.substitute(keyL, keyR);
  29288. var f = utils.permute(s);
  29289. var t = l;
  29290. l = (r ^ f) >>> 0;
  29291. r = t;
  29292. }
  29293. // Reverse Initial Permutation
  29294. utils.rip(l, r, out, off);
  29295. };
  29296. },{"./cipher":235,"./utils":238,"inherits":279,"minimalistic-assert":292}],237:[function(require,module,exports){
  29297. 'use strict';
  29298. var assert = require('minimalistic-assert');
  29299. var inherits = require('inherits');
  29300. var Cipher = require('./cipher');
  29301. var DES = require('./des');
  29302. function EDEState(type, key) {
  29303. assert.equal(key.length, 24, 'Invalid key length');
  29304. var k1 = key.slice(0, 8);
  29305. var k2 = key.slice(8, 16);
  29306. var k3 = key.slice(16, 24);
  29307. if (type === 'encrypt') {
  29308. this.ciphers = [DES.create({
  29309. type: 'encrypt',
  29310. key: k1
  29311. }), DES.create({
  29312. type: 'decrypt',
  29313. key: k2
  29314. }), DES.create({
  29315. type: 'encrypt',
  29316. key: k3
  29317. })];
  29318. } else {
  29319. this.ciphers = [DES.create({
  29320. type: 'decrypt',
  29321. key: k3
  29322. }), DES.create({
  29323. type: 'encrypt',
  29324. key: k2
  29325. }), DES.create({
  29326. type: 'decrypt',
  29327. key: k1
  29328. })];
  29329. }
  29330. }
  29331. function EDE(options) {
  29332. Cipher.call(this, options);
  29333. var state = new EDEState(this.type, this.options.key);
  29334. this._edeState = state;
  29335. }
  29336. inherits(EDE, Cipher);
  29337. module.exports = EDE;
  29338. EDE.create = function create(options) {
  29339. return new EDE(options);
  29340. };
  29341. EDE.prototype._update = function _update(inp, inOff, out, outOff) {
  29342. var state = this._edeState;
  29343. state.ciphers[0]._update(inp, inOff, out, outOff);
  29344. state.ciphers[1]._update(out, outOff, out, outOff);
  29345. state.ciphers[2]._update(out, outOff, out, outOff);
  29346. };
  29347. EDE.prototype._pad = DES.prototype._pad;
  29348. EDE.prototype._unpad = DES.prototype._unpad;
  29349. },{"./cipher":235,"./des":236,"inherits":279,"minimalistic-assert":292}],238:[function(require,module,exports){
  29350. 'use strict';
  29351. exports.readUInt32BE = function readUInt32BE(bytes, off) {
  29352. var res = bytes[0 + off] << 24 | bytes[1 + off] << 16 | bytes[2 + off] << 8 | bytes[3 + off];
  29353. return res >>> 0;
  29354. };
  29355. exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
  29356. bytes[0 + off] = value >>> 24;
  29357. bytes[1 + off] = value >>> 16 & 0xff;
  29358. bytes[2 + off] = value >>> 8 & 0xff;
  29359. bytes[3 + off] = value & 0xff;
  29360. };
  29361. exports.ip = function ip(inL, inR, out, off) {
  29362. var outL = 0;
  29363. var outR = 0;
  29364. for (var i = 6; i >= 0; i -= 2) {
  29365. for (var j = 0; j <= 24; j += 8) {
  29366. outL <<= 1;
  29367. outL |= inR >>> j + i & 1;
  29368. }
  29369. for (var j = 0; j <= 24; j += 8) {
  29370. outL <<= 1;
  29371. outL |= inL >>> j + i & 1;
  29372. }
  29373. }
  29374. for (var i = 6; i >= 0; i -= 2) {
  29375. for (var j = 1; j <= 25; j += 8) {
  29376. outR <<= 1;
  29377. outR |= inR >>> j + i & 1;
  29378. }
  29379. for (var j = 1; j <= 25; j += 8) {
  29380. outR <<= 1;
  29381. outR |= inL >>> j + i & 1;
  29382. }
  29383. }
  29384. out[off + 0] = outL >>> 0;
  29385. out[off + 1] = outR >>> 0;
  29386. };
  29387. exports.rip = function rip(inL, inR, out, off) {
  29388. var outL = 0;
  29389. var outR = 0;
  29390. for (var i = 0; i < 4; i++) {
  29391. for (var j = 24; j >= 0; j -= 8) {
  29392. outL <<= 1;
  29393. outL |= inR >>> j + i & 1;
  29394. outL <<= 1;
  29395. outL |= inL >>> j + i & 1;
  29396. }
  29397. }
  29398. for (var i = 4; i < 8; i++) {
  29399. for (var j = 24; j >= 0; j -= 8) {
  29400. outR <<= 1;
  29401. outR |= inR >>> j + i & 1;
  29402. outR <<= 1;
  29403. outR |= inL >>> j + i & 1;
  29404. }
  29405. }
  29406. out[off + 0] = outL >>> 0;
  29407. out[off + 1] = outR >>> 0;
  29408. };
  29409. exports.pc1 = function pc1(inL, inR, out, off) {
  29410. var outL = 0;
  29411. var outR = 0;
  29412. // 7, 15, 23, 31, 39, 47, 55, 63
  29413. // 6, 14, 22, 30, 39, 47, 55, 63
  29414. // 5, 13, 21, 29, 39, 47, 55, 63
  29415. // 4, 12, 20, 28
  29416. for (var i = 7; i >= 5; i--) {
  29417. for (var j = 0; j <= 24; j += 8) {
  29418. outL <<= 1;
  29419. outL |= inR >> j + i & 1;
  29420. }
  29421. for (var j = 0; j <= 24; j += 8) {
  29422. outL <<= 1;
  29423. outL |= inL >> j + i & 1;
  29424. }
  29425. }
  29426. for (var j = 0; j <= 24; j += 8) {
  29427. outL <<= 1;
  29428. outL |= inR >> j + i & 1;
  29429. }
  29430. // 1, 9, 17, 25, 33, 41, 49, 57
  29431. // 2, 10, 18, 26, 34, 42, 50, 58
  29432. // 3, 11, 19, 27, 35, 43, 51, 59
  29433. // 36, 44, 52, 60
  29434. for (var i = 1; i <= 3; i++) {
  29435. for (var j = 0; j <= 24; j += 8) {
  29436. outR <<= 1;
  29437. outR |= inR >> j + i & 1;
  29438. }
  29439. for (var j = 0; j <= 24; j += 8) {
  29440. outR <<= 1;
  29441. outR |= inL >> j + i & 1;
  29442. }
  29443. }
  29444. for (var j = 0; j <= 24; j += 8) {
  29445. outR <<= 1;
  29446. outR |= inL >> j + i & 1;
  29447. }
  29448. out[off + 0] = outL >>> 0;
  29449. out[off + 1] = outR >>> 0;
  29450. };
  29451. exports.r28shl = function r28shl(num, shift) {
  29452. return num << shift & 0xfffffff | num >>> 28 - shift;
  29453. };
  29454. var pc2table = [
  29455. // inL => outL
  29456. 14, 11, 17, 4, 27, 23, 25, 0, 13, 22, 7, 18, 5, 9, 16, 24, 2, 20, 12, 21, 1, 8, 15, 26,
  29457. // inR => outR
  29458. 15, 4, 25, 19, 9, 1, 26, 16, 5, 11, 23, 8, 12, 7, 17, 0, 22, 3, 10, 14, 6, 20, 27, 24];
  29459. exports.pc2 = function pc2(inL, inR, out, off) {
  29460. var outL = 0;
  29461. var outR = 0;
  29462. var len = pc2table.length >>> 1;
  29463. for (var i = 0; i < len; i++) {
  29464. outL <<= 1;
  29465. outL |= inL >>> pc2table[i] & 0x1;
  29466. }
  29467. for (var i = len; i < pc2table.length; i++) {
  29468. outR <<= 1;
  29469. outR |= inR >>> pc2table[i] & 0x1;
  29470. }
  29471. out[off + 0] = outL >>> 0;
  29472. out[off + 1] = outR >>> 0;
  29473. };
  29474. exports.expand = function expand(r, out, off) {
  29475. var outL = 0;
  29476. var outR = 0;
  29477. outL = (r & 1) << 5 | r >>> 27;
  29478. for (var i = 23; i >= 15; i -= 4) {
  29479. outL <<= 6;
  29480. outL |= r >>> i & 0x3f;
  29481. }
  29482. for (var i = 11; i >= 3; i -= 4) {
  29483. outR |= r >>> i & 0x3f;
  29484. outR <<= 6;
  29485. }
  29486. outR |= (r & 0x1f) << 1 | r >>> 31;
  29487. out[off + 0] = outL >>> 0;
  29488. out[off + 1] = outR >>> 0;
  29489. };
  29490. var sTable = [14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11];
  29491. exports.substitute = function substitute(inL, inR) {
  29492. var out = 0;
  29493. for (var i = 0; i < 4; i++) {
  29494. var b = inL >>> 18 - i * 6 & 0x3f;
  29495. var sb = sTable[i * 0x40 + b];
  29496. out <<= 4;
  29497. out |= sb;
  29498. }
  29499. for (var i = 0; i < 4; i++) {
  29500. var b = inR >>> 18 - i * 6 & 0x3f;
  29501. var sb = sTable[4 * 0x40 + i * 0x40 + b];
  29502. out <<= 4;
  29503. out |= sb;
  29504. }
  29505. return out >>> 0;
  29506. };
  29507. var permuteTable = [16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7];
  29508. exports.permute = function permute(num) {
  29509. var out = 0;
  29510. for (var i = 0; i < permuteTable.length; i++) {
  29511. out <<= 1;
  29512. out |= num >>> permuteTable[i] & 0x1;
  29513. }
  29514. return out >>> 0;
  29515. };
  29516. exports.padSplit = function padSplit(num, size, group) {
  29517. var str = num.toString(2);
  29518. while (str.length < size) str = '0' + str;
  29519. var out = [];
  29520. for (var i = 0; i < size; i += group) out.push(str.slice(i, i + group));
  29521. return out.join(' ');
  29522. };
  29523. },{}],239:[function(require,module,exports){
  29524. (function (Buffer){(function (){
  29525. "use strict";
  29526. var generatePrime = require('./lib/generatePrime');
  29527. var primes = require('./lib/primes.json');
  29528. var DH = require('./lib/dh');
  29529. function getDiffieHellman(mod) {
  29530. var prime = new Buffer(primes[mod].prime, 'hex');
  29531. var gen = new Buffer(primes[mod].gen, 'hex');
  29532. return new DH(prime, gen);
  29533. }
  29534. var ENCODINGS = {
  29535. 'binary': true,
  29536. 'hex': true,
  29537. 'base64': true
  29538. };
  29539. function createDiffieHellman(prime, enc, generator, genc) {
  29540. if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
  29541. return createDiffieHellman(prime, 'binary', enc, generator);
  29542. }
  29543. enc = enc || 'binary';
  29544. genc = genc || 'binary';
  29545. generator = generator || new Buffer([2]);
  29546. if (!Buffer.isBuffer(generator)) {
  29547. generator = new Buffer(generator, genc);
  29548. }
  29549. if (typeof prime === 'number') {
  29550. return new DH(generatePrime(prime, generator), generator, true);
  29551. }
  29552. if (!Buffer.isBuffer(prime)) {
  29553. prime = new Buffer(prime, enc);
  29554. }
  29555. return new DH(prime, generator, true);
  29556. }
  29557. exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman;
  29558. exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman;
  29559. }).call(this)}).call(this,require("buffer").Buffer)
  29560. },{"./lib/dh":240,"./lib/generatePrime":241,"./lib/primes.json":242,"buffer":220}],240:[function(require,module,exports){
  29561. (function (Buffer){(function (){
  29562. "use strict";
  29563. var BN = require('bn.js');
  29564. var MillerRabin = require('miller-rabin');
  29565. var millerRabin = new MillerRabin();
  29566. var TWENTYFOUR = new BN(24);
  29567. var ELEVEN = new BN(11);
  29568. var TEN = new BN(10);
  29569. var THREE = new BN(3);
  29570. var SEVEN = new BN(7);
  29571. var primes = require('./generatePrime');
  29572. var randomBytes = require('randombytes');
  29573. module.exports = DH;
  29574. function setPublicKey(pub, enc) {
  29575. enc = enc || 'utf8';
  29576. if (!Buffer.isBuffer(pub)) {
  29577. pub = new Buffer(pub, enc);
  29578. }
  29579. this._pub = new BN(pub);
  29580. return this;
  29581. }
  29582. function setPrivateKey(priv, enc) {
  29583. enc = enc || 'utf8';
  29584. if (!Buffer.isBuffer(priv)) {
  29585. priv = new Buffer(priv, enc);
  29586. }
  29587. this._priv = new BN(priv);
  29588. return this;
  29589. }
  29590. var primeCache = {};
  29591. function checkPrime(prime, generator) {
  29592. var gen = generator.toString('hex');
  29593. var hex = [gen, prime.toString(16)].join('_');
  29594. if (hex in primeCache) {
  29595. return primeCache[hex];
  29596. }
  29597. var error = 0;
  29598. if (prime.isEven() || !primes.simpleSieve || !primes.fermatTest(prime) || !millerRabin.test(prime)) {
  29599. //not a prime so +1
  29600. error += 1;
  29601. if (gen === '02' || gen === '05') {
  29602. // we'd be able to check the generator
  29603. // it would fail so +8
  29604. error += 8;
  29605. } else {
  29606. //we wouldn't be able to test the generator
  29607. // so +4
  29608. error += 4;
  29609. }
  29610. primeCache[hex] = error;
  29611. return error;
  29612. }
  29613. if (!millerRabin.test(prime.shrn(1))) {
  29614. //not a safe prime
  29615. error += 2;
  29616. }
  29617. var rem;
  29618. switch (gen) {
  29619. case '02':
  29620. if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
  29621. // unsuidable generator
  29622. error += 8;
  29623. }
  29624. break;
  29625. case '05':
  29626. rem = prime.mod(TEN);
  29627. if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
  29628. // prime mod 10 needs to equal 3 or 7
  29629. error += 8;
  29630. }
  29631. break;
  29632. default:
  29633. error += 4;
  29634. }
  29635. primeCache[hex] = error;
  29636. return error;
  29637. }
  29638. function DH(prime, generator, malleable) {
  29639. this.setGenerator(generator);
  29640. this.__prime = new BN(prime);
  29641. this._prime = BN.mont(this.__prime);
  29642. this._primeLen = prime.length;
  29643. this._pub = undefined;
  29644. this._priv = undefined;
  29645. this._primeCode = undefined;
  29646. if (malleable) {
  29647. this.setPublicKey = setPublicKey;
  29648. this.setPrivateKey = setPrivateKey;
  29649. } else {
  29650. this._primeCode = 8;
  29651. }
  29652. }
  29653. Object.defineProperty(DH.prototype, 'verifyError', {
  29654. enumerable: true,
  29655. get: function () {
  29656. if (typeof this._primeCode !== 'number') {
  29657. this._primeCode = checkPrime(this.__prime, this.__gen);
  29658. }
  29659. return this._primeCode;
  29660. }
  29661. });
  29662. DH.prototype.generateKeys = function () {
  29663. if (!this._priv) {
  29664. this._priv = new BN(randomBytes(this._primeLen));
  29665. }
  29666. this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
  29667. return this.getPublicKey();
  29668. };
  29669. DH.prototype.computeSecret = function (other) {
  29670. other = new BN(other);
  29671. other = other.toRed(this._prime);
  29672. var secret = other.redPow(this._priv).fromRed();
  29673. var out = new Buffer(secret.toArray());
  29674. var prime = this.getPrime();
  29675. if (out.length < prime.length) {
  29676. var front = new Buffer(prime.length - out.length);
  29677. front.fill(0);
  29678. out = Buffer.concat([front, out]);
  29679. }
  29680. return out;
  29681. };
  29682. DH.prototype.getPublicKey = function getPublicKey(enc) {
  29683. return formatReturnValue(this._pub, enc);
  29684. };
  29685. DH.prototype.getPrivateKey = function getPrivateKey(enc) {
  29686. return formatReturnValue(this._priv, enc);
  29687. };
  29688. DH.prototype.getPrime = function (enc) {
  29689. return formatReturnValue(this.__prime, enc);
  29690. };
  29691. DH.prototype.getGenerator = function (enc) {
  29692. return formatReturnValue(this._gen, enc);
  29693. };
  29694. DH.prototype.setGenerator = function (gen, enc) {
  29695. enc = enc || 'utf8';
  29696. if (!Buffer.isBuffer(gen)) {
  29697. gen = new Buffer(gen, enc);
  29698. }
  29699. this.__gen = gen;
  29700. this._gen = new BN(gen);
  29701. return this;
  29702. };
  29703. function formatReturnValue(bn, enc) {
  29704. var buf = new Buffer(bn.toArray());
  29705. if (!enc) {
  29706. return buf;
  29707. } else {
  29708. return buf.toString(enc);
  29709. }
  29710. }
  29711. }).call(this)}).call(this,require("buffer").Buffer)
  29712. },{"./generatePrime":241,"bn.js":243,"buffer":220,"miller-rabin":290,"randombytes":314}],241:[function(require,module,exports){
  29713. "use strict";
  29714. var randomBytes = require('randombytes');
  29715. module.exports = findPrime;
  29716. findPrime.simpleSieve = simpleSieve;
  29717. findPrime.fermatTest = fermatTest;
  29718. var BN = require('bn.js');
  29719. var TWENTYFOUR = new BN(24);
  29720. var MillerRabin = require('miller-rabin');
  29721. var millerRabin = new MillerRabin();
  29722. var ONE = new BN(1);
  29723. var TWO = new BN(2);
  29724. var FIVE = new BN(5);
  29725. var SIXTEEN = new BN(16);
  29726. var EIGHT = new BN(8);
  29727. var TEN = new BN(10);
  29728. var THREE = new BN(3);
  29729. var SEVEN = new BN(7);
  29730. var ELEVEN = new BN(11);
  29731. var FOUR = new BN(4);
  29732. var TWELVE = new BN(12);
  29733. var primes = null;
  29734. function _getPrimes() {
  29735. if (primes !== null) return primes;
  29736. var limit = 0x100000;
  29737. var res = [];
  29738. res[0] = 2;
  29739. for (var i = 1, k = 3; k < limit; k += 2) {
  29740. var sqrt = Math.ceil(Math.sqrt(k));
  29741. for (var j = 0; j < i && res[j] <= sqrt; j++) if (k % res[j] === 0) break;
  29742. if (i !== j && res[j] <= sqrt) continue;
  29743. res[i++] = k;
  29744. }
  29745. primes = res;
  29746. return res;
  29747. }
  29748. function simpleSieve(p) {
  29749. var primes = _getPrimes();
  29750. for (var i = 0; i < primes.length; i++) if (p.modn(primes[i]) === 0) {
  29751. if (p.cmpn(primes[i]) === 0) {
  29752. return true;
  29753. } else {
  29754. return false;
  29755. }
  29756. }
  29757. return true;
  29758. }
  29759. function fermatTest(p) {
  29760. var red = BN.mont(p);
  29761. return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
  29762. }
  29763. function findPrime(bits, gen) {
  29764. if (bits < 16) {
  29765. // this is what openssl does
  29766. if (gen === 2 || gen === 5) {
  29767. return new BN([0x8c, 0x7b]);
  29768. } else {
  29769. return new BN([0x8c, 0x27]);
  29770. }
  29771. }
  29772. gen = new BN(gen);
  29773. var num, n2;
  29774. while (true) {
  29775. num = new BN(randomBytes(Math.ceil(bits / 8)));
  29776. while (num.bitLength() > bits) {
  29777. num.ishrn(1);
  29778. }
  29779. if (num.isEven()) {
  29780. num.iadd(ONE);
  29781. }
  29782. if (!num.testn(1)) {
  29783. num.iadd(TWO);
  29784. }
  29785. if (!gen.cmp(TWO)) {
  29786. while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
  29787. num.iadd(FOUR);
  29788. }
  29789. } else if (!gen.cmp(FIVE)) {
  29790. while (num.mod(TEN).cmp(THREE)) {
  29791. num.iadd(FOUR);
  29792. }
  29793. }
  29794. n2 = num.shrn(1);
  29795. if (simpleSieve(n2) && simpleSieve(num) && fermatTest(n2) && fermatTest(num) && millerRabin.test(n2) && millerRabin.test(num)) {
  29796. return num;
  29797. }
  29798. }
  29799. }
  29800. },{"bn.js":243,"miller-rabin":290,"randombytes":314}],242:[function(require,module,exports){
  29801. module.exports={
  29802. "modp1": {
  29803. "gen": "02",
  29804. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
  29805. },
  29806. "modp2": {
  29807. "gen": "02",
  29808. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
  29809. },
  29810. "modp5": {
  29811. "gen": "02",
  29812. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
  29813. },
  29814. "modp14": {
  29815. "gen": "02",
  29816. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
  29817. },
  29818. "modp15": {
  29819. "gen": "02",
  29820. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
  29821. },
  29822. "modp16": {
  29823. "gen": "02",
  29824. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
  29825. },
  29826. "modp17": {
  29827. "gen": "02",
  29828. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
  29829. },
  29830. "modp18": {
  29831. "gen": "02",
  29832. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
  29833. }
  29834. }
  29835. },{}],243:[function(require,module,exports){
  29836. arguments[4][184][0].apply(exports,arguments)
  29837. },{"buffer":188,"dup":184}],244:[function(require,module,exports){
  29838. 'use strict';
  29839. var elliptic = exports;
  29840. elliptic.version = require('../package.json').version;
  29841. elliptic.utils = require('./elliptic/utils');
  29842. elliptic.rand = require('brorand');
  29843. elliptic.curve = require('./elliptic/curve');
  29844. elliptic.curves = require('./elliptic/curves');
  29845. // Protocols
  29846. elliptic.ec = require('./elliptic/ec');
  29847. elliptic.eddsa = require('./elliptic/eddsa');
  29848. },{"../package.json":260,"./elliptic/curve":247,"./elliptic/curves":250,"./elliptic/ec":251,"./elliptic/eddsa":254,"./elliptic/utils":258,"brorand":187}],245:[function(require,module,exports){
  29849. 'use strict';
  29850. var BN = require('bn.js');
  29851. var utils = require('../utils');
  29852. var getNAF = utils.getNAF;
  29853. var getJSF = utils.getJSF;
  29854. var assert = utils.assert;
  29855. function BaseCurve(type, conf) {
  29856. this.type = type;
  29857. this.p = new BN(conf.p, 16);
  29858. // Use Montgomery, when there is no fast reduction for the prime
  29859. this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
  29860. // Useful for many curves
  29861. this.zero = new BN(0).toRed(this.red);
  29862. this.one = new BN(1).toRed(this.red);
  29863. this.two = new BN(2).toRed(this.red);
  29864. // Curve configuration, optional
  29865. this.n = conf.n && new BN(conf.n, 16);
  29866. this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
  29867. // Temporary arrays
  29868. this._wnafT1 = new Array(4);
  29869. this._wnafT2 = new Array(4);
  29870. this._wnafT3 = new Array(4);
  29871. this._wnafT4 = new Array(4);
  29872. this._bitLength = this.n ? this.n.bitLength() : 0;
  29873. // Generalized Greg Maxwell's trick
  29874. var adjustCount = this.n && this.p.div(this.n);
  29875. if (!adjustCount || adjustCount.cmpn(100) > 0) {
  29876. this.redN = null;
  29877. } else {
  29878. this._maxwellTrick = true;
  29879. this.redN = this.n.toRed(this.red);
  29880. }
  29881. }
  29882. module.exports = BaseCurve;
  29883. BaseCurve.prototype.point = function point() {
  29884. throw new Error('Not implemented');
  29885. };
  29886. BaseCurve.prototype.validate = function validate() {
  29887. throw new Error('Not implemented');
  29888. };
  29889. BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
  29890. assert(p.precomputed);
  29891. var doubles = p._getDoubles();
  29892. var naf = getNAF(k, 1, this._bitLength);
  29893. var I = (1 << doubles.step + 1) - (doubles.step % 2 === 0 ? 2 : 1);
  29894. I /= 3;
  29895. // Translate into more windowed form
  29896. var repr = [];
  29897. var j;
  29898. var nafW;
  29899. for (j = 0; j < naf.length; j += doubles.step) {
  29900. nafW = 0;
  29901. for (var l = j + doubles.step - 1; l >= j; l--) nafW = (nafW << 1) + naf[l];
  29902. repr.push(nafW);
  29903. }
  29904. var a = this.jpoint(null, null, null);
  29905. var b = this.jpoint(null, null, null);
  29906. for (var i = I; i > 0; i--) {
  29907. for (j = 0; j < repr.length; j++) {
  29908. nafW = repr[j];
  29909. if (nafW === i) b = b.mixedAdd(doubles.points[j]);else if (nafW === -i) b = b.mixedAdd(doubles.points[j].neg());
  29910. }
  29911. a = a.add(b);
  29912. }
  29913. return a.toP();
  29914. };
  29915. BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
  29916. var w = 4;
  29917. // Precompute window
  29918. var nafPoints = p._getNAFPoints(w);
  29919. w = nafPoints.wnd;
  29920. var wnd = nafPoints.points;
  29921. // Get NAF form
  29922. var naf = getNAF(k, w, this._bitLength);
  29923. // Add `this`*(N+1) for every w-NAF index
  29924. var acc = this.jpoint(null, null, null);
  29925. for (var i = naf.length - 1; i >= 0; i--) {
  29926. // Count zeroes
  29927. for (var l = 0; i >= 0 && naf[i] === 0; i--) l++;
  29928. if (i >= 0) l++;
  29929. acc = acc.dblp(l);
  29930. if (i < 0) break;
  29931. var z = naf[i];
  29932. assert(z !== 0);
  29933. if (p.type === 'affine') {
  29934. // J +- P
  29935. if (z > 0) acc = acc.mixedAdd(wnd[z - 1 >> 1]);else acc = acc.mixedAdd(wnd[-z - 1 >> 1].neg());
  29936. } else {
  29937. // J +- J
  29938. if (z > 0) acc = acc.add(wnd[z - 1 >> 1]);else acc = acc.add(wnd[-z - 1 >> 1].neg());
  29939. }
  29940. }
  29941. return p.type === 'affine' ? acc.toP() : acc;
  29942. };
  29943. BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, len, jacobianResult) {
  29944. var wndWidth = this._wnafT1;
  29945. var wnd = this._wnafT2;
  29946. var naf = this._wnafT3;
  29947. // Fill all arrays
  29948. var max = 0;
  29949. var i;
  29950. var j;
  29951. var p;
  29952. for (i = 0; i < len; i++) {
  29953. p = points[i];
  29954. var nafPoints = p._getNAFPoints(defW);
  29955. wndWidth[i] = nafPoints.wnd;
  29956. wnd[i] = nafPoints.points;
  29957. }
  29958. // Comb small window NAFs
  29959. for (i = len - 1; i >= 1; i -= 2) {
  29960. var a = i - 1;
  29961. var b = i;
  29962. if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
  29963. naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);
  29964. naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);
  29965. max = Math.max(naf[a].length, max);
  29966. max = Math.max(naf[b].length, max);
  29967. continue;
  29968. }
  29969. var comb = [points[a], /* 1 */
  29970. null, /* 3 */
  29971. null, /* 5 */
  29972. points[b] /* 7 */];
  29973. // Try to avoid Projective points, if possible
  29974. if (points[a].y.cmp(points[b].y) === 0) {
  29975. comb[1] = points[a].add(points[b]);
  29976. comb[2] = points[a].toJ().mixedAdd(points[b].neg());
  29977. } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
  29978. comb[1] = points[a].toJ().mixedAdd(points[b]);
  29979. comb[2] = points[a].add(points[b].neg());
  29980. } else {
  29981. comb[1] = points[a].toJ().mixedAdd(points[b]);
  29982. comb[2] = points[a].toJ().mixedAdd(points[b].neg());
  29983. }
  29984. var index = [-3, /* -1 -1 */
  29985. -1, /* -1 0 */
  29986. -5, /* -1 1 */
  29987. -7, /* 0 -1 */
  29988. 0, /* 0 0 */
  29989. 7, /* 0 1 */
  29990. 5, /* 1 -1 */
  29991. 1, /* 1 0 */
  29992. 3 /* 1 1 */];
  29993. var jsf = getJSF(coeffs[a], coeffs[b]);
  29994. max = Math.max(jsf[0].length, max);
  29995. naf[a] = new Array(max);
  29996. naf[b] = new Array(max);
  29997. for (j = 0; j < max; j++) {
  29998. var ja = jsf[0][j] | 0;
  29999. var jb = jsf[1][j] | 0;
  30000. naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
  30001. naf[b][j] = 0;
  30002. wnd[a] = comb;
  30003. }
  30004. }
  30005. var acc = this.jpoint(null, null, null);
  30006. var tmp = this._wnafT4;
  30007. for (i = max; i >= 0; i--) {
  30008. var k = 0;
  30009. while (i >= 0) {
  30010. var zero = true;
  30011. for (j = 0; j < len; j++) {
  30012. tmp[j] = naf[j][i] | 0;
  30013. if (tmp[j] !== 0) zero = false;
  30014. }
  30015. if (!zero) break;
  30016. k++;
  30017. i--;
  30018. }
  30019. if (i >= 0) k++;
  30020. acc = acc.dblp(k);
  30021. if (i < 0) break;
  30022. for (j = 0; j < len; j++) {
  30023. var z = tmp[j];
  30024. p;
  30025. if (z === 0) continue;else if (z > 0) p = wnd[j][z - 1 >> 1];else if (z < 0) p = wnd[j][-z - 1 >> 1].neg();
  30026. if (p.type === 'affine') acc = acc.mixedAdd(p);else acc = acc.add(p);
  30027. }
  30028. }
  30029. // Zeroify references
  30030. for (i = 0; i < len; i++) wnd[i] = null;
  30031. if (jacobianResult) return acc;else return acc.toP();
  30032. };
  30033. function BasePoint(curve, type) {
  30034. this.curve = curve;
  30035. this.type = type;
  30036. this.precomputed = null;
  30037. }
  30038. BaseCurve.BasePoint = BasePoint;
  30039. BasePoint.prototype.eq = function eq( /*other*/
  30040. ) {
  30041. throw new Error('Not implemented');
  30042. };
  30043. BasePoint.prototype.validate = function validate() {
  30044. return this.curve.validate(this);
  30045. };
  30046. BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  30047. bytes = utils.toArray(bytes, enc);
  30048. var len = this.p.byteLength();
  30049. // uncompressed, hybrid-odd, hybrid-even
  30050. if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && bytes.length - 1 === 2 * len) {
  30051. if (bytes[0] === 0x06) assert(bytes[bytes.length - 1] % 2 === 0);else if (bytes[0] === 0x07) assert(bytes[bytes.length - 1] % 2 === 1);
  30052. var res = this.point(bytes.slice(1, 1 + len), bytes.slice(1 + len, 1 + 2 * len));
  30053. return res;
  30054. } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && bytes.length - 1 === len) {
  30055. return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
  30056. }
  30057. throw new Error('Unknown point format');
  30058. };
  30059. BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
  30060. return this.encode(enc, true);
  30061. };
  30062. BasePoint.prototype._encode = function _encode(compact) {
  30063. var len = this.curve.p.byteLength();
  30064. var x = this.getX().toArray('be', len);
  30065. if (compact) return [this.getY().isEven() ? 0x02 : 0x03].concat(x);
  30066. return [0x04].concat(x, this.getY().toArray('be', len));
  30067. };
  30068. BasePoint.prototype.encode = function encode(enc, compact) {
  30069. return utils.encode(this._encode(compact), enc);
  30070. };
  30071. BasePoint.prototype.precompute = function precompute(power) {
  30072. if (this.precomputed) return this;
  30073. var precomputed = {
  30074. doubles: null,
  30075. naf: null,
  30076. beta: null
  30077. };
  30078. precomputed.naf = this._getNAFPoints(8);
  30079. precomputed.doubles = this._getDoubles(4, power);
  30080. precomputed.beta = this._getBeta();
  30081. this.precomputed = precomputed;
  30082. return this;
  30083. };
  30084. BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
  30085. if (!this.precomputed) return false;
  30086. var doubles = this.precomputed.doubles;
  30087. if (!doubles) return false;
  30088. return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
  30089. };
  30090. BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
  30091. if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles;
  30092. var doubles = [this];
  30093. var acc = this;
  30094. for (var i = 0; i < power; i += step) {
  30095. for (var j = 0; j < step; j++) acc = acc.dbl();
  30096. doubles.push(acc);
  30097. }
  30098. return {
  30099. step: step,
  30100. points: doubles
  30101. };
  30102. };
  30103. BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
  30104. if (this.precomputed && this.precomputed.naf) return this.precomputed.naf;
  30105. var res = [this];
  30106. var max = (1 << wnd) - 1;
  30107. var dbl = max === 1 ? null : this.dbl();
  30108. for (var i = 1; i < max; i++) res[i] = res[i - 1].add(dbl);
  30109. return {
  30110. wnd: wnd,
  30111. points: res
  30112. };
  30113. };
  30114. BasePoint.prototype._getBeta = function _getBeta() {
  30115. return null;
  30116. };
  30117. BasePoint.prototype.dblp = function dblp(k) {
  30118. var r = this;
  30119. for (var i = 0; i < k; i++) r = r.dbl();
  30120. return r;
  30121. };
  30122. },{"../utils":258,"bn.js":259}],246:[function(require,module,exports){
  30123. 'use strict';
  30124. var utils = require('../utils');
  30125. var BN = require('bn.js');
  30126. var inherits = require('inherits');
  30127. var Base = require('./base');
  30128. var assert = utils.assert;
  30129. function EdwardsCurve(conf) {
  30130. // NOTE: Important as we are creating point in Base.call()
  30131. this.twisted = (conf.a | 0) !== 1;
  30132. this.mOneA = this.twisted && (conf.a | 0) === -1;
  30133. this.extended = this.mOneA;
  30134. Base.call(this, 'edwards', conf);
  30135. this.a = new BN(conf.a, 16).umod(this.red.m);
  30136. this.a = this.a.toRed(this.red);
  30137. this.c = new BN(conf.c, 16).toRed(this.red);
  30138. this.c2 = this.c.redSqr();
  30139. this.d = new BN(conf.d, 16).toRed(this.red);
  30140. this.dd = this.d.redAdd(this.d);
  30141. assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
  30142. this.oneC = (conf.c | 0) === 1;
  30143. }
  30144. inherits(EdwardsCurve, Base);
  30145. module.exports = EdwardsCurve;
  30146. EdwardsCurve.prototype._mulA = function _mulA(num) {
  30147. if (this.mOneA) return num.redNeg();else return this.a.redMul(num);
  30148. };
  30149. EdwardsCurve.prototype._mulC = function _mulC(num) {
  30150. if (this.oneC) return num;else return this.c.redMul(num);
  30151. };
  30152. // Just for compatibility with Short curve
  30153. EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
  30154. return this.point(x, y, z, t);
  30155. };
  30156. EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
  30157. x = new BN(x, 16);
  30158. if (!x.red) x = x.toRed(this.red);
  30159. var x2 = x.redSqr();
  30160. var rhs = this.c2.redSub(this.a.redMul(x2));
  30161. var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
  30162. var y2 = rhs.redMul(lhs.redInvm());
  30163. var y = y2.redSqrt();
  30164. if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error('invalid point');
  30165. var isOdd = y.fromRed().isOdd();
  30166. if (odd && !isOdd || !odd && isOdd) y = y.redNeg();
  30167. return this.point(x, y);
  30168. };
  30169. EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
  30170. y = new BN(y, 16);
  30171. if (!y.red) y = y.toRed(this.red);
  30172. // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
  30173. var y2 = y.redSqr();
  30174. var lhs = y2.redSub(this.c2);
  30175. var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
  30176. var x2 = lhs.redMul(rhs.redInvm());
  30177. if (x2.cmp(this.zero) === 0) {
  30178. if (odd) throw new Error('invalid point');else return this.point(this.zero, y);
  30179. }
  30180. var x = x2.redSqrt();
  30181. if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) throw new Error('invalid point');
  30182. if (x.fromRed().isOdd() !== odd) x = x.redNeg();
  30183. return this.point(x, y);
  30184. };
  30185. EdwardsCurve.prototype.validate = function validate(point) {
  30186. if (point.isInfinity()) return true;
  30187. // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
  30188. point.normalize();
  30189. var x2 = point.x.redSqr();
  30190. var y2 = point.y.redSqr();
  30191. var lhs = x2.redMul(this.a).redAdd(y2);
  30192. var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
  30193. return lhs.cmp(rhs) === 0;
  30194. };
  30195. function Point(curve, x, y, z, t) {
  30196. Base.BasePoint.call(this, curve, 'projective');
  30197. if (x === null && y === null && z === null) {
  30198. this.x = this.curve.zero;
  30199. this.y = this.curve.one;
  30200. this.z = this.curve.one;
  30201. this.t = this.curve.zero;
  30202. this.zOne = true;
  30203. } else {
  30204. this.x = new BN(x, 16);
  30205. this.y = new BN(y, 16);
  30206. this.z = z ? new BN(z, 16) : this.curve.one;
  30207. this.t = t && new BN(t, 16);
  30208. if (!this.x.red) this.x = this.x.toRed(this.curve.red);
  30209. if (!this.y.red) this.y = this.y.toRed(this.curve.red);
  30210. if (!this.z.red) this.z = this.z.toRed(this.curve.red);
  30211. if (this.t && !this.t.red) this.t = this.t.toRed(this.curve.red);
  30212. this.zOne = this.z === this.curve.one;
  30213. // Use extended coordinates
  30214. if (this.curve.extended && !this.t) {
  30215. this.t = this.x.redMul(this.y);
  30216. if (!this.zOne) this.t = this.t.redMul(this.z.redInvm());
  30217. }
  30218. }
  30219. }
  30220. inherits(Point, Base.BasePoint);
  30221. EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  30222. return Point.fromJSON(this, obj);
  30223. };
  30224. EdwardsCurve.prototype.point = function point(x, y, z, t) {
  30225. return new Point(this, x, y, z, t);
  30226. };
  30227. Point.fromJSON = function fromJSON(curve, obj) {
  30228. return new Point(curve, obj[0], obj[1], obj[2]);
  30229. };
  30230. Point.prototype.inspect = function inspect() {
  30231. if (this.isInfinity()) return '<EC Point Infinity>';
  30232. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) + ' y: ' + this.y.fromRed().toString(16, 2) + ' z: ' + this.z.fromRed().toString(16, 2) + '>';
  30233. };
  30234. Point.prototype.isInfinity = function isInfinity() {
  30235. // XXX This code assumes that zero is always zero in red
  30236. return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || this.zOne && this.y.cmp(this.curve.c) === 0);
  30237. };
  30238. Point.prototype._extDbl = function _extDbl() {
  30239. // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  30240. // #doubling-dbl-2008-hwcd
  30241. // 4M + 4S
  30242. // A = X1^2
  30243. var a = this.x.redSqr();
  30244. // B = Y1^2
  30245. var b = this.y.redSqr();
  30246. // C = 2 * Z1^2
  30247. var c = this.z.redSqr();
  30248. c = c.redIAdd(c);
  30249. // D = a * A
  30250. var d = this.curve._mulA(a);
  30251. // E = (X1 + Y1)^2 - A - B
  30252. var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
  30253. // G = D + B
  30254. var g = d.redAdd(b);
  30255. // F = G - C
  30256. var f = g.redSub(c);
  30257. // H = D - B
  30258. var h = d.redSub(b);
  30259. // X3 = E * F
  30260. var nx = e.redMul(f);
  30261. // Y3 = G * H
  30262. var ny = g.redMul(h);
  30263. // T3 = E * H
  30264. var nt = e.redMul(h);
  30265. // Z3 = F * G
  30266. var nz = f.redMul(g);
  30267. return this.curve.point(nx, ny, nz, nt);
  30268. };
  30269. Point.prototype._projDbl = function _projDbl() {
  30270. // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  30271. // #doubling-dbl-2008-bbjlp
  30272. // #doubling-dbl-2007-bl
  30273. // and others
  30274. // Generally 3M + 4S or 2M + 4S
  30275. // B = (X1 + Y1)^2
  30276. var b = this.x.redAdd(this.y).redSqr();
  30277. // C = X1^2
  30278. var c = this.x.redSqr();
  30279. // D = Y1^2
  30280. var d = this.y.redSqr();
  30281. var nx;
  30282. var ny;
  30283. var nz;
  30284. var e;
  30285. var h;
  30286. var j;
  30287. if (this.curve.twisted) {
  30288. // E = a * C
  30289. e = this.curve._mulA(c);
  30290. // F = E + D
  30291. var f = e.redAdd(d);
  30292. if (this.zOne) {
  30293. // X3 = (B - C - D) * (F - 2)
  30294. nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
  30295. // Y3 = F * (E - D)
  30296. ny = f.redMul(e.redSub(d));
  30297. // Z3 = F^2 - 2 * F
  30298. nz = f.redSqr().redSub(f).redSub(f);
  30299. } else {
  30300. // H = Z1^2
  30301. h = this.z.redSqr();
  30302. // J = F - 2 * H
  30303. j = f.redSub(h).redISub(h);
  30304. // X3 = (B-C-D)*J
  30305. nx = b.redSub(c).redISub(d).redMul(j);
  30306. // Y3 = F * (E - D)
  30307. ny = f.redMul(e.redSub(d));
  30308. // Z3 = F * J
  30309. nz = f.redMul(j);
  30310. }
  30311. } else {
  30312. // E = C + D
  30313. e = c.redAdd(d);
  30314. // H = (c * Z1)^2
  30315. h = this.curve._mulC(this.z).redSqr();
  30316. // J = E - 2 * H
  30317. j = e.redSub(h).redSub(h);
  30318. // X3 = c * (B - E) * J
  30319. nx = this.curve._mulC(b.redISub(e)).redMul(j);
  30320. // Y3 = c * E * (C - D)
  30321. ny = this.curve._mulC(e).redMul(c.redISub(d));
  30322. // Z3 = E * J
  30323. nz = e.redMul(j);
  30324. }
  30325. return this.curve.point(nx, ny, nz);
  30326. };
  30327. Point.prototype.dbl = function dbl() {
  30328. if (this.isInfinity()) return this;
  30329. // Double in extended coordinates
  30330. if (this.curve.extended) return this._extDbl();else return this._projDbl();
  30331. };
  30332. Point.prototype._extAdd = function _extAdd(p) {
  30333. // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  30334. // #addition-add-2008-hwcd-3
  30335. // 8M
  30336. // A = (Y1 - X1) * (Y2 - X2)
  30337. var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
  30338. // B = (Y1 + X1) * (Y2 + X2)
  30339. var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
  30340. // C = T1 * k * T2
  30341. var c = this.t.redMul(this.curve.dd).redMul(p.t);
  30342. // D = Z1 * 2 * Z2
  30343. var d = this.z.redMul(p.z.redAdd(p.z));
  30344. // E = B - A
  30345. var e = b.redSub(a);
  30346. // F = D - C
  30347. var f = d.redSub(c);
  30348. // G = D + C
  30349. var g = d.redAdd(c);
  30350. // H = B + A
  30351. var h = b.redAdd(a);
  30352. // X3 = E * F
  30353. var nx = e.redMul(f);
  30354. // Y3 = G * H
  30355. var ny = g.redMul(h);
  30356. // T3 = E * H
  30357. var nt = e.redMul(h);
  30358. // Z3 = F * G
  30359. var nz = f.redMul(g);
  30360. return this.curve.point(nx, ny, nz, nt);
  30361. };
  30362. Point.prototype._projAdd = function _projAdd(p) {
  30363. // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  30364. // #addition-add-2008-bbjlp
  30365. // #addition-add-2007-bl
  30366. // 10M + 1S
  30367. // A = Z1 * Z2
  30368. var a = this.z.redMul(p.z);
  30369. // B = A^2
  30370. var b = a.redSqr();
  30371. // C = X1 * X2
  30372. var c = this.x.redMul(p.x);
  30373. // D = Y1 * Y2
  30374. var d = this.y.redMul(p.y);
  30375. // E = d * C * D
  30376. var e = this.curve.d.redMul(c).redMul(d);
  30377. // F = B - E
  30378. var f = b.redSub(e);
  30379. // G = B + E
  30380. var g = b.redAdd(e);
  30381. // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
  30382. var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
  30383. var nx = a.redMul(f).redMul(tmp);
  30384. var ny;
  30385. var nz;
  30386. if (this.curve.twisted) {
  30387. // Y3 = A * G * (D - a * C)
  30388. ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
  30389. // Z3 = F * G
  30390. nz = f.redMul(g);
  30391. } else {
  30392. // Y3 = A * G * (D - C)
  30393. ny = a.redMul(g).redMul(d.redSub(c));
  30394. // Z3 = c * F * G
  30395. nz = this.curve._mulC(f).redMul(g);
  30396. }
  30397. return this.curve.point(nx, ny, nz);
  30398. };
  30399. Point.prototype.add = function add(p) {
  30400. if (this.isInfinity()) return p;
  30401. if (p.isInfinity()) return this;
  30402. if (this.curve.extended) return this._extAdd(p);else return this._projAdd(p);
  30403. };
  30404. Point.prototype.mul = function mul(k) {
  30405. if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k);else return this.curve._wnafMul(this, k);
  30406. };
  30407. Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
  30408. return this.curve._wnafMulAdd(1, [this, p], [k1, k2], 2, false);
  30409. };
  30410. Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
  30411. return this.curve._wnafMulAdd(1, [this, p], [k1, k2], 2, true);
  30412. };
  30413. Point.prototype.normalize = function normalize() {
  30414. if (this.zOne) return this;
  30415. // Normalize coordinates
  30416. var zi = this.z.redInvm();
  30417. this.x = this.x.redMul(zi);
  30418. this.y = this.y.redMul(zi);
  30419. if (this.t) this.t = this.t.redMul(zi);
  30420. this.z = this.curve.one;
  30421. this.zOne = true;
  30422. return this;
  30423. };
  30424. Point.prototype.neg = function neg() {
  30425. return this.curve.point(this.x.redNeg(), this.y, this.z, this.t && this.t.redNeg());
  30426. };
  30427. Point.prototype.getX = function getX() {
  30428. this.normalize();
  30429. return this.x.fromRed();
  30430. };
  30431. Point.prototype.getY = function getY() {
  30432. this.normalize();
  30433. return this.y.fromRed();
  30434. };
  30435. Point.prototype.eq = function eq(other) {
  30436. return this === other || this.getX().cmp(other.getX()) === 0 && this.getY().cmp(other.getY()) === 0;
  30437. };
  30438. Point.prototype.eqXToP = function eqXToP(x) {
  30439. var rx = x.toRed(this.curve.red).redMul(this.z);
  30440. if (this.x.cmp(rx) === 0) return true;
  30441. var xc = x.clone();
  30442. var t = this.curve.redN.redMul(this.z);
  30443. for (;;) {
  30444. xc.iadd(this.curve.n);
  30445. if (xc.cmp(this.curve.p) >= 0) return false;
  30446. rx.redIAdd(t);
  30447. if (this.x.cmp(rx) === 0) return true;
  30448. }
  30449. };
  30450. // Compatibility with BaseCurve
  30451. Point.prototype.toP = Point.prototype.normalize;
  30452. Point.prototype.mixedAdd = Point.prototype.add;
  30453. },{"../utils":258,"./base":245,"bn.js":259,"inherits":279}],247:[function(require,module,exports){
  30454. 'use strict';
  30455. var curve = exports;
  30456. curve.base = require('./base');
  30457. curve.short = require('./short');
  30458. curve.mont = require('./mont');
  30459. curve.edwards = require('./edwards');
  30460. },{"./base":245,"./edwards":246,"./mont":248,"./short":249}],248:[function(require,module,exports){
  30461. 'use strict';
  30462. var BN = require('bn.js');
  30463. var inherits = require('inherits');
  30464. var Base = require('./base');
  30465. var utils = require('../utils');
  30466. function MontCurve(conf) {
  30467. Base.call(this, 'mont', conf);
  30468. this.a = new BN(conf.a, 16).toRed(this.red);
  30469. this.b = new BN(conf.b, 16).toRed(this.red);
  30470. this.i4 = new BN(4).toRed(this.red).redInvm();
  30471. this.two = new BN(2).toRed(this.red);
  30472. this.a24 = this.i4.redMul(this.a.redAdd(this.two));
  30473. }
  30474. inherits(MontCurve, Base);
  30475. module.exports = MontCurve;
  30476. MontCurve.prototype.validate = function validate(point) {
  30477. var x = point.normalize().x;
  30478. var x2 = x.redSqr();
  30479. var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
  30480. var y = rhs.redSqrt();
  30481. return y.redSqr().cmp(rhs) === 0;
  30482. };
  30483. function Point(curve, x, z) {
  30484. Base.BasePoint.call(this, curve, 'projective');
  30485. if (x === null && z === null) {
  30486. this.x = this.curve.one;
  30487. this.z = this.curve.zero;
  30488. } else {
  30489. this.x = new BN(x, 16);
  30490. this.z = new BN(z, 16);
  30491. if (!this.x.red) this.x = this.x.toRed(this.curve.red);
  30492. if (!this.z.red) this.z = this.z.toRed(this.curve.red);
  30493. }
  30494. }
  30495. inherits(Point, Base.BasePoint);
  30496. MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  30497. return this.point(utils.toArray(bytes, enc), 1);
  30498. };
  30499. MontCurve.prototype.point = function point(x, z) {
  30500. return new Point(this, x, z);
  30501. };
  30502. MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  30503. return Point.fromJSON(this, obj);
  30504. };
  30505. Point.prototype.precompute = function precompute() {
  30506. // No-op
  30507. };
  30508. Point.prototype._encode = function _encode() {
  30509. return this.getX().toArray('be', this.curve.p.byteLength());
  30510. };
  30511. Point.fromJSON = function fromJSON(curve, obj) {
  30512. return new Point(curve, obj[0], obj[1] || curve.one);
  30513. };
  30514. Point.prototype.inspect = function inspect() {
  30515. if (this.isInfinity()) return '<EC Point Infinity>';
  30516. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) + ' z: ' + this.z.fromRed().toString(16, 2) + '>';
  30517. };
  30518. Point.prototype.isInfinity = function isInfinity() {
  30519. // XXX This code assumes that zero is always zero in red
  30520. return this.z.cmpn(0) === 0;
  30521. };
  30522. Point.prototype.dbl = function dbl() {
  30523. // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
  30524. // 2M + 2S + 4A
  30525. // A = X1 + Z1
  30526. var a = this.x.redAdd(this.z);
  30527. // AA = A^2
  30528. var aa = a.redSqr();
  30529. // B = X1 - Z1
  30530. var b = this.x.redSub(this.z);
  30531. // BB = B^2
  30532. var bb = b.redSqr();
  30533. // C = AA - BB
  30534. var c = aa.redSub(bb);
  30535. // X3 = AA * BB
  30536. var nx = aa.redMul(bb);
  30537. // Z3 = C * (BB + A24 * C)
  30538. var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
  30539. return this.curve.point(nx, nz);
  30540. };
  30541. Point.prototype.add = function add() {
  30542. throw new Error('Not supported on Montgomery curve');
  30543. };
  30544. Point.prototype.diffAdd = function diffAdd(p, diff) {
  30545. // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
  30546. // 4M + 2S + 6A
  30547. // A = X2 + Z2
  30548. var a = this.x.redAdd(this.z);
  30549. // B = X2 - Z2
  30550. var b = this.x.redSub(this.z);
  30551. // C = X3 + Z3
  30552. var c = p.x.redAdd(p.z);
  30553. // D = X3 - Z3
  30554. var d = p.x.redSub(p.z);
  30555. // DA = D * A
  30556. var da = d.redMul(a);
  30557. // CB = C * B
  30558. var cb = c.redMul(b);
  30559. // X5 = Z1 * (DA + CB)^2
  30560. var nx = diff.z.redMul(da.redAdd(cb).redSqr());
  30561. // Z5 = X1 * (DA - CB)^2
  30562. var nz = diff.x.redMul(da.redISub(cb).redSqr());
  30563. return this.curve.point(nx, nz);
  30564. };
  30565. Point.prototype.mul = function mul(k) {
  30566. var t = k.clone();
  30567. var a = this; // (N / 2) * Q + Q
  30568. var b = this.curve.point(null, null); // (N / 2) * Q
  30569. var c = this; // Q
  30570. for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) bits.push(t.andln(1));
  30571. for (var i = bits.length - 1; i >= 0; i--) {
  30572. if (bits[i] === 0) {
  30573. // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
  30574. a = a.diffAdd(b, c);
  30575. // N * Q = 2 * ((N / 2) * Q + Q))
  30576. b = b.dbl();
  30577. } else {
  30578. // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
  30579. b = a.diffAdd(b, c);
  30580. // N * Q + Q = 2 * ((N / 2) * Q + Q)
  30581. a = a.dbl();
  30582. }
  30583. }
  30584. return b;
  30585. };
  30586. Point.prototype.mulAdd = function mulAdd() {
  30587. throw new Error('Not supported on Montgomery curve');
  30588. };
  30589. Point.prototype.jumlAdd = function jumlAdd() {
  30590. throw new Error('Not supported on Montgomery curve');
  30591. };
  30592. Point.prototype.eq = function eq(other) {
  30593. return this.getX().cmp(other.getX()) === 0;
  30594. };
  30595. Point.prototype.normalize = function normalize() {
  30596. this.x = this.x.redMul(this.z.redInvm());
  30597. this.z = this.curve.one;
  30598. return this;
  30599. };
  30600. Point.prototype.getX = function getX() {
  30601. // Normalize coordinates
  30602. this.normalize();
  30603. return this.x.fromRed();
  30604. };
  30605. },{"../utils":258,"./base":245,"bn.js":259,"inherits":279}],249:[function(require,module,exports){
  30606. 'use strict';
  30607. var utils = require('../utils');
  30608. var BN = require('bn.js');
  30609. var inherits = require('inherits');
  30610. var Base = require('./base');
  30611. var assert = utils.assert;
  30612. function ShortCurve(conf) {
  30613. Base.call(this, 'short', conf);
  30614. this.a = new BN(conf.a, 16).toRed(this.red);
  30615. this.b = new BN(conf.b, 16).toRed(this.red);
  30616. this.tinv = this.two.redInvm();
  30617. this.zeroA = this.a.fromRed().cmpn(0) === 0;
  30618. this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
  30619. // If the curve is endomorphic, precalculate beta and lambda
  30620. this.endo = this._getEndomorphism(conf);
  30621. this._endoWnafT1 = new Array(4);
  30622. this._endoWnafT2 = new Array(4);
  30623. }
  30624. inherits(ShortCurve, Base);
  30625. module.exports = ShortCurve;
  30626. ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
  30627. // No efficient endomorphism
  30628. if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) return;
  30629. // Compute beta and lambda, that lambda * P = (beta * Px; Py)
  30630. var beta;
  30631. var lambda;
  30632. if (conf.beta) {
  30633. beta = new BN(conf.beta, 16).toRed(this.red);
  30634. } else {
  30635. var betas = this._getEndoRoots(this.p);
  30636. // Choose the smallest beta
  30637. beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
  30638. beta = beta.toRed(this.red);
  30639. }
  30640. if (conf.lambda) {
  30641. lambda = new BN(conf.lambda, 16);
  30642. } else {
  30643. // Choose the lambda that is matching selected beta
  30644. var lambdas = this._getEndoRoots(this.n);
  30645. if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
  30646. lambda = lambdas[0];
  30647. } else {
  30648. lambda = lambdas[1];
  30649. assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
  30650. }
  30651. }
  30652. // Get basis vectors, used for balanced length-two representation
  30653. var basis;
  30654. if (conf.basis) {
  30655. basis = conf.basis.map(function (vec) {
  30656. return {
  30657. a: new BN(vec.a, 16),
  30658. b: new BN(vec.b, 16)
  30659. };
  30660. });
  30661. } else {
  30662. basis = this._getEndoBasis(lambda);
  30663. }
  30664. return {
  30665. beta: beta,
  30666. lambda: lambda,
  30667. basis: basis
  30668. };
  30669. };
  30670. ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
  30671. // Find roots of for x^2 + x + 1 in F
  30672. // Root = (-1 +- Sqrt(-3)) / 2
  30673. //
  30674. var red = num === this.p ? this.red : BN.mont(num);
  30675. var tinv = new BN(2).toRed(red).redInvm();
  30676. var ntinv = tinv.redNeg();
  30677. var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
  30678. var l1 = ntinv.redAdd(s).fromRed();
  30679. var l2 = ntinv.redSub(s).fromRed();
  30680. return [l1, l2];
  30681. };
  30682. ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
  30683. // aprxSqrt >= sqrt(this.n)
  30684. var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
  30685. // 3.74
  30686. // Run EGCD, until r(L + 1) < aprxSqrt
  30687. var u = lambda;
  30688. var v = this.n.clone();
  30689. var x1 = new BN(1);
  30690. var y1 = new BN(0);
  30691. var x2 = new BN(0);
  30692. var y2 = new BN(1);
  30693. // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
  30694. var a0;
  30695. var b0;
  30696. // First vector
  30697. var a1;
  30698. var b1;
  30699. // Second vector
  30700. var a2;
  30701. var b2;
  30702. var prevR;
  30703. var i = 0;
  30704. var r;
  30705. var x;
  30706. while (u.cmpn(0) !== 0) {
  30707. var q = v.div(u);
  30708. r = v.sub(q.mul(u));
  30709. x = x2.sub(q.mul(x1));
  30710. var y = y2.sub(q.mul(y1));
  30711. if (!a1 && r.cmp(aprxSqrt) < 0) {
  30712. a0 = prevR.neg();
  30713. b0 = x1;
  30714. a1 = r.neg();
  30715. b1 = x;
  30716. } else if (a1 && ++i === 2) {
  30717. break;
  30718. }
  30719. prevR = r;
  30720. v = u;
  30721. u = r;
  30722. x2 = x1;
  30723. x1 = x;
  30724. y2 = y1;
  30725. y1 = y;
  30726. }
  30727. a2 = r.neg();
  30728. b2 = x;
  30729. var len1 = a1.sqr().add(b1.sqr());
  30730. var len2 = a2.sqr().add(b2.sqr());
  30731. if (len2.cmp(len1) >= 0) {
  30732. a2 = a0;
  30733. b2 = b0;
  30734. }
  30735. // Normalize signs
  30736. if (a1.negative) {
  30737. a1 = a1.neg();
  30738. b1 = b1.neg();
  30739. }
  30740. if (a2.negative) {
  30741. a2 = a2.neg();
  30742. b2 = b2.neg();
  30743. }
  30744. return [{
  30745. a: a1,
  30746. b: b1
  30747. }, {
  30748. a: a2,
  30749. b: b2
  30750. }];
  30751. };
  30752. ShortCurve.prototype._endoSplit = function _endoSplit(k) {
  30753. var basis = this.endo.basis;
  30754. var v1 = basis[0];
  30755. var v2 = basis[1];
  30756. var c1 = v2.b.mul(k).divRound(this.n);
  30757. var c2 = v1.b.neg().mul(k).divRound(this.n);
  30758. var p1 = c1.mul(v1.a);
  30759. var p2 = c2.mul(v2.a);
  30760. var q1 = c1.mul(v1.b);
  30761. var q2 = c2.mul(v2.b);
  30762. // Calculate answer
  30763. var k1 = k.sub(p1).sub(p2);
  30764. var k2 = q1.add(q2).neg();
  30765. return {
  30766. k1: k1,
  30767. k2: k2
  30768. };
  30769. };
  30770. ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
  30771. x = new BN(x, 16);
  30772. if (!x.red) x = x.toRed(this.red);
  30773. var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
  30774. var y = y2.redSqrt();
  30775. if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error('invalid point');
  30776. // XXX Is there any way to tell if the number is odd without converting it
  30777. // to non-red form?
  30778. var isOdd = y.fromRed().isOdd();
  30779. if (odd && !isOdd || !odd && isOdd) y = y.redNeg();
  30780. return this.point(x, y);
  30781. };
  30782. ShortCurve.prototype.validate = function validate(point) {
  30783. if (point.inf) return true;
  30784. var x = point.x;
  30785. var y = point.y;
  30786. var ax = this.a.redMul(x);
  30787. var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
  30788. return y.redSqr().redISub(rhs).cmpn(0) === 0;
  30789. };
  30790. ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs, jacobianResult) {
  30791. var npoints = this._endoWnafT1;
  30792. var ncoeffs = this._endoWnafT2;
  30793. for (var i = 0; i < points.length; i++) {
  30794. var split = this._endoSplit(coeffs[i]);
  30795. var p = points[i];
  30796. var beta = p._getBeta();
  30797. if (split.k1.negative) {
  30798. split.k1.ineg();
  30799. p = p.neg(true);
  30800. }
  30801. if (split.k2.negative) {
  30802. split.k2.ineg();
  30803. beta = beta.neg(true);
  30804. }
  30805. npoints[i * 2] = p;
  30806. npoints[i * 2 + 1] = beta;
  30807. ncoeffs[i * 2] = split.k1;
  30808. ncoeffs[i * 2 + 1] = split.k2;
  30809. }
  30810. var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
  30811. // Clean-up references to points and coefficients
  30812. for (var j = 0; j < i * 2; j++) {
  30813. npoints[j] = null;
  30814. ncoeffs[j] = null;
  30815. }
  30816. return res;
  30817. };
  30818. function Point(curve, x, y, isRed) {
  30819. Base.BasePoint.call(this, curve, 'affine');
  30820. if (x === null && y === null) {
  30821. this.x = null;
  30822. this.y = null;
  30823. this.inf = true;
  30824. } else {
  30825. this.x = new BN(x, 16);
  30826. this.y = new BN(y, 16);
  30827. // Force redgomery representation when loading from JSON
  30828. if (isRed) {
  30829. this.x.forceRed(this.curve.red);
  30830. this.y.forceRed(this.curve.red);
  30831. }
  30832. if (!this.x.red) this.x = this.x.toRed(this.curve.red);
  30833. if (!this.y.red) this.y = this.y.toRed(this.curve.red);
  30834. this.inf = false;
  30835. }
  30836. }
  30837. inherits(Point, Base.BasePoint);
  30838. ShortCurve.prototype.point = function point(x, y, isRed) {
  30839. return new Point(this, x, y, isRed);
  30840. };
  30841. ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
  30842. return Point.fromJSON(this, obj, red);
  30843. };
  30844. Point.prototype._getBeta = function _getBeta() {
  30845. if (!this.curve.endo) return;
  30846. var pre = this.precomputed;
  30847. if (pre && pre.beta) return pre.beta;
  30848. var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
  30849. if (pre) {
  30850. var curve = this.curve;
  30851. var endoMul = function (p) {
  30852. return curve.point(p.x.redMul(curve.endo.beta), p.y);
  30853. };
  30854. pre.beta = beta;
  30855. beta.precomputed = {
  30856. beta: null,
  30857. naf: pre.naf && {
  30858. wnd: pre.naf.wnd,
  30859. points: pre.naf.points.map(endoMul)
  30860. },
  30861. doubles: pre.doubles && {
  30862. step: pre.doubles.step,
  30863. points: pre.doubles.points.map(endoMul)
  30864. }
  30865. };
  30866. }
  30867. return beta;
  30868. };
  30869. Point.prototype.toJSON = function toJSON() {
  30870. if (!this.precomputed) return [this.x, this.y];
  30871. return [this.x, this.y, this.precomputed && {
  30872. doubles: this.precomputed.doubles && {
  30873. step: this.precomputed.doubles.step,
  30874. points: this.precomputed.doubles.points.slice(1)
  30875. },
  30876. naf: this.precomputed.naf && {
  30877. wnd: this.precomputed.naf.wnd,
  30878. points: this.precomputed.naf.points.slice(1)
  30879. }
  30880. }];
  30881. };
  30882. Point.fromJSON = function fromJSON(curve, obj, red) {
  30883. if (typeof obj === 'string') obj = JSON.parse(obj);
  30884. var res = curve.point(obj[0], obj[1], red);
  30885. if (!obj[2]) return res;
  30886. function obj2point(obj) {
  30887. return curve.point(obj[0], obj[1], red);
  30888. }
  30889. var pre = obj[2];
  30890. res.precomputed = {
  30891. beta: null,
  30892. doubles: pre.doubles && {
  30893. step: pre.doubles.step,
  30894. points: [res].concat(pre.doubles.points.map(obj2point))
  30895. },
  30896. naf: pre.naf && {
  30897. wnd: pre.naf.wnd,
  30898. points: [res].concat(pre.naf.points.map(obj2point))
  30899. }
  30900. };
  30901. return res;
  30902. };
  30903. Point.prototype.inspect = function inspect() {
  30904. if (this.isInfinity()) return '<EC Point Infinity>';
  30905. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) + ' y: ' + this.y.fromRed().toString(16, 2) + '>';
  30906. };
  30907. Point.prototype.isInfinity = function isInfinity() {
  30908. return this.inf;
  30909. };
  30910. Point.prototype.add = function add(p) {
  30911. // O + P = P
  30912. if (this.inf) return p;
  30913. // P + O = P
  30914. if (p.inf) return this;
  30915. // P + P = 2P
  30916. if (this.eq(p)) return this.dbl();
  30917. // P + (-P) = O
  30918. if (this.neg().eq(p)) return this.curve.point(null, null);
  30919. // P + Q = O
  30920. if (this.x.cmp(p.x) === 0) return this.curve.point(null, null);
  30921. var c = this.y.redSub(p.y);
  30922. if (c.cmpn(0) !== 0) c = c.redMul(this.x.redSub(p.x).redInvm());
  30923. var nx = c.redSqr().redISub(this.x).redISub(p.x);
  30924. var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  30925. return this.curve.point(nx, ny);
  30926. };
  30927. Point.prototype.dbl = function dbl() {
  30928. if (this.inf) return this;
  30929. // 2P = O
  30930. var ys1 = this.y.redAdd(this.y);
  30931. if (ys1.cmpn(0) === 0) return this.curve.point(null, null);
  30932. var a = this.curve.a;
  30933. var x2 = this.x.redSqr();
  30934. var dyinv = ys1.redInvm();
  30935. var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
  30936. var nx = c.redSqr().redISub(this.x.redAdd(this.x));
  30937. var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  30938. return this.curve.point(nx, ny);
  30939. };
  30940. Point.prototype.getX = function getX() {
  30941. return this.x.fromRed();
  30942. };
  30943. Point.prototype.getY = function getY() {
  30944. return this.y.fromRed();
  30945. };
  30946. Point.prototype.mul = function mul(k) {
  30947. k = new BN(k, 16);
  30948. if (this.isInfinity()) return this;else if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k);else if (this.curve.endo) return this.curve._endoWnafMulAdd([this], [k]);else return this.curve._wnafMul(this, k);
  30949. };
  30950. Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
  30951. var points = [this, p2];
  30952. var coeffs = [k1, k2];
  30953. if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs);else return this.curve._wnafMulAdd(1, points, coeffs, 2);
  30954. };
  30955. Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
  30956. var points = [this, p2];
  30957. var coeffs = [k1, k2];
  30958. if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs, true);else return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
  30959. };
  30960. Point.prototype.eq = function eq(p) {
  30961. return this === p || this.inf === p.inf && (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
  30962. };
  30963. Point.prototype.neg = function neg(_precompute) {
  30964. if (this.inf) return this;
  30965. var res = this.curve.point(this.x, this.y.redNeg());
  30966. if (_precompute && this.precomputed) {
  30967. var pre = this.precomputed;
  30968. var negate = function (p) {
  30969. return p.neg();
  30970. };
  30971. res.precomputed = {
  30972. naf: pre.naf && {
  30973. wnd: pre.naf.wnd,
  30974. points: pre.naf.points.map(negate)
  30975. },
  30976. doubles: pre.doubles && {
  30977. step: pre.doubles.step,
  30978. points: pre.doubles.points.map(negate)
  30979. }
  30980. };
  30981. }
  30982. return res;
  30983. };
  30984. Point.prototype.toJ = function toJ() {
  30985. if (this.inf) return this.curve.jpoint(null, null, null);
  30986. var res = this.curve.jpoint(this.x, this.y, this.curve.one);
  30987. return res;
  30988. };
  30989. function JPoint(curve, x, y, z) {
  30990. Base.BasePoint.call(this, curve, 'jacobian');
  30991. if (x === null && y === null && z === null) {
  30992. this.x = this.curve.one;
  30993. this.y = this.curve.one;
  30994. this.z = new BN(0);
  30995. } else {
  30996. this.x = new BN(x, 16);
  30997. this.y = new BN(y, 16);
  30998. this.z = new BN(z, 16);
  30999. }
  31000. if (!this.x.red) this.x = this.x.toRed(this.curve.red);
  31001. if (!this.y.red) this.y = this.y.toRed(this.curve.red);
  31002. if (!this.z.red) this.z = this.z.toRed(this.curve.red);
  31003. this.zOne = this.z === this.curve.one;
  31004. }
  31005. inherits(JPoint, Base.BasePoint);
  31006. ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
  31007. return new JPoint(this, x, y, z);
  31008. };
  31009. JPoint.prototype.toP = function toP() {
  31010. if (this.isInfinity()) return this.curve.point(null, null);
  31011. var zinv = this.z.redInvm();
  31012. var zinv2 = zinv.redSqr();
  31013. var ax = this.x.redMul(zinv2);
  31014. var ay = this.y.redMul(zinv2).redMul(zinv);
  31015. return this.curve.point(ax, ay);
  31016. };
  31017. JPoint.prototype.neg = function neg() {
  31018. return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
  31019. };
  31020. JPoint.prototype.add = function add(p) {
  31021. // O + P = P
  31022. if (this.isInfinity()) return p;
  31023. // P + O = P
  31024. if (p.isInfinity()) return this;
  31025. // 12M + 4S + 7A
  31026. var pz2 = p.z.redSqr();
  31027. var z2 = this.z.redSqr();
  31028. var u1 = this.x.redMul(pz2);
  31029. var u2 = p.x.redMul(z2);
  31030. var s1 = this.y.redMul(pz2.redMul(p.z));
  31031. var s2 = p.y.redMul(z2.redMul(this.z));
  31032. var h = u1.redSub(u2);
  31033. var r = s1.redSub(s2);
  31034. if (h.cmpn(0) === 0) {
  31035. if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null);else return this.dbl();
  31036. }
  31037. var h2 = h.redSqr();
  31038. var h3 = h2.redMul(h);
  31039. var v = u1.redMul(h2);
  31040. var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  31041. var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  31042. var nz = this.z.redMul(p.z).redMul(h);
  31043. return this.curve.jpoint(nx, ny, nz);
  31044. };
  31045. JPoint.prototype.mixedAdd = function mixedAdd(p) {
  31046. // O + P = P
  31047. if (this.isInfinity()) return p.toJ();
  31048. // P + O = P
  31049. if (p.isInfinity()) return this;
  31050. // 8M + 3S + 7A
  31051. var z2 = this.z.redSqr();
  31052. var u1 = this.x;
  31053. var u2 = p.x.redMul(z2);
  31054. var s1 = this.y;
  31055. var s2 = p.y.redMul(z2).redMul(this.z);
  31056. var h = u1.redSub(u2);
  31057. var r = s1.redSub(s2);
  31058. if (h.cmpn(0) === 0) {
  31059. if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null);else return this.dbl();
  31060. }
  31061. var h2 = h.redSqr();
  31062. var h3 = h2.redMul(h);
  31063. var v = u1.redMul(h2);
  31064. var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  31065. var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  31066. var nz = this.z.redMul(h);
  31067. return this.curve.jpoint(nx, ny, nz);
  31068. };
  31069. JPoint.prototype.dblp = function dblp(pow) {
  31070. if (pow === 0) return this;
  31071. if (this.isInfinity()) return this;
  31072. if (!pow) return this.dbl();
  31073. var i;
  31074. if (this.curve.zeroA || this.curve.threeA) {
  31075. var r = this;
  31076. for (i = 0; i < pow; i++) r = r.dbl();
  31077. return r;
  31078. }
  31079. // 1M + 2S + 1A + N * (4S + 5M + 8A)
  31080. // N = 1 => 6M + 6S + 9A
  31081. var a = this.curve.a;
  31082. var tinv = this.curve.tinv;
  31083. var jx = this.x;
  31084. var jy = this.y;
  31085. var jz = this.z;
  31086. var jz4 = jz.redSqr().redSqr();
  31087. // Reuse results
  31088. var jyd = jy.redAdd(jy);
  31089. for (i = 0; i < pow; i++) {
  31090. var jx2 = jx.redSqr();
  31091. var jyd2 = jyd.redSqr();
  31092. var jyd4 = jyd2.redSqr();
  31093. var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
  31094. var t1 = jx.redMul(jyd2);
  31095. var nx = c.redSqr().redISub(t1.redAdd(t1));
  31096. var t2 = t1.redISub(nx);
  31097. var dny = c.redMul(t2);
  31098. dny = dny.redIAdd(dny).redISub(jyd4);
  31099. var nz = jyd.redMul(jz);
  31100. if (i + 1 < pow) jz4 = jz4.redMul(jyd4);
  31101. jx = nx;
  31102. jz = nz;
  31103. jyd = dny;
  31104. }
  31105. return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
  31106. };
  31107. JPoint.prototype.dbl = function dbl() {
  31108. if (this.isInfinity()) return this;
  31109. if (this.curve.zeroA) return this._zeroDbl();else if (this.curve.threeA) return this._threeDbl();else return this._dbl();
  31110. };
  31111. JPoint.prototype._zeroDbl = function _zeroDbl() {
  31112. var nx;
  31113. var ny;
  31114. var nz;
  31115. // Z = 1
  31116. if (this.zOne) {
  31117. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
  31118. // #doubling-mdbl-2007-bl
  31119. // 1M + 5S + 14A
  31120. // XX = X1^2
  31121. var xx = this.x.redSqr();
  31122. // YY = Y1^2
  31123. var yy = this.y.redSqr();
  31124. // YYYY = YY^2
  31125. var yyyy = yy.redSqr();
  31126. // S = 2 * ((X1 + YY)^2 - XX - YYYY)
  31127. var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  31128. s = s.redIAdd(s);
  31129. // M = 3 * XX + a; a = 0
  31130. var m = xx.redAdd(xx).redIAdd(xx);
  31131. // T = M ^ 2 - 2*S
  31132. var t = m.redSqr().redISub(s).redISub(s);
  31133. // 8 * YYYY
  31134. var yyyy8 = yyyy.redIAdd(yyyy);
  31135. yyyy8 = yyyy8.redIAdd(yyyy8);
  31136. yyyy8 = yyyy8.redIAdd(yyyy8);
  31137. // X3 = T
  31138. nx = t;
  31139. // Y3 = M * (S - T) - 8 * YYYY
  31140. ny = m.redMul(s.redISub(t)).redISub(yyyy8);
  31141. // Z3 = 2*Y1
  31142. nz = this.y.redAdd(this.y);
  31143. } else {
  31144. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
  31145. // #doubling-dbl-2009-l
  31146. // 2M + 5S + 13A
  31147. // A = X1^2
  31148. var a = this.x.redSqr();
  31149. // B = Y1^2
  31150. var b = this.y.redSqr();
  31151. // C = B^2
  31152. var c = b.redSqr();
  31153. // D = 2 * ((X1 + B)^2 - A - C)
  31154. var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
  31155. d = d.redIAdd(d);
  31156. // E = 3 * A
  31157. var e = a.redAdd(a).redIAdd(a);
  31158. // F = E^2
  31159. var f = e.redSqr();
  31160. // 8 * C
  31161. var c8 = c.redIAdd(c);
  31162. c8 = c8.redIAdd(c8);
  31163. c8 = c8.redIAdd(c8);
  31164. // X3 = F - 2 * D
  31165. nx = f.redISub(d).redISub(d);
  31166. // Y3 = E * (D - X3) - 8 * C
  31167. ny = e.redMul(d.redISub(nx)).redISub(c8);
  31168. // Z3 = 2 * Y1 * Z1
  31169. nz = this.y.redMul(this.z);
  31170. nz = nz.redIAdd(nz);
  31171. }
  31172. return this.curve.jpoint(nx, ny, nz);
  31173. };
  31174. JPoint.prototype._threeDbl = function _threeDbl() {
  31175. var nx;
  31176. var ny;
  31177. var nz;
  31178. // Z = 1
  31179. if (this.zOne) {
  31180. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
  31181. // #doubling-mdbl-2007-bl
  31182. // 1M + 5S + 15A
  31183. // XX = X1^2
  31184. var xx = this.x.redSqr();
  31185. // YY = Y1^2
  31186. var yy = this.y.redSqr();
  31187. // YYYY = YY^2
  31188. var yyyy = yy.redSqr();
  31189. // S = 2 * ((X1 + YY)^2 - XX - YYYY)
  31190. var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  31191. s = s.redIAdd(s);
  31192. // M = 3 * XX + a
  31193. var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
  31194. // T = M^2 - 2 * S
  31195. var t = m.redSqr().redISub(s).redISub(s);
  31196. // X3 = T
  31197. nx = t;
  31198. // Y3 = M * (S - T) - 8 * YYYY
  31199. var yyyy8 = yyyy.redIAdd(yyyy);
  31200. yyyy8 = yyyy8.redIAdd(yyyy8);
  31201. yyyy8 = yyyy8.redIAdd(yyyy8);
  31202. ny = m.redMul(s.redISub(t)).redISub(yyyy8);
  31203. // Z3 = 2 * Y1
  31204. nz = this.y.redAdd(this.y);
  31205. } else {
  31206. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
  31207. // 3M + 5S
  31208. // delta = Z1^2
  31209. var delta = this.z.redSqr();
  31210. // gamma = Y1^2
  31211. var gamma = this.y.redSqr();
  31212. // beta = X1 * gamma
  31213. var beta = this.x.redMul(gamma);
  31214. // alpha = 3 * (X1 - delta) * (X1 + delta)
  31215. var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
  31216. alpha = alpha.redAdd(alpha).redIAdd(alpha);
  31217. // X3 = alpha^2 - 8 * beta
  31218. var beta4 = beta.redIAdd(beta);
  31219. beta4 = beta4.redIAdd(beta4);
  31220. var beta8 = beta4.redAdd(beta4);
  31221. nx = alpha.redSqr().redISub(beta8);
  31222. // Z3 = (Y1 + Z1)^2 - gamma - delta
  31223. nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
  31224. // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
  31225. var ggamma8 = gamma.redSqr();
  31226. ggamma8 = ggamma8.redIAdd(ggamma8);
  31227. ggamma8 = ggamma8.redIAdd(ggamma8);
  31228. ggamma8 = ggamma8.redIAdd(ggamma8);
  31229. ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
  31230. }
  31231. return this.curve.jpoint(nx, ny, nz);
  31232. };
  31233. JPoint.prototype._dbl = function _dbl() {
  31234. var a = this.curve.a;
  31235. // 4M + 6S + 10A
  31236. var jx = this.x;
  31237. var jy = this.y;
  31238. var jz = this.z;
  31239. var jz4 = jz.redSqr().redSqr();
  31240. var jx2 = jx.redSqr();
  31241. var jy2 = jy.redSqr();
  31242. var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
  31243. var jxd4 = jx.redAdd(jx);
  31244. jxd4 = jxd4.redIAdd(jxd4);
  31245. var t1 = jxd4.redMul(jy2);
  31246. var nx = c.redSqr().redISub(t1.redAdd(t1));
  31247. var t2 = t1.redISub(nx);
  31248. var jyd8 = jy2.redSqr();
  31249. jyd8 = jyd8.redIAdd(jyd8);
  31250. jyd8 = jyd8.redIAdd(jyd8);
  31251. jyd8 = jyd8.redIAdd(jyd8);
  31252. var ny = c.redMul(t2).redISub(jyd8);
  31253. var nz = jy.redAdd(jy).redMul(jz);
  31254. return this.curve.jpoint(nx, ny, nz);
  31255. };
  31256. JPoint.prototype.trpl = function trpl() {
  31257. if (!this.curve.zeroA) return this.dbl().add(this);
  31258. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
  31259. // 5M + 10S + ...
  31260. // XX = X1^2
  31261. var xx = this.x.redSqr();
  31262. // YY = Y1^2
  31263. var yy = this.y.redSqr();
  31264. // ZZ = Z1^2
  31265. var zz = this.z.redSqr();
  31266. // YYYY = YY^2
  31267. var yyyy = yy.redSqr();
  31268. // M = 3 * XX + a * ZZ2; a = 0
  31269. var m = xx.redAdd(xx).redIAdd(xx);
  31270. // MM = M^2
  31271. var mm = m.redSqr();
  31272. // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
  31273. var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  31274. e = e.redIAdd(e);
  31275. e = e.redAdd(e).redIAdd(e);
  31276. e = e.redISub(mm);
  31277. // EE = E^2
  31278. var ee = e.redSqr();
  31279. // T = 16*YYYY
  31280. var t = yyyy.redIAdd(yyyy);
  31281. t = t.redIAdd(t);
  31282. t = t.redIAdd(t);
  31283. t = t.redIAdd(t);
  31284. // U = (M + E)^2 - MM - EE - T
  31285. var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
  31286. // X3 = 4 * (X1 * EE - 4 * YY * U)
  31287. var yyu4 = yy.redMul(u);
  31288. yyu4 = yyu4.redIAdd(yyu4);
  31289. yyu4 = yyu4.redIAdd(yyu4);
  31290. var nx = this.x.redMul(ee).redISub(yyu4);
  31291. nx = nx.redIAdd(nx);
  31292. nx = nx.redIAdd(nx);
  31293. // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
  31294. var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
  31295. ny = ny.redIAdd(ny);
  31296. ny = ny.redIAdd(ny);
  31297. ny = ny.redIAdd(ny);
  31298. // Z3 = (Z1 + E)^2 - ZZ - EE
  31299. var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
  31300. return this.curve.jpoint(nx, ny, nz);
  31301. };
  31302. JPoint.prototype.mul = function mul(k, kbase) {
  31303. k = new BN(k, kbase);
  31304. return this.curve._wnafMul(this, k);
  31305. };
  31306. JPoint.prototype.eq = function eq(p) {
  31307. if (p.type === 'affine') return this.eq(p.toJ());
  31308. if (this === p) return true;
  31309. // x1 * z2^2 == x2 * z1^2
  31310. var z2 = this.z.redSqr();
  31311. var pz2 = p.z.redSqr();
  31312. if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) return false;
  31313. // y1 * z2^3 == y2 * z1^3
  31314. var z3 = z2.redMul(this.z);
  31315. var pz3 = pz2.redMul(p.z);
  31316. return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
  31317. };
  31318. JPoint.prototype.eqXToP = function eqXToP(x) {
  31319. var zs = this.z.redSqr();
  31320. var rx = x.toRed(this.curve.red).redMul(zs);
  31321. if (this.x.cmp(rx) === 0) return true;
  31322. var xc = x.clone();
  31323. var t = this.curve.redN.redMul(zs);
  31324. for (;;) {
  31325. xc.iadd(this.curve.n);
  31326. if (xc.cmp(this.curve.p) >= 0) return false;
  31327. rx.redIAdd(t);
  31328. if (this.x.cmp(rx) === 0) return true;
  31329. }
  31330. };
  31331. JPoint.prototype.inspect = function inspect() {
  31332. if (this.isInfinity()) return '<EC JPoint Infinity>';
  31333. return '<EC JPoint x: ' + this.x.toString(16, 2) + ' y: ' + this.y.toString(16, 2) + ' z: ' + this.z.toString(16, 2) + '>';
  31334. };
  31335. JPoint.prototype.isInfinity = function isInfinity() {
  31336. // XXX This code assumes that zero is always zero in red
  31337. return this.z.cmpn(0) === 0;
  31338. };
  31339. },{"../utils":258,"./base":245,"bn.js":259,"inherits":279}],250:[function(require,module,exports){
  31340. 'use strict';
  31341. var curves = exports;
  31342. var hash = require('hash.js');
  31343. var curve = require('./curve');
  31344. var utils = require('./utils');
  31345. var assert = utils.assert;
  31346. function PresetCurve(options) {
  31347. if (options.type === 'short') this.curve = new curve.short(options);else if (options.type === 'edwards') this.curve = new curve.edwards(options);else this.curve = new curve.mont(options);
  31348. this.g = this.curve.g;
  31349. this.n = this.curve.n;
  31350. this.hash = options.hash;
  31351. assert(this.g.validate(), 'Invalid curve');
  31352. assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
  31353. }
  31354. curves.PresetCurve = PresetCurve;
  31355. function defineCurve(name, options) {
  31356. Object.defineProperty(curves, name, {
  31357. configurable: true,
  31358. enumerable: true,
  31359. get: function () {
  31360. var curve = new PresetCurve(options);
  31361. Object.defineProperty(curves, name, {
  31362. configurable: true,
  31363. enumerable: true,
  31364. value: curve
  31365. });
  31366. return curve;
  31367. }
  31368. });
  31369. }
  31370. defineCurve('p192', {
  31371. type: 'short',
  31372. prime: 'p192',
  31373. p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
  31374. a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
  31375. b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
  31376. n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
  31377. hash: hash.sha256,
  31378. gRed: false,
  31379. g: ['188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811']
  31380. });
  31381. defineCurve('p224', {
  31382. type: 'short',
  31383. prime: 'p224',
  31384. p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
  31385. a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
  31386. b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
  31387. n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
  31388. hash: hash.sha256,
  31389. gRed: false,
  31390. g: ['b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34']
  31391. });
  31392. defineCurve('p256', {
  31393. type: 'short',
  31394. prime: null,
  31395. p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
  31396. a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
  31397. b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
  31398. n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
  31399. hash: hash.sha256,
  31400. gRed: false,
  31401. g: ['6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5']
  31402. });
  31403. defineCurve('p384', {
  31404. type: 'short',
  31405. prime: null,
  31406. p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'fffffffe ffffffff 00000000 00000000 ffffffff',
  31407. a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'fffffffe ffffffff 00000000 00000000 fffffffc',
  31408. b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
  31409. n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
  31410. hash: hash.sha384,
  31411. gRed: false,
  31412. g: ['aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + '5502f25d bf55296c 3a545e38 72760ab7', '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f']
  31413. });
  31414. defineCurve('p521', {
  31415. type: 'short',
  31416. prime: null,
  31417. p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff',
  31418. a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff fffffffc',
  31419. b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
  31420. n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
  31421. hash: hash.sha512,
  31422. gRed: false,
  31423. g: ['000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + '3fad0761 353c7086 a272c240 88be9476 9fd16650']
  31424. });
  31425. defineCurve('curve25519', {
  31426. type: 'mont',
  31427. prime: 'p25519',
  31428. p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  31429. a: '76d06',
  31430. b: '1',
  31431. n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  31432. hash: hash.sha256,
  31433. gRed: false,
  31434. g: ['9']
  31435. });
  31436. defineCurve('ed25519', {
  31437. type: 'edwards',
  31438. prime: 'p25519',
  31439. p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  31440. a: '-1',
  31441. c: '1',
  31442. // -121665 * (121666^(-1)) (mod P)
  31443. d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
  31444. n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  31445. hash: hash.sha256,
  31446. gRed: false,
  31447. g: ['216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
  31448. // 4/5
  31449. '6666666666666666666666666666666666666666666666666666666666666658']
  31450. });
  31451. var pre;
  31452. try {
  31453. pre = require('./precomputed/secp256k1');
  31454. } catch (e) {
  31455. pre = undefined;
  31456. }
  31457. defineCurve('secp256k1', {
  31458. type: 'short',
  31459. prime: 'k256',
  31460. p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
  31461. a: '0',
  31462. b: '7',
  31463. n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
  31464. h: '1',
  31465. hash: hash.sha256,
  31466. // Precomputed endomorphism
  31467. beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
  31468. lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
  31469. basis: [{
  31470. a: '3086d221a7d46bcde86c90e49284eb15',
  31471. b: '-e4437ed6010e88286f547fa90abfe4c3'
  31472. }, {
  31473. a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
  31474. b: '3086d221a7d46bcde86c90e49284eb15'
  31475. }],
  31476. gRed: false,
  31477. g: ['79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', pre]
  31478. });
  31479. },{"./curve":247,"./precomputed/secp256k1":257,"./utils":258,"hash.js":265}],251:[function(require,module,exports){
  31480. 'use strict';
  31481. var BN = require('bn.js');
  31482. var HmacDRBG = require('hmac-drbg');
  31483. var utils = require('../utils');
  31484. var curves = require('../curves');
  31485. var rand = require('brorand');
  31486. var assert = utils.assert;
  31487. var KeyPair = require('./key');
  31488. var Signature = require('./signature');
  31489. function EC(options) {
  31490. if (!(this instanceof EC)) return new EC(options);
  31491. // Shortcut `elliptic.ec(curve-name)`
  31492. if (typeof options === 'string') {
  31493. assert(Object.prototype.hasOwnProperty.call(curves, options), 'Unknown curve ' + options);
  31494. options = curves[options];
  31495. }
  31496. // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
  31497. if (options instanceof curves.PresetCurve) options = {
  31498. curve: options
  31499. };
  31500. this.curve = options.curve.curve;
  31501. this.n = this.curve.n;
  31502. this.nh = this.n.ushrn(1);
  31503. this.g = this.curve.g;
  31504. // Point on curve
  31505. this.g = options.curve.g;
  31506. this.g.precompute(options.curve.n.bitLength() + 1);
  31507. // Hash for function for DRBG
  31508. this.hash = options.hash || options.curve.hash;
  31509. }
  31510. module.exports = EC;
  31511. EC.prototype.keyPair = function keyPair(options) {
  31512. return new KeyPair(this, options);
  31513. };
  31514. EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
  31515. return KeyPair.fromPrivate(this, priv, enc);
  31516. };
  31517. EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
  31518. return KeyPair.fromPublic(this, pub, enc);
  31519. };
  31520. EC.prototype.genKeyPair = function genKeyPair(options) {
  31521. if (!options) options = {};
  31522. // Instantiate Hmac_DRBG
  31523. var drbg = new HmacDRBG({
  31524. hash: this.hash,
  31525. pers: options.pers,
  31526. persEnc: options.persEnc || 'utf8',
  31527. entropy: options.entropy || rand(this.hash.hmacStrength),
  31528. entropyEnc: options.entropy && options.entropyEnc || 'utf8',
  31529. nonce: this.n.toArray()
  31530. });
  31531. var bytes = this.n.byteLength();
  31532. var ns2 = this.n.sub(new BN(2));
  31533. for (;;) {
  31534. var priv = new BN(drbg.generate(bytes));
  31535. if (priv.cmp(ns2) > 0) continue;
  31536. priv.iaddn(1);
  31537. return this.keyFromPrivate(priv);
  31538. }
  31539. };
  31540. EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) {
  31541. var delta = msg.byteLength() * 8 - this.n.bitLength();
  31542. if (delta > 0) msg = msg.ushrn(delta);
  31543. if (!truncOnly && msg.cmp(this.n) >= 0) return msg.sub(this.n);else return msg;
  31544. };
  31545. EC.prototype.sign = function sign(msg, key, enc, options) {
  31546. if (typeof enc === 'object') {
  31547. options = enc;
  31548. enc = null;
  31549. }
  31550. if (!options) options = {};
  31551. key = this.keyFromPrivate(key, enc);
  31552. msg = this._truncateToN(new BN(msg, 16));
  31553. // Zero-extend key to provide enough entropy
  31554. var bytes = this.n.byteLength();
  31555. var bkey = key.getPrivate().toArray('be', bytes);
  31556. // Zero-extend nonce to have the same byte size as N
  31557. var nonce = msg.toArray('be', bytes);
  31558. // Instantiate Hmac_DRBG
  31559. var drbg = new HmacDRBG({
  31560. hash: this.hash,
  31561. entropy: bkey,
  31562. nonce: nonce,
  31563. pers: options.pers,
  31564. persEnc: options.persEnc || 'utf8'
  31565. });
  31566. // Number of bytes to generate
  31567. var ns1 = this.n.sub(new BN(1));
  31568. for (var iter = 0;; iter++) {
  31569. var k = options.k ? options.k(iter) : new BN(drbg.generate(this.n.byteLength()));
  31570. k = this._truncateToN(k, true);
  31571. if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) continue;
  31572. var kp = this.g.mul(k);
  31573. if (kp.isInfinity()) continue;
  31574. var kpX = kp.getX();
  31575. var r = kpX.umod(this.n);
  31576. if (r.cmpn(0) === 0) continue;
  31577. var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
  31578. s = s.umod(this.n);
  31579. if (s.cmpn(0) === 0) continue;
  31580. var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r) !== 0 ? 2 : 0);
  31581. // Use complement of `s`, if it is > `n / 2`
  31582. if (options.canonical && s.cmp(this.nh) > 0) {
  31583. s = this.n.sub(s);
  31584. recoveryParam ^= 1;
  31585. }
  31586. return new Signature({
  31587. r: r,
  31588. s: s,
  31589. recoveryParam: recoveryParam
  31590. });
  31591. }
  31592. };
  31593. EC.prototype.verify = function verify(msg, signature, key, enc) {
  31594. msg = this._truncateToN(new BN(msg, 16));
  31595. key = this.keyFromPublic(key, enc);
  31596. signature = new Signature(signature, 'hex');
  31597. // Perform primitive values validation
  31598. var r = signature.r;
  31599. var s = signature.s;
  31600. if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) return false;
  31601. if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) return false;
  31602. // Validate signature
  31603. var sinv = s.invm(this.n);
  31604. var u1 = sinv.mul(msg).umod(this.n);
  31605. var u2 = sinv.mul(r).umod(this.n);
  31606. var p;
  31607. if (!this.curve._maxwellTrick) {
  31608. p = this.g.mulAdd(u1, key.getPublic(), u2);
  31609. if (p.isInfinity()) return false;
  31610. return p.getX().umod(this.n).cmp(r) === 0;
  31611. }
  31612. // NOTE: Greg Maxwell's trick, inspired by:
  31613. // https://git.io/vad3K
  31614. p = this.g.jmulAdd(u1, key.getPublic(), u2);
  31615. if (p.isInfinity()) return false;
  31616. // Compare `p.x` of Jacobian point with `r`,
  31617. // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
  31618. // inverse of `p.z^2`
  31619. return p.eqXToP(r);
  31620. };
  31621. EC.prototype.recoverPubKey = function (msg, signature, j, enc) {
  31622. assert((3 & j) === j, 'The recovery param is more than two bits');
  31623. signature = new Signature(signature, enc);
  31624. var n = this.n;
  31625. var e = new BN(msg);
  31626. var r = signature.r;
  31627. var s = signature.s;
  31628. // A set LSB signifies that the y-coordinate is odd
  31629. var isYOdd = j & 1;
  31630. var isSecondKey = j >> 1;
  31631. if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) throw new Error('Unable to find sencond key candinate');
  31632. // 1.1. Let x = r + jn.
  31633. if (isSecondKey) r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);else r = this.curve.pointFromX(r, isYOdd);
  31634. var rInv = signature.r.invm(n);
  31635. var s1 = n.sub(e).mul(rInv).umod(n);
  31636. var s2 = s.mul(rInv).umod(n);
  31637. // 1.6.1 Compute Q = r^-1 (sR - eG)
  31638. // Q = r^-1 (sR + -eG)
  31639. return this.g.mulAdd(s1, r, s2);
  31640. };
  31641. EC.prototype.getKeyRecoveryParam = function (e, signature, Q, enc) {
  31642. signature = new Signature(signature, enc);
  31643. if (signature.recoveryParam !== null) return signature.recoveryParam;
  31644. for (var i = 0; i < 4; i++) {
  31645. var Qprime;
  31646. try {
  31647. Qprime = this.recoverPubKey(e, signature, i);
  31648. } catch (e) {
  31649. continue;
  31650. }
  31651. if (Qprime.eq(Q)) return i;
  31652. }
  31653. throw new Error('Unable to find valid recovery factor');
  31654. };
  31655. },{"../curves":250,"../utils":258,"./key":252,"./signature":253,"bn.js":259,"brorand":187,"hmac-drbg":277}],252:[function(require,module,exports){
  31656. 'use strict';
  31657. var BN = require('bn.js');
  31658. var utils = require('../utils');
  31659. var assert = utils.assert;
  31660. function KeyPair(ec, options) {
  31661. this.ec = ec;
  31662. this.priv = null;
  31663. this.pub = null;
  31664. // KeyPair(ec, { priv: ..., pub: ... })
  31665. if (options.priv) this._importPrivate(options.priv, options.privEnc);
  31666. if (options.pub) this._importPublic(options.pub, options.pubEnc);
  31667. }
  31668. module.exports = KeyPair;
  31669. KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
  31670. if (pub instanceof KeyPair) return pub;
  31671. return new KeyPair(ec, {
  31672. pub: pub,
  31673. pubEnc: enc
  31674. });
  31675. };
  31676. KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
  31677. if (priv instanceof KeyPair) return priv;
  31678. return new KeyPair(ec, {
  31679. priv: priv,
  31680. privEnc: enc
  31681. });
  31682. };
  31683. KeyPair.prototype.validate = function validate() {
  31684. var pub = this.getPublic();
  31685. if (pub.isInfinity()) return {
  31686. result: false,
  31687. reason: 'Invalid public key'
  31688. };
  31689. if (!pub.validate()) return {
  31690. result: false,
  31691. reason: 'Public key is not a point'
  31692. };
  31693. if (!pub.mul(this.ec.curve.n).isInfinity()) return {
  31694. result: false,
  31695. reason: 'Public key * N != O'
  31696. };
  31697. return {
  31698. result: true,
  31699. reason: null
  31700. };
  31701. };
  31702. KeyPair.prototype.getPublic = function getPublic(compact, enc) {
  31703. // compact is optional argument
  31704. if (typeof compact === 'string') {
  31705. enc = compact;
  31706. compact = null;
  31707. }
  31708. if (!this.pub) this.pub = this.ec.g.mul(this.priv);
  31709. if (!enc) return this.pub;
  31710. return this.pub.encode(enc, compact);
  31711. };
  31712. KeyPair.prototype.getPrivate = function getPrivate(enc) {
  31713. if (enc === 'hex') return this.priv.toString(16, 2);else return this.priv;
  31714. };
  31715. KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
  31716. this.priv = new BN(key, enc || 16);
  31717. // Ensure that the priv won't be bigger than n, otherwise we may fail
  31718. // in fixed multiplication method
  31719. this.priv = this.priv.umod(this.ec.curve.n);
  31720. };
  31721. KeyPair.prototype._importPublic = function _importPublic(key, enc) {
  31722. if (key.x || key.y) {
  31723. // Montgomery points only have an `x` coordinate.
  31724. // Weierstrass/Edwards points on the other hand have both `x` and
  31725. // `y` coordinates.
  31726. if (this.ec.curve.type === 'mont') {
  31727. assert(key.x, 'Need x coordinate');
  31728. } else if (this.ec.curve.type === 'short' || this.ec.curve.type === 'edwards') {
  31729. assert(key.x && key.y, 'Need both x and y coordinate');
  31730. }
  31731. this.pub = this.ec.curve.point(key.x, key.y);
  31732. return;
  31733. }
  31734. this.pub = this.ec.curve.decodePoint(key, enc);
  31735. };
  31736. // ECDH
  31737. KeyPair.prototype.derive = function derive(pub) {
  31738. if (!pub.validate()) {
  31739. assert(pub.validate(), 'public point not validated');
  31740. }
  31741. return pub.mul(this.priv).getX();
  31742. };
  31743. // ECDSA
  31744. KeyPair.prototype.sign = function sign(msg, enc, options) {
  31745. return this.ec.sign(msg, this, enc, options);
  31746. };
  31747. KeyPair.prototype.verify = function verify(msg, signature) {
  31748. return this.ec.verify(msg, signature, this);
  31749. };
  31750. KeyPair.prototype.inspect = function inspect() {
  31751. return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) + ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
  31752. };
  31753. },{"../utils":258,"bn.js":259}],253:[function(require,module,exports){
  31754. 'use strict';
  31755. var BN = require('bn.js');
  31756. var utils = require('../utils');
  31757. var assert = utils.assert;
  31758. function Signature(options, enc) {
  31759. if (options instanceof Signature) return options;
  31760. if (this._importDER(options, enc)) return;
  31761. assert(options.r && options.s, 'Signature without r or s');
  31762. this.r = new BN(options.r, 16);
  31763. this.s = new BN(options.s, 16);
  31764. if (options.recoveryParam === undefined) this.recoveryParam = null;else this.recoveryParam = options.recoveryParam;
  31765. }
  31766. module.exports = Signature;
  31767. function Position() {
  31768. this.place = 0;
  31769. }
  31770. function getLength(buf, p) {
  31771. var initial = buf[p.place++];
  31772. if (!(initial & 0x80)) {
  31773. return initial;
  31774. }
  31775. var octetLen = initial & 0xf;
  31776. // Indefinite length or overflow
  31777. if (octetLen === 0 || octetLen > 4) {
  31778. return false;
  31779. }
  31780. var val = 0;
  31781. for (var i = 0, off = p.place; i < octetLen; i++, off++) {
  31782. val <<= 8;
  31783. val |= buf[off];
  31784. val >>>= 0;
  31785. }
  31786. // Leading zeroes
  31787. if (val <= 0x7f) {
  31788. return false;
  31789. }
  31790. p.place = off;
  31791. return val;
  31792. }
  31793. function rmPadding(buf) {
  31794. var i = 0;
  31795. var len = buf.length - 1;
  31796. while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
  31797. i++;
  31798. }
  31799. if (i === 0) {
  31800. return buf;
  31801. }
  31802. return buf.slice(i);
  31803. }
  31804. Signature.prototype._importDER = function _importDER(data, enc) {
  31805. data = utils.toArray(data, enc);
  31806. var p = new Position();
  31807. if (data[p.place++] !== 0x30) {
  31808. return false;
  31809. }
  31810. var len = getLength(data, p);
  31811. if (len === false) {
  31812. return false;
  31813. }
  31814. if (len + p.place !== data.length) {
  31815. return false;
  31816. }
  31817. if (data[p.place++] !== 0x02) {
  31818. return false;
  31819. }
  31820. var rlen = getLength(data, p);
  31821. if (rlen === false) {
  31822. return false;
  31823. }
  31824. var r = data.slice(p.place, rlen + p.place);
  31825. p.place += rlen;
  31826. if (data[p.place++] !== 0x02) {
  31827. return false;
  31828. }
  31829. var slen = getLength(data, p);
  31830. if (slen === false) {
  31831. return false;
  31832. }
  31833. if (data.length !== slen + p.place) {
  31834. return false;
  31835. }
  31836. var s = data.slice(p.place, slen + p.place);
  31837. if (r[0] === 0) {
  31838. if (r[1] & 0x80) {
  31839. r = r.slice(1);
  31840. } else {
  31841. // Leading zeroes
  31842. return false;
  31843. }
  31844. }
  31845. if (s[0] === 0) {
  31846. if (s[1] & 0x80) {
  31847. s = s.slice(1);
  31848. } else {
  31849. // Leading zeroes
  31850. return false;
  31851. }
  31852. }
  31853. this.r = new BN(r);
  31854. this.s = new BN(s);
  31855. this.recoveryParam = null;
  31856. return true;
  31857. };
  31858. function constructLength(arr, len) {
  31859. if (len < 0x80) {
  31860. arr.push(len);
  31861. return;
  31862. }
  31863. var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
  31864. arr.push(octets | 0x80);
  31865. while (--octets) {
  31866. arr.push(len >>> (octets << 3) & 0xff);
  31867. }
  31868. arr.push(len);
  31869. }
  31870. Signature.prototype.toDER = function toDER(enc) {
  31871. var r = this.r.toArray();
  31872. var s = this.s.toArray();
  31873. // Pad values
  31874. if (r[0] & 0x80) r = [0].concat(r);
  31875. // Pad values
  31876. if (s[0] & 0x80) s = [0].concat(s);
  31877. r = rmPadding(r);
  31878. s = rmPadding(s);
  31879. while (!s[0] && !(s[1] & 0x80)) {
  31880. s = s.slice(1);
  31881. }
  31882. var arr = [0x02];
  31883. constructLength(arr, r.length);
  31884. arr = arr.concat(r);
  31885. arr.push(0x02);
  31886. constructLength(arr, s.length);
  31887. var backHalf = arr.concat(s);
  31888. var res = [0x30];
  31889. constructLength(res, backHalf.length);
  31890. res = res.concat(backHalf);
  31891. return utils.encode(res, enc);
  31892. };
  31893. },{"../utils":258,"bn.js":259}],254:[function(require,module,exports){
  31894. 'use strict';
  31895. var hash = require('hash.js');
  31896. var curves = require('../curves');
  31897. var utils = require('../utils');
  31898. var assert = utils.assert;
  31899. var parseBytes = utils.parseBytes;
  31900. var KeyPair = require('./key');
  31901. var Signature = require('./signature');
  31902. function EDDSA(curve) {
  31903. assert(curve === 'ed25519', 'only tested with ed25519 so far');
  31904. if (!(this instanceof EDDSA)) return new EDDSA(curve);
  31905. curve = curves[curve].curve;
  31906. this.curve = curve;
  31907. this.g = curve.g;
  31908. this.g.precompute(curve.n.bitLength() + 1);
  31909. this.pointClass = curve.point().constructor;
  31910. this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
  31911. this.hash = hash.sha512;
  31912. }
  31913. module.exports = EDDSA;
  31914. /**
  31915. * @param {Array|String} message - message bytes
  31916. * @param {Array|String|KeyPair} secret - secret bytes or a keypair
  31917. * @returns {Signature} - signature
  31918. */
  31919. EDDSA.prototype.sign = function sign(message, secret) {
  31920. message = parseBytes(message);
  31921. var key = this.keyFromSecret(secret);
  31922. var r = this.hashInt(key.messagePrefix(), message);
  31923. var R = this.g.mul(r);
  31924. var Rencoded = this.encodePoint(R);
  31925. var s_ = this.hashInt(Rencoded, key.pubBytes(), message).mul(key.priv());
  31926. var S = r.add(s_).umod(this.curve.n);
  31927. return this.makeSignature({
  31928. R: R,
  31929. S: S,
  31930. Rencoded: Rencoded
  31931. });
  31932. };
  31933. /**
  31934. * @param {Array} message - message bytes
  31935. * @param {Array|String|Signature} sig - sig bytes
  31936. * @param {Array|String|Point|KeyPair} pub - public key
  31937. * @returns {Boolean} - true if public key matches sig of message
  31938. */
  31939. EDDSA.prototype.verify = function verify(message, sig, pub) {
  31940. message = parseBytes(message);
  31941. sig = this.makeSignature(sig);
  31942. var key = this.keyFromPublic(pub);
  31943. var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
  31944. var SG = this.g.mul(sig.S());
  31945. var RplusAh = sig.R().add(key.pub().mul(h));
  31946. return RplusAh.eq(SG);
  31947. };
  31948. EDDSA.prototype.hashInt = function hashInt() {
  31949. var hash = this.hash();
  31950. for (var i = 0; i < arguments.length; i++) hash.update(arguments[i]);
  31951. return utils.intFromLE(hash.digest()).umod(this.curve.n);
  31952. };
  31953. EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
  31954. return KeyPair.fromPublic(this, pub);
  31955. };
  31956. EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
  31957. return KeyPair.fromSecret(this, secret);
  31958. };
  31959. EDDSA.prototype.makeSignature = function makeSignature(sig) {
  31960. if (sig instanceof Signature) return sig;
  31961. return new Signature(this, sig);
  31962. };
  31963. /**
  31964. * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
  31965. *
  31966. * EDDSA defines methods for encoding and decoding points and integers. These are
  31967. * helper convenience methods, that pass along to utility functions implied
  31968. * parameters.
  31969. *
  31970. */
  31971. EDDSA.prototype.encodePoint = function encodePoint(point) {
  31972. var enc = point.getY().toArray('le', this.encodingLength);
  31973. enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
  31974. return enc;
  31975. };
  31976. EDDSA.prototype.decodePoint = function decodePoint(bytes) {
  31977. bytes = utils.parseBytes(bytes);
  31978. var lastIx = bytes.length - 1;
  31979. var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
  31980. var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
  31981. var y = utils.intFromLE(normed);
  31982. return this.curve.pointFromY(y, xIsOdd);
  31983. };
  31984. EDDSA.prototype.encodeInt = function encodeInt(num) {
  31985. return num.toArray('le', this.encodingLength);
  31986. };
  31987. EDDSA.prototype.decodeInt = function decodeInt(bytes) {
  31988. return utils.intFromLE(bytes);
  31989. };
  31990. EDDSA.prototype.isPoint = function isPoint(val) {
  31991. return val instanceof this.pointClass;
  31992. };
  31993. },{"../curves":250,"../utils":258,"./key":255,"./signature":256,"hash.js":265}],255:[function(require,module,exports){
  31994. 'use strict';
  31995. var utils = require('../utils');
  31996. var assert = utils.assert;
  31997. var parseBytes = utils.parseBytes;
  31998. var cachedProperty = utils.cachedProperty;
  31999. /**
  32000. * @param {EDDSA} eddsa - instance
  32001. * @param {Object} params - public/private key parameters
  32002. *
  32003. * @param {Array<Byte>} [params.secret] - secret seed bytes
  32004. * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
  32005. * @param {Array<Byte>} [params.pub] - public key point encoded as bytes
  32006. *
  32007. */
  32008. function KeyPair(eddsa, params) {
  32009. this.eddsa = eddsa;
  32010. this._secret = parseBytes(params.secret);
  32011. if (eddsa.isPoint(params.pub)) this._pub = params.pub;else this._pubBytes = parseBytes(params.pub);
  32012. }
  32013. KeyPair.fromPublic = function fromPublic(eddsa, pub) {
  32014. if (pub instanceof KeyPair) return pub;
  32015. return new KeyPair(eddsa, {
  32016. pub: pub
  32017. });
  32018. };
  32019. KeyPair.fromSecret = function fromSecret(eddsa, secret) {
  32020. if (secret instanceof KeyPair) return secret;
  32021. return new KeyPair(eddsa, {
  32022. secret: secret
  32023. });
  32024. };
  32025. KeyPair.prototype.secret = function secret() {
  32026. return this._secret;
  32027. };
  32028. cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
  32029. return this.eddsa.encodePoint(this.pub());
  32030. });
  32031. cachedProperty(KeyPair, 'pub', function pub() {
  32032. if (this._pubBytes) return this.eddsa.decodePoint(this._pubBytes);
  32033. return this.eddsa.g.mul(this.priv());
  32034. });
  32035. cachedProperty(KeyPair, 'privBytes', function privBytes() {
  32036. var eddsa = this.eddsa;
  32037. var hash = this.hash();
  32038. var lastIx = eddsa.encodingLength - 1;
  32039. var a = hash.slice(0, eddsa.encodingLength);
  32040. a[0] &= 248;
  32041. a[lastIx] &= 127;
  32042. a[lastIx] |= 64;
  32043. return a;
  32044. });
  32045. cachedProperty(KeyPair, 'priv', function priv() {
  32046. return this.eddsa.decodeInt(this.privBytes());
  32047. });
  32048. cachedProperty(KeyPair, 'hash', function hash() {
  32049. return this.eddsa.hash().update(this.secret()).digest();
  32050. });
  32051. cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
  32052. return this.hash().slice(this.eddsa.encodingLength);
  32053. });
  32054. KeyPair.prototype.sign = function sign(message) {
  32055. assert(this._secret, 'KeyPair can only verify');
  32056. return this.eddsa.sign(message, this);
  32057. };
  32058. KeyPair.prototype.verify = function verify(message, sig) {
  32059. return this.eddsa.verify(message, sig, this);
  32060. };
  32061. KeyPair.prototype.getSecret = function getSecret(enc) {
  32062. assert(this._secret, 'KeyPair is public only');
  32063. return utils.encode(this.secret(), enc);
  32064. };
  32065. KeyPair.prototype.getPublic = function getPublic(enc) {
  32066. return utils.encode(this.pubBytes(), enc);
  32067. };
  32068. module.exports = KeyPair;
  32069. },{"../utils":258}],256:[function(require,module,exports){
  32070. 'use strict';
  32071. var BN = require('bn.js');
  32072. var utils = require('../utils');
  32073. var assert = utils.assert;
  32074. var cachedProperty = utils.cachedProperty;
  32075. var parseBytes = utils.parseBytes;
  32076. /**
  32077. * @param {EDDSA} eddsa - eddsa instance
  32078. * @param {Array<Bytes>|Object} sig -
  32079. * @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
  32080. * @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
  32081. * @param {Array<Bytes>} [sig.Rencoded] - R point encoded
  32082. * @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
  32083. */
  32084. function Signature(eddsa, sig) {
  32085. this.eddsa = eddsa;
  32086. if (typeof sig !== 'object') sig = parseBytes(sig);
  32087. if (Array.isArray(sig)) {
  32088. sig = {
  32089. R: sig.slice(0, eddsa.encodingLength),
  32090. S: sig.slice(eddsa.encodingLength)
  32091. };
  32092. }
  32093. assert(sig.R && sig.S, 'Signature without R or S');
  32094. if (eddsa.isPoint(sig.R)) this._R = sig.R;
  32095. if (sig.S instanceof BN) this._S = sig.S;
  32096. this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
  32097. this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
  32098. }
  32099. cachedProperty(Signature, 'S', function S() {
  32100. return this.eddsa.decodeInt(this.Sencoded());
  32101. });
  32102. cachedProperty(Signature, 'R', function R() {
  32103. return this.eddsa.decodePoint(this.Rencoded());
  32104. });
  32105. cachedProperty(Signature, 'Rencoded', function Rencoded() {
  32106. return this.eddsa.encodePoint(this.R());
  32107. });
  32108. cachedProperty(Signature, 'Sencoded', function Sencoded() {
  32109. return this.eddsa.encodeInt(this.S());
  32110. });
  32111. Signature.prototype.toBytes = function toBytes() {
  32112. return this.Rencoded().concat(this.Sencoded());
  32113. };
  32114. Signature.prototype.toHex = function toHex() {
  32115. return utils.encode(this.toBytes(), 'hex').toUpperCase();
  32116. };
  32117. module.exports = Signature;
  32118. },{"../utils":258,"bn.js":259}],257:[function(require,module,exports){
  32119. "use strict";
  32120. module.exports = {
  32121. doubles: {
  32122. step: 4,
  32123. points: [['e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'], ['8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'], ['175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'], ['363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'], ['8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'], ['723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'], ['eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'], ['100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'], ['e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'], ['feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'], ['da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'], ['53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'], ['8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'], ['385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'], ['6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'], ['3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'], ['85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'], ['948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'], ['6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'], ['e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'], ['e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'], ['213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'], ['4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'], ['fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'], ['76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'], ['c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'], ['d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'], ['b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'], ['e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'], ['a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'], ['90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'], ['8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'], ['e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'], ['8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'], ['e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'], ['b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'], ['d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'], ['324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'], ['4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'], ['9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'], ['6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'], ['a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'], ['7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'], ['928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'], ['85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'], ['ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'], ['827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'], ['eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'], ['e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'], ['1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'], ['146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'], ['fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'], ['da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'], ['a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'], ['174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'], ['959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'], ['d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'], ['64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'], ['8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'], ['13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'], ['bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'], ['8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'], ['8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'], ['dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'], ['f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82']]
  32124. },
  32125. naf: {
  32126. wnd: 7,
  32127. points: [['f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'], ['2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'], ['5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'], ['acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'], ['774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'], ['f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'], ['d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'], ['defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'], ['2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'], ['352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'], ['2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'], ['9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'], ['daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'], ['c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'], ['6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'], ['1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'], ['605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'], ['62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'], ['80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'], ['7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'], ['d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'], ['49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'], ['77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'], ['f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'], ['463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'], ['f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'], ['caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'], ['2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'], ['7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'], ['754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'], ['e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'], ['186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'], ['df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'], ['5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'], ['290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'], ['af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'], ['766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'], ['59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'], ['f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'], ['7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'], ['948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'], ['7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'], ['3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'], ['d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'], ['1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'], ['733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'], ['15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'], ['a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'], ['e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'], ['311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'], ['34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'], ['f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'], ['d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'], ['32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'], ['7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'], ['ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'], ['16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'], ['eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'], ['78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'], ['494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'], ['a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'], ['c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'], ['841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'], ['5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'], ['36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'], ['336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'], ['8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'], ['1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'], ['85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'], ['29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'], ['a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'], ['4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'], ['d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'], ['ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'], ['af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'], ['e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'], ['591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'], ['11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'], ['3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'], ['cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'], ['c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'], ['c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'], ['a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'], ['347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'], ['da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'], ['c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'], ['4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'], ['3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'], ['cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'], ['b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'], ['d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'], ['48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'], ['dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'], ['6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'], ['e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'], ['eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'], ['13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'], ['ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'], ['b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'], ['ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'], ['8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'], ['52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'], ['e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'], ['7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'], ['5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'], ['32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'], ['e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'], ['8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'], ['4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'], ['3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'], ['674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'], ['d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'], ['30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'], ['be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'], ['93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'], ['b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'], ['d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'], ['d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'], ['463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'], ['7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'], ['74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'], ['30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'], ['9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'], ['176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'], ['75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'], ['809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'], ['1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9']]
  32128. }
  32129. };
  32130. },{}],258:[function(require,module,exports){
  32131. 'use strict';
  32132. var utils = exports;
  32133. var BN = require('bn.js');
  32134. var minAssert = require('minimalistic-assert');
  32135. var minUtils = require('minimalistic-crypto-utils');
  32136. utils.assert = minAssert;
  32137. utils.toArray = minUtils.toArray;
  32138. utils.zero2 = minUtils.zero2;
  32139. utils.toHex = minUtils.toHex;
  32140. utils.encode = minUtils.encode;
  32141. // Represent num in a w-NAF form
  32142. function getNAF(num, w, bits) {
  32143. var naf = new Array(Math.max(num.bitLength(), bits) + 1);
  32144. naf.fill(0);
  32145. var ws = 1 << w + 1;
  32146. var k = num.clone();
  32147. for (var i = 0; i < naf.length; i++) {
  32148. var z;
  32149. var mod = k.andln(ws - 1);
  32150. if (k.isOdd()) {
  32151. if (mod > (ws >> 1) - 1) z = (ws >> 1) - mod;else z = mod;
  32152. k.isubn(z);
  32153. } else {
  32154. z = 0;
  32155. }
  32156. naf[i] = z;
  32157. k.iushrn(1);
  32158. }
  32159. return naf;
  32160. }
  32161. utils.getNAF = getNAF;
  32162. // Represent k1, k2 in a Joint Sparse Form
  32163. function getJSF(k1, k2) {
  32164. var jsf = [[], []];
  32165. k1 = k1.clone();
  32166. k2 = k2.clone();
  32167. var d1 = 0;
  32168. var d2 = 0;
  32169. var m8;
  32170. while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
  32171. // First phase
  32172. var m14 = k1.andln(3) + d1 & 3;
  32173. var m24 = k2.andln(3) + d2 & 3;
  32174. if (m14 === 3) m14 = -1;
  32175. if (m24 === 3) m24 = -1;
  32176. var u1;
  32177. if ((m14 & 1) === 0) {
  32178. u1 = 0;
  32179. } else {
  32180. m8 = k1.andln(7) + d1 & 7;
  32181. if ((m8 === 3 || m8 === 5) && m24 === 2) u1 = -m14;else u1 = m14;
  32182. }
  32183. jsf[0].push(u1);
  32184. var u2;
  32185. if ((m24 & 1) === 0) {
  32186. u2 = 0;
  32187. } else {
  32188. m8 = k2.andln(7) + d2 & 7;
  32189. if ((m8 === 3 || m8 === 5) && m14 === 2) u2 = -m24;else u2 = m24;
  32190. }
  32191. jsf[1].push(u2);
  32192. // Second phase
  32193. if (2 * d1 === u1 + 1) d1 = 1 - d1;
  32194. if (2 * d2 === u2 + 1) d2 = 1 - d2;
  32195. k1.iushrn(1);
  32196. k2.iushrn(1);
  32197. }
  32198. return jsf;
  32199. }
  32200. utils.getJSF = getJSF;
  32201. function cachedProperty(obj, name, computer) {
  32202. var key = '_' + name;
  32203. obj.prototype[name] = function cachedProperty() {
  32204. return this[key] !== undefined ? this[key] : this[key] = computer.call(this);
  32205. };
  32206. }
  32207. utils.cachedProperty = cachedProperty;
  32208. function parseBytes(bytes) {
  32209. return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : bytes;
  32210. }
  32211. utils.parseBytes = parseBytes;
  32212. function intFromLE(bytes) {
  32213. return new BN(bytes, 'hex', 'le');
  32214. }
  32215. utils.intFromLE = intFromLE;
  32216. },{"bn.js":259,"minimalistic-assert":292,"minimalistic-crypto-utils":293}],259:[function(require,module,exports){
  32217. arguments[4][184][0].apply(exports,arguments)
  32218. },{"buffer":188,"dup":184}],260:[function(require,module,exports){
  32219. module.exports={
  32220. "name": "elliptic",
  32221. "version": "6.5.4",
  32222. "description": "EC cryptography",
  32223. "main": "lib/elliptic.js",
  32224. "files": [
  32225. "lib"
  32226. ],
  32227. "scripts": {
  32228. "lint": "eslint lib test",
  32229. "lint:fix": "npm run lint -- --fix",
  32230. "unit": "istanbul test _mocha --reporter=spec test/index.js",
  32231. "test": "npm run lint && npm run unit",
  32232. "version": "grunt dist && git add dist/"
  32233. },
  32234. "repository": {
  32235. "type": "git",
  32236. "url": "git@github.com:indutny/elliptic"
  32237. },
  32238. "keywords": [
  32239. "EC",
  32240. "Elliptic",
  32241. "curve",
  32242. "Cryptography"
  32243. ],
  32244. "author": "Fedor Indutny <fedor@indutny.com>",
  32245. "license": "MIT",
  32246. "bugs": {
  32247. "url": "https://github.com/indutny/elliptic/issues"
  32248. },
  32249. "homepage": "https://github.com/indutny/elliptic",
  32250. "devDependencies": {
  32251. "brfs": "^2.0.2",
  32252. "coveralls": "^3.1.0",
  32253. "eslint": "^7.6.0",
  32254. "grunt": "^1.2.1",
  32255. "grunt-browserify": "^5.3.0",
  32256. "grunt-cli": "^1.3.2",
  32257. "grunt-contrib-connect": "^3.0.0",
  32258. "grunt-contrib-copy": "^1.0.0",
  32259. "grunt-contrib-uglify": "^5.0.0",
  32260. "grunt-mocha-istanbul": "^5.0.2",
  32261. "grunt-saucelabs": "^9.0.1",
  32262. "istanbul": "^0.4.5",
  32263. "mocha": "^8.0.1"
  32264. },
  32265. "dependencies": {
  32266. "bn.js": "^4.11.9",
  32267. "brorand": "^1.1.0",
  32268. "hash.js": "^1.0.0",
  32269. "hmac-drbg": "^1.0.1",
  32270. "inherits": "^2.0.4",
  32271. "minimalistic-assert": "^1.0.1",
  32272. "minimalistic-crypto-utils": "^1.0.1"
  32273. }
  32274. }
  32275. },{}],261:[function(require,module,exports){
  32276. "use strict";
  32277. // Copyright Joyent, Inc. and other Node contributors.
  32278. //
  32279. // Permission is hereby granted, free of charge, to any person obtaining a
  32280. // copy of this software and associated documentation files (the
  32281. // "Software"), to deal in the Software without restriction, including
  32282. // without limitation the rights to use, copy, modify, merge, publish,
  32283. // distribute, sublicense, and/or sell copies of the Software, and to permit
  32284. // persons to whom the Software is furnished to do so, subject to the
  32285. // following conditions:
  32286. //
  32287. // The above copyright notice and this permission notice shall be included
  32288. // in all copies or substantial portions of the Software.
  32289. //
  32290. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  32291. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  32292. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  32293. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  32294. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  32295. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  32296. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  32297. var objectCreate = Object.create || objectCreatePolyfill;
  32298. var objectKeys = Object.keys || objectKeysPolyfill;
  32299. var bind = Function.prototype.bind || functionBindPolyfill;
  32300. function EventEmitter() {
  32301. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  32302. this._events = objectCreate(null);
  32303. this._eventsCount = 0;
  32304. }
  32305. this._maxListeners = this._maxListeners || undefined;
  32306. }
  32307. module.exports = EventEmitter;
  32308. // Backwards-compat with node 0.10.x
  32309. EventEmitter.EventEmitter = EventEmitter;
  32310. EventEmitter.prototype._events = undefined;
  32311. EventEmitter.prototype._maxListeners = undefined;
  32312. // By default EventEmitters will print a warning if more than 10 listeners are
  32313. // added to it. This is a useful default which helps finding memory leaks.
  32314. var defaultMaxListeners = 10;
  32315. var hasDefineProperty;
  32316. try {
  32317. var o = {};
  32318. if (Object.defineProperty) Object.defineProperty(o, 'x', {
  32319. value: 0
  32320. });
  32321. hasDefineProperty = o.x === 0;
  32322. } catch (err) {
  32323. hasDefineProperty = false;
  32324. }
  32325. if (hasDefineProperty) {
  32326. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  32327. enumerable: true,
  32328. get: function () {
  32329. return defaultMaxListeners;
  32330. },
  32331. set: function (arg) {
  32332. // check whether the input is a positive number (whose value is zero or
  32333. // greater and not a NaN).
  32334. if (typeof arg !== 'number' || arg < 0 || arg !== arg) throw new TypeError('"defaultMaxListeners" must be a positive number');
  32335. defaultMaxListeners = arg;
  32336. }
  32337. });
  32338. } else {
  32339. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  32340. }
  32341. // Obviously not all Emitters should be limited to 10. This function allows
  32342. // that to be increased. Set to zero for unlimited.
  32343. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  32344. if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number');
  32345. this._maxListeners = n;
  32346. return this;
  32347. };
  32348. function $getMaxListeners(that) {
  32349. if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners;
  32350. return that._maxListeners;
  32351. }
  32352. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  32353. return $getMaxListeners(this);
  32354. };
  32355. // These standalone emit* functions are used to optimize calling of event
  32356. // handlers for fast cases because emit() itself often has a variable number of
  32357. // arguments and can be deoptimized because of that. These functions always have
  32358. // the same number of arguments and thus do not get deoptimized, so the code
  32359. // inside them can execute faster.
  32360. function emitNone(handler, isFn, self) {
  32361. if (isFn) handler.call(self);else {
  32362. var len = handler.length;
  32363. var listeners = arrayClone(handler, len);
  32364. for (var i = 0; i < len; ++i) listeners[i].call(self);
  32365. }
  32366. }
  32367. function emitOne(handler, isFn, self, arg1) {
  32368. if (isFn) handler.call(self, arg1);else {
  32369. var len = handler.length;
  32370. var listeners = arrayClone(handler, len);
  32371. for (var i = 0; i < len; ++i) listeners[i].call(self, arg1);
  32372. }
  32373. }
  32374. function emitTwo(handler, isFn, self, arg1, arg2) {
  32375. if (isFn) handler.call(self, arg1, arg2);else {
  32376. var len = handler.length;
  32377. var listeners = arrayClone(handler, len);
  32378. for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2);
  32379. }
  32380. }
  32381. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  32382. if (isFn) handler.call(self, arg1, arg2, arg3);else {
  32383. var len = handler.length;
  32384. var listeners = arrayClone(handler, len);
  32385. for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2, arg3);
  32386. }
  32387. }
  32388. function emitMany(handler, isFn, self, args) {
  32389. if (isFn) handler.apply(self, args);else {
  32390. var len = handler.length;
  32391. var listeners = arrayClone(handler, len);
  32392. for (var i = 0; i < len; ++i) listeners[i].apply(self, args);
  32393. }
  32394. }
  32395. EventEmitter.prototype.emit = function emit(type) {
  32396. var er, handler, len, args, i, events;
  32397. var doError = type === 'error';
  32398. events = this._events;
  32399. if (events) doError = doError && events.error == null;else if (!doError) return false;
  32400. // If there is no 'error' event listener then throw.
  32401. if (doError) {
  32402. if (arguments.length > 1) er = arguments[1];
  32403. if (er instanceof Error) {
  32404. throw er; // Unhandled 'error' event
  32405. } else {
  32406. // At least give some kind of context to the user
  32407. var err = new Error('Unhandled "error" event. (' + er + ')');
  32408. err.context = er;
  32409. throw err;
  32410. }
  32411. return false;
  32412. }
  32413. handler = events[type];
  32414. if (!handler) return false;
  32415. var isFn = typeof handler === 'function';
  32416. len = arguments.length;
  32417. switch (len) {
  32418. // fast cases
  32419. case 1:
  32420. emitNone(handler, isFn, this);
  32421. break;
  32422. case 2:
  32423. emitOne(handler, isFn, this, arguments[1]);
  32424. break;
  32425. case 3:
  32426. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  32427. break;
  32428. case 4:
  32429. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  32430. break;
  32431. // slower
  32432. default:
  32433. args = new Array(len - 1);
  32434. for (i = 1; i < len; i++) args[i - 1] = arguments[i];
  32435. emitMany(handler, isFn, this, args);
  32436. }
  32437. return true;
  32438. };
  32439. function _addListener(target, type, listener, prepend) {
  32440. var m;
  32441. var events;
  32442. var existing;
  32443. if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
  32444. events = target._events;
  32445. if (!events) {
  32446. events = target._events = objectCreate(null);
  32447. target._eventsCount = 0;
  32448. } else {
  32449. // To avoid recursion in the case that type === "newListener"! Before
  32450. // adding it to the listeners, first emit "newListener".
  32451. if (events.newListener) {
  32452. target.emit('newListener', type, listener.listener ? listener.listener : listener);
  32453. // Re-assign `events` because a newListener handler could have caused the
  32454. // this._events to be assigned to a new object
  32455. events = target._events;
  32456. }
  32457. existing = events[type];
  32458. }
  32459. if (!existing) {
  32460. // Optimize the case of one listener. Don't need the extra array object.
  32461. existing = events[type] = listener;
  32462. ++target._eventsCount;
  32463. } else {
  32464. if (typeof existing === 'function') {
  32465. // Adding the second element, need to change to array.
  32466. existing = events[type] = prepend ? [listener, existing] : [existing, listener];
  32467. } else {
  32468. // If we've already got an array, just append.
  32469. if (prepend) {
  32470. existing.unshift(listener);
  32471. } else {
  32472. existing.push(listener);
  32473. }
  32474. }
  32475. // Check for listener leak
  32476. if (!existing.warned) {
  32477. m = $getMaxListeners(target);
  32478. if (m && m > 0 && existing.length > m) {
  32479. existing.warned = true;
  32480. var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' "' + String(type) + '" listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit.');
  32481. w.name = 'MaxListenersExceededWarning';
  32482. w.emitter = target;
  32483. w.type = type;
  32484. w.count = existing.length;
  32485. if (typeof console === 'object' && console.warn) {
  32486. console.warn('%s: %s', w.name, w.message);
  32487. }
  32488. }
  32489. }
  32490. }
  32491. return target;
  32492. }
  32493. EventEmitter.prototype.addListener = function addListener(type, listener) {
  32494. return _addListener(this, type, listener, false);
  32495. };
  32496. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  32497. EventEmitter.prototype.prependListener = function prependListener(type, listener) {
  32498. return _addListener(this, type, listener, true);
  32499. };
  32500. function onceWrapper() {
  32501. if (!this.fired) {
  32502. this.target.removeListener(this.type, this.wrapFn);
  32503. this.fired = true;
  32504. switch (arguments.length) {
  32505. case 0:
  32506. return this.listener.call(this.target);
  32507. case 1:
  32508. return this.listener.call(this.target, arguments[0]);
  32509. case 2:
  32510. return this.listener.call(this.target, arguments[0], arguments[1]);
  32511. case 3:
  32512. return this.listener.call(this.target, arguments[0], arguments[1], arguments[2]);
  32513. default:
  32514. var args = new Array(arguments.length);
  32515. for (var i = 0; i < args.length; ++i) args[i] = arguments[i];
  32516. this.listener.apply(this.target, args);
  32517. }
  32518. }
  32519. }
  32520. function _onceWrap(target, type, listener) {
  32521. var state = {
  32522. fired: false,
  32523. wrapFn: undefined,
  32524. target: target,
  32525. type: type,
  32526. listener: listener
  32527. };
  32528. var wrapped = bind.call(onceWrapper, state);
  32529. wrapped.listener = listener;
  32530. state.wrapFn = wrapped;
  32531. return wrapped;
  32532. }
  32533. EventEmitter.prototype.once = function once(type, listener) {
  32534. if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
  32535. this.on(type, _onceWrap(this, type, listener));
  32536. return this;
  32537. };
  32538. EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
  32539. if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
  32540. this.prependListener(type, _onceWrap(this, type, listener));
  32541. return this;
  32542. };
  32543. // Emits a 'removeListener' event if and only if the listener was removed.
  32544. EventEmitter.prototype.removeListener = function removeListener(type, listener) {
  32545. var list, events, position, i, originalListener;
  32546. if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
  32547. events = this._events;
  32548. if (!events) return this;
  32549. list = events[type];
  32550. if (!list) return this;
  32551. if (list === listener || list.listener === listener) {
  32552. if (--this._eventsCount === 0) this._events = objectCreate(null);else {
  32553. delete events[type];
  32554. if (events.removeListener) this.emit('removeListener', type, list.listener || listener);
  32555. }
  32556. } else if (typeof list !== 'function') {
  32557. position = -1;
  32558. for (i = list.length - 1; i >= 0; i--) {
  32559. if (list[i] === listener || list[i].listener === listener) {
  32560. originalListener = list[i].listener;
  32561. position = i;
  32562. break;
  32563. }
  32564. }
  32565. if (position < 0) return this;
  32566. if (position === 0) list.shift();else spliceOne(list, position);
  32567. if (list.length === 1) events[type] = list[0];
  32568. if (events.removeListener) this.emit('removeListener', type, originalListener || listener);
  32569. }
  32570. return this;
  32571. };
  32572. EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
  32573. var listeners, events, i;
  32574. events = this._events;
  32575. if (!events) return this;
  32576. // not listening for removeListener, no need to emit
  32577. if (!events.removeListener) {
  32578. if (arguments.length === 0) {
  32579. this._events = objectCreate(null);
  32580. this._eventsCount = 0;
  32581. } else if (events[type]) {
  32582. if (--this._eventsCount === 0) this._events = objectCreate(null);else delete events[type];
  32583. }
  32584. return this;
  32585. }
  32586. // emit removeListener for all listeners on all events
  32587. if (arguments.length === 0) {
  32588. var keys = objectKeys(events);
  32589. var key;
  32590. for (i = 0; i < keys.length; ++i) {
  32591. key = keys[i];
  32592. if (key === 'removeListener') continue;
  32593. this.removeAllListeners(key);
  32594. }
  32595. this.removeAllListeners('removeListener');
  32596. this._events = objectCreate(null);
  32597. this._eventsCount = 0;
  32598. return this;
  32599. }
  32600. listeners = events[type];
  32601. if (typeof listeners === 'function') {
  32602. this.removeListener(type, listeners);
  32603. } else if (listeners) {
  32604. // LIFO order
  32605. for (i = listeners.length - 1; i >= 0; i--) {
  32606. this.removeListener(type, listeners[i]);
  32607. }
  32608. }
  32609. return this;
  32610. };
  32611. function _listeners(target, type, unwrap) {
  32612. var events = target._events;
  32613. if (!events) return [];
  32614. var evlistener = events[type];
  32615. if (!evlistener) return [];
  32616. if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  32617. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  32618. }
  32619. EventEmitter.prototype.listeners = function listeners(type) {
  32620. return _listeners(this, type, true);
  32621. };
  32622. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  32623. return _listeners(this, type, false);
  32624. };
  32625. EventEmitter.listenerCount = function (emitter, type) {
  32626. if (typeof emitter.listenerCount === 'function') {
  32627. return emitter.listenerCount(type);
  32628. } else {
  32629. return listenerCount.call(emitter, type);
  32630. }
  32631. };
  32632. EventEmitter.prototype.listenerCount = listenerCount;
  32633. function listenerCount(type) {
  32634. var events = this._events;
  32635. if (events) {
  32636. var evlistener = events[type];
  32637. if (typeof evlistener === 'function') {
  32638. return 1;
  32639. } else if (evlistener) {
  32640. return evlistener.length;
  32641. }
  32642. }
  32643. return 0;
  32644. }
  32645. EventEmitter.prototype.eventNames = function eventNames() {
  32646. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  32647. };
  32648. // About 1.5x faster than the two-arg version of Array#splice().
  32649. function spliceOne(list, index) {
  32650. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k];
  32651. list.pop();
  32652. }
  32653. function arrayClone(arr, n) {
  32654. var copy = new Array(n);
  32655. for (var i = 0; i < n; ++i) copy[i] = arr[i];
  32656. return copy;
  32657. }
  32658. function unwrapListeners(arr) {
  32659. var ret = new Array(arr.length);
  32660. for (var i = 0; i < ret.length; ++i) {
  32661. ret[i] = arr[i].listener || arr[i];
  32662. }
  32663. return ret;
  32664. }
  32665. function objectCreatePolyfill(proto) {
  32666. var F = function () {};
  32667. F.prototype = proto;
  32668. return new F();
  32669. }
  32670. function objectKeysPolyfill(obj) {
  32671. var keys = [];
  32672. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  32673. keys.push(k);
  32674. }
  32675. return k;
  32676. }
  32677. function functionBindPolyfill(context) {
  32678. var fn = this;
  32679. return function () {
  32680. return fn.apply(context, arguments);
  32681. };
  32682. }
  32683. },{}],262:[function(require,module,exports){
  32684. "use strict";
  32685. var Buffer = require('safe-buffer').Buffer;
  32686. var MD5 = require('md5.js');
  32687. /* eslint-disable camelcase */
  32688. function EVP_BytesToKey(password, salt, keyBits, ivLen) {
  32689. if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary');
  32690. if (salt) {
  32691. if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary');
  32692. if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length');
  32693. }
  32694. var keyLen = keyBits / 8;
  32695. var key = Buffer.alloc(keyLen);
  32696. var iv = Buffer.alloc(ivLen || 0);
  32697. var tmp = Buffer.alloc(0);
  32698. while (keyLen > 0 || ivLen > 0) {
  32699. var hash = new MD5();
  32700. hash.update(tmp);
  32701. hash.update(password);
  32702. if (salt) hash.update(salt);
  32703. tmp = hash.digest();
  32704. var used = 0;
  32705. if (keyLen > 0) {
  32706. var keyStart = key.length - keyLen;
  32707. used = Math.min(keyLen, tmp.length);
  32708. tmp.copy(key, keyStart, 0, used);
  32709. keyLen -= used;
  32710. }
  32711. if (used < tmp.length && ivLen > 0) {
  32712. var ivStart = iv.length - ivLen;
  32713. var length = Math.min(ivLen, tmp.length - used);
  32714. tmp.copy(iv, ivStart, used, used + length);
  32715. ivLen -= length;
  32716. }
  32717. }
  32718. tmp.fill(0);
  32719. return {
  32720. key: key,
  32721. iv: iv
  32722. };
  32723. }
  32724. module.exports = EVP_BytesToKey;
  32725. },{"md5.js":289,"safe-buffer":332}],263:[function(require,module,exports){
  32726. "use strict";
  32727. Object.defineProperty(exports, "__esModule", {
  32728. value: true
  32729. });
  32730. exports.CsvParserStream = exports.ParserOptions = exports.parseFile = exports.parseStream = exports.parseString = exports.parse = exports.FormatterOptions = exports.CsvFormatterStream = exports.writeToPath = exports.writeToString = exports.writeToBuffer = exports.writeToStream = exports.write = exports.format = void 0;
  32731. var format_1 = require("@fast-csv/format");
  32732. Object.defineProperty(exports, "format", {
  32733. enumerable: true,
  32734. get: function () {
  32735. return format_1.format;
  32736. }
  32737. });
  32738. Object.defineProperty(exports, "write", {
  32739. enumerable: true,
  32740. get: function () {
  32741. return format_1.write;
  32742. }
  32743. });
  32744. Object.defineProperty(exports, "writeToStream", {
  32745. enumerable: true,
  32746. get: function () {
  32747. return format_1.writeToStream;
  32748. }
  32749. });
  32750. Object.defineProperty(exports, "writeToBuffer", {
  32751. enumerable: true,
  32752. get: function () {
  32753. return format_1.writeToBuffer;
  32754. }
  32755. });
  32756. Object.defineProperty(exports, "writeToString", {
  32757. enumerable: true,
  32758. get: function () {
  32759. return format_1.writeToString;
  32760. }
  32761. });
  32762. Object.defineProperty(exports, "writeToPath", {
  32763. enumerable: true,
  32764. get: function () {
  32765. return format_1.writeToPath;
  32766. }
  32767. });
  32768. Object.defineProperty(exports, "CsvFormatterStream", {
  32769. enumerable: true,
  32770. get: function () {
  32771. return format_1.CsvFormatterStream;
  32772. }
  32773. });
  32774. Object.defineProperty(exports, "FormatterOptions", {
  32775. enumerable: true,
  32776. get: function () {
  32777. return format_1.FormatterOptions;
  32778. }
  32779. });
  32780. var parse_1 = require("@fast-csv/parse");
  32781. Object.defineProperty(exports, "parse", {
  32782. enumerable: true,
  32783. get: function () {
  32784. return parse_1.parse;
  32785. }
  32786. });
  32787. Object.defineProperty(exports, "parseString", {
  32788. enumerable: true,
  32789. get: function () {
  32790. return parse_1.parseString;
  32791. }
  32792. });
  32793. Object.defineProperty(exports, "parseStream", {
  32794. enumerable: true,
  32795. get: function () {
  32796. return parse_1.parseStream;
  32797. }
  32798. });
  32799. Object.defineProperty(exports, "parseFile", {
  32800. enumerable: true,
  32801. get: function () {
  32802. return parse_1.parseFile;
  32803. }
  32804. });
  32805. Object.defineProperty(exports, "ParserOptions", {
  32806. enumerable: true,
  32807. get: function () {
  32808. return parse_1.ParserOptions;
  32809. }
  32810. });
  32811. Object.defineProperty(exports, "CsvParserStream", {
  32812. enumerable: true,
  32813. get: function () {
  32814. return parse_1.CsvParserStream;
  32815. }
  32816. });
  32817. },{"@fast-csv/format":151,"@fast-csv/parse":155}],264:[function(require,module,exports){
  32818. 'use strict';
  32819. var Buffer = require('safe-buffer').Buffer;
  32820. var Transform = require('readable-stream').Transform;
  32821. var inherits = require('inherits');
  32822. function throwIfNotStringOrBuffer(val, prefix) {
  32823. if (!Buffer.isBuffer(val) && typeof val !== 'string') {
  32824. throw new TypeError(prefix + ' must be a string or a buffer');
  32825. }
  32826. }
  32827. function HashBase(blockSize) {
  32828. Transform.call(this);
  32829. this._block = Buffer.allocUnsafe(blockSize);
  32830. this._blockSize = blockSize;
  32831. this._blockOffset = 0;
  32832. this._length = [0, 0, 0, 0];
  32833. this._finalized = false;
  32834. }
  32835. inherits(HashBase, Transform);
  32836. HashBase.prototype._transform = function (chunk, encoding, callback) {
  32837. var error = null;
  32838. try {
  32839. this.update(chunk, encoding);
  32840. } catch (err) {
  32841. error = err;
  32842. }
  32843. callback(error);
  32844. };
  32845. HashBase.prototype._flush = function (callback) {
  32846. var error = null;
  32847. try {
  32848. this.push(this.digest());
  32849. } catch (err) {
  32850. error = err;
  32851. }
  32852. callback(error);
  32853. };
  32854. HashBase.prototype.update = function (data, encoding) {
  32855. throwIfNotStringOrBuffer(data, 'Data');
  32856. if (this._finalized) throw new Error('Digest already called');
  32857. if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding);
  32858. // consume data
  32859. var block = this._block;
  32860. var offset = 0;
  32861. while (this._blockOffset + data.length - offset >= this._blockSize) {
  32862. for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++];
  32863. this._update();
  32864. this._blockOffset = 0;
  32865. }
  32866. while (offset < data.length) block[this._blockOffset++] = data[offset++];
  32867. // update length
  32868. for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
  32869. this._length[j] += carry;
  32870. carry = this._length[j] / 0x0100000000 | 0;
  32871. if (carry > 0) this._length[j] -= 0x0100000000 * carry;
  32872. }
  32873. return this;
  32874. };
  32875. HashBase.prototype._update = function () {
  32876. throw new Error('_update is not implemented');
  32877. };
  32878. HashBase.prototype.digest = function (encoding) {
  32879. if (this._finalized) throw new Error('Digest already called');
  32880. this._finalized = true;
  32881. var digest = this._digest();
  32882. if (encoding !== undefined) digest = digest.toString(encoding);
  32883. // reset state
  32884. this._block.fill(0);
  32885. this._blockOffset = 0;
  32886. for (var i = 0; i < 4; ++i) this._length[i] = 0;
  32887. return digest;
  32888. };
  32889. HashBase.prototype._digest = function () {
  32890. throw new Error('_digest is not implemented');
  32891. };
  32892. module.exports = HashBase;
  32893. },{"inherits":279,"readable-stream":330,"safe-buffer":332}],265:[function(require,module,exports){
  32894. "use strict";
  32895. var hash = exports;
  32896. hash.utils = require('./hash/utils');
  32897. hash.common = require('./hash/common');
  32898. hash.sha = require('./hash/sha');
  32899. hash.ripemd = require('./hash/ripemd');
  32900. hash.hmac = require('./hash/hmac');
  32901. // Proxy hash functions to the main object
  32902. hash.sha1 = hash.sha.sha1;
  32903. hash.sha256 = hash.sha.sha256;
  32904. hash.sha224 = hash.sha.sha224;
  32905. hash.sha384 = hash.sha.sha384;
  32906. hash.sha512 = hash.sha.sha512;
  32907. hash.ripemd160 = hash.ripemd.ripemd160;
  32908. },{"./hash/common":266,"./hash/hmac":267,"./hash/ripemd":268,"./hash/sha":269,"./hash/utils":276}],266:[function(require,module,exports){
  32909. 'use strict';
  32910. var utils = require('./utils');
  32911. var assert = require('minimalistic-assert');
  32912. function BlockHash() {
  32913. this.pending = null;
  32914. this.pendingTotal = 0;
  32915. this.blockSize = this.constructor.blockSize;
  32916. this.outSize = this.constructor.outSize;
  32917. this.hmacStrength = this.constructor.hmacStrength;
  32918. this.padLength = this.constructor.padLength / 8;
  32919. this.endian = 'big';
  32920. this._delta8 = this.blockSize / 8;
  32921. this._delta32 = this.blockSize / 32;
  32922. }
  32923. exports.BlockHash = BlockHash;
  32924. BlockHash.prototype.update = function update(msg, enc) {
  32925. // Convert message to array, pad it, and join into 32bit blocks
  32926. msg = utils.toArray(msg, enc);
  32927. if (!this.pending) this.pending = msg;else this.pending = this.pending.concat(msg);
  32928. this.pendingTotal += msg.length;
  32929. // Enough data, try updating
  32930. if (this.pending.length >= this._delta8) {
  32931. msg = this.pending;
  32932. // Process pending data in blocks
  32933. var r = msg.length % this._delta8;
  32934. this.pending = msg.slice(msg.length - r, msg.length);
  32935. if (this.pending.length === 0) this.pending = null;
  32936. msg = utils.join32(msg, 0, msg.length - r, this.endian);
  32937. for (var i = 0; i < msg.length; i += this._delta32) this._update(msg, i, i + this._delta32);
  32938. }
  32939. return this;
  32940. };
  32941. BlockHash.prototype.digest = function digest(enc) {
  32942. this.update(this._pad());
  32943. assert(this.pending === null);
  32944. return this._digest(enc);
  32945. };
  32946. BlockHash.prototype._pad = function pad() {
  32947. var len = this.pendingTotal;
  32948. var bytes = this._delta8;
  32949. var k = bytes - (len + this.padLength) % bytes;
  32950. var res = new Array(k + this.padLength);
  32951. res[0] = 0x80;
  32952. for (var i = 1; i < k; i++) res[i] = 0;
  32953. // Append length
  32954. len <<= 3;
  32955. if (this.endian === 'big') {
  32956. for (var t = 8; t < this.padLength; t++) res[i++] = 0;
  32957. res[i++] = 0;
  32958. res[i++] = 0;
  32959. res[i++] = 0;
  32960. res[i++] = 0;
  32961. res[i++] = len >>> 24 & 0xff;
  32962. res[i++] = len >>> 16 & 0xff;
  32963. res[i++] = len >>> 8 & 0xff;
  32964. res[i++] = len & 0xff;
  32965. } else {
  32966. res[i++] = len & 0xff;
  32967. res[i++] = len >>> 8 & 0xff;
  32968. res[i++] = len >>> 16 & 0xff;
  32969. res[i++] = len >>> 24 & 0xff;
  32970. res[i++] = 0;
  32971. res[i++] = 0;
  32972. res[i++] = 0;
  32973. res[i++] = 0;
  32974. for (t = 8; t < this.padLength; t++) res[i++] = 0;
  32975. }
  32976. return res;
  32977. };
  32978. },{"./utils":276,"minimalistic-assert":292}],267:[function(require,module,exports){
  32979. 'use strict';
  32980. var utils = require('./utils');
  32981. var assert = require('minimalistic-assert');
  32982. function Hmac(hash, key, enc) {
  32983. if (!(this instanceof Hmac)) return new Hmac(hash, key, enc);
  32984. this.Hash = hash;
  32985. this.blockSize = hash.blockSize / 8;
  32986. this.outSize = hash.outSize / 8;
  32987. this.inner = null;
  32988. this.outer = null;
  32989. this._init(utils.toArray(key, enc));
  32990. }
  32991. module.exports = Hmac;
  32992. Hmac.prototype._init = function init(key) {
  32993. // Shorten key, if needed
  32994. if (key.length > this.blockSize) key = new this.Hash().update(key).digest();
  32995. assert(key.length <= this.blockSize);
  32996. // Add padding to key
  32997. for (var i = key.length; i < this.blockSize; i++) key.push(0);
  32998. for (i = 0; i < key.length; i++) key[i] ^= 0x36;
  32999. this.inner = new this.Hash().update(key);
  33000. // 0x36 ^ 0x5c = 0x6a
  33001. for (i = 0; i < key.length; i++) key[i] ^= 0x6a;
  33002. this.outer = new this.Hash().update(key);
  33003. };
  33004. Hmac.prototype.update = function update(msg, enc) {
  33005. this.inner.update(msg, enc);
  33006. return this;
  33007. };
  33008. Hmac.prototype.digest = function digest(enc) {
  33009. this.outer.update(this.inner.digest());
  33010. return this.outer.digest(enc);
  33011. };
  33012. },{"./utils":276,"minimalistic-assert":292}],268:[function(require,module,exports){
  33013. 'use strict';
  33014. var utils = require('./utils');
  33015. var common = require('./common');
  33016. var rotl32 = utils.rotl32;
  33017. var sum32 = utils.sum32;
  33018. var sum32_3 = utils.sum32_3;
  33019. var sum32_4 = utils.sum32_4;
  33020. var BlockHash = common.BlockHash;
  33021. function RIPEMD160() {
  33022. if (!(this instanceof RIPEMD160)) return new RIPEMD160();
  33023. BlockHash.call(this);
  33024. this.h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
  33025. this.endian = 'little';
  33026. }
  33027. utils.inherits(RIPEMD160, BlockHash);
  33028. exports.ripemd160 = RIPEMD160;
  33029. RIPEMD160.blockSize = 512;
  33030. RIPEMD160.outSize = 160;
  33031. RIPEMD160.hmacStrength = 192;
  33032. RIPEMD160.padLength = 64;
  33033. RIPEMD160.prototype._update = function update(msg, start) {
  33034. var A = this.h[0];
  33035. var B = this.h[1];
  33036. var C = this.h[2];
  33037. var D = this.h[3];
  33038. var E = this.h[4];
  33039. var Ah = A;
  33040. var Bh = B;
  33041. var Ch = C;
  33042. var Dh = D;
  33043. var Eh = E;
  33044. for (var j = 0; j < 80; j++) {
  33045. var T = sum32(rotl32(sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), s[j]), E);
  33046. A = E;
  33047. E = D;
  33048. D = rotl32(C, 10);
  33049. C = B;
  33050. B = T;
  33051. T = sum32(rotl32(sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), sh[j]), Eh);
  33052. Ah = Eh;
  33053. Eh = Dh;
  33054. Dh = rotl32(Ch, 10);
  33055. Ch = Bh;
  33056. Bh = T;
  33057. }
  33058. T = sum32_3(this.h[1], C, Dh);
  33059. this.h[1] = sum32_3(this.h[2], D, Eh);
  33060. this.h[2] = sum32_3(this.h[3], E, Ah);
  33061. this.h[3] = sum32_3(this.h[4], A, Bh);
  33062. this.h[4] = sum32_3(this.h[0], B, Ch);
  33063. this.h[0] = T;
  33064. };
  33065. RIPEMD160.prototype._digest = function digest(enc) {
  33066. if (enc === 'hex') return utils.toHex32(this.h, 'little');else return utils.split32(this.h, 'little');
  33067. };
  33068. function f(j, x, y, z) {
  33069. if (j <= 15) return x ^ y ^ z;else if (j <= 31) return x & y | ~x & z;else if (j <= 47) return (x | ~y) ^ z;else if (j <= 63) return x & z | y & ~z;else return x ^ (y | ~z);
  33070. }
  33071. function K(j) {
  33072. if (j <= 15) return 0x00000000;else if (j <= 31) return 0x5a827999;else if (j <= 47) return 0x6ed9eba1;else if (j <= 63) return 0x8f1bbcdc;else return 0xa953fd4e;
  33073. }
  33074. function Kh(j) {
  33075. if (j <= 15) return 0x50a28be6;else if (j <= 31) return 0x5c4dd124;else if (j <= 47) return 0x6d703ef3;else if (j <= 63) return 0x7a6d76e9;else return 0x00000000;
  33076. }
  33077. var r = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13];
  33078. var rh = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11];
  33079. var s = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6];
  33080. var sh = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11];
  33081. },{"./common":266,"./utils":276}],269:[function(require,module,exports){
  33082. 'use strict';
  33083. exports.sha1 = require('./sha/1');
  33084. exports.sha224 = require('./sha/224');
  33085. exports.sha256 = require('./sha/256');
  33086. exports.sha384 = require('./sha/384');
  33087. exports.sha512 = require('./sha/512');
  33088. },{"./sha/1":270,"./sha/224":271,"./sha/256":272,"./sha/384":273,"./sha/512":274}],270:[function(require,module,exports){
  33089. 'use strict';
  33090. var utils = require('../utils');
  33091. var common = require('../common');
  33092. var shaCommon = require('./common');
  33093. var rotl32 = utils.rotl32;
  33094. var sum32 = utils.sum32;
  33095. var sum32_5 = utils.sum32_5;
  33096. var ft_1 = shaCommon.ft_1;
  33097. var BlockHash = common.BlockHash;
  33098. var sha1_K = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6];
  33099. function SHA1() {
  33100. if (!(this instanceof SHA1)) return new SHA1();
  33101. BlockHash.call(this);
  33102. this.h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
  33103. this.W = new Array(80);
  33104. }
  33105. utils.inherits(SHA1, BlockHash);
  33106. module.exports = SHA1;
  33107. SHA1.blockSize = 512;
  33108. SHA1.outSize = 160;
  33109. SHA1.hmacStrength = 80;
  33110. SHA1.padLength = 64;
  33111. SHA1.prototype._update = function _update(msg, start) {
  33112. var W = this.W;
  33113. for (var i = 0; i < 16; i++) W[i] = msg[start + i];
  33114. for (; i < W.length; i++) W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
  33115. var a = this.h[0];
  33116. var b = this.h[1];
  33117. var c = this.h[2];
  33118. var d = this.h[3];
  33119. var e = this.h[4];
  33120. for (i = 0; i < W.length; i++) {
  33121. var s = ~~(i / 20);
  33122. var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
  33123. e = d;
  33124. d = c;
  33125. c = rotl32(b, 30);
  33126. b = a;
  33127. a = t;
  33128. }
  33129. this.h[0] = sum32(this.h[0], a);
  33130. this.h[1] = sum32(this.h[1], b);
  33131. this.h[2] = sum32(this.h[2], c);
  33132. this.h[3] = sum32(this.h[3], d);
  33133. this.h[4] = sum32(this.h[4], e);
  33134. };
  33135. SHA1.prototype._digest = function digest(enc) {
  33136. if (enc === 'hex') return utils.toHex32(this.h, 'big');else return utils.split32(this.h, 'big');
  33137. };
  33138. },{"../common":266,"../utils":276,"./common":275}],271:[function(require,module,exports){
  33139. 'use strict';
  33140. var utils = require('../utils');
  33141. var SHA256 = require('./256');
  33142. function SHA224() {
  33143. if (!(this instanceof SHA224)) return new SHA224();
  33144. SHA256.call(this);
  33145. this.h = [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4];
  33146. }
  33147. utils.inherits(SHA224, SHA256);
  33148. module.exports = SHA224;
  33149. SHA224.blockSize = 512;
  33150. SHA224.outSize = 224;
  33151. SHA224.hmacStrength = 192;
  33152. SHA224.padLength = 64;
  33153. SHA224.prototype._digest = function digest(enc) {
  33154. // Just truncate output
  33155. if (enc === 'hex') return utils.toHex32(this.h.slice(0, 7), 'big');else return utils.split32(this.h.slice(0, 7), 'big');
  33156. };
  33157. },{"../utils":276,"./256":272}],272:[function(require,module,exports){
  33158. 'use strict';
  33159. var utils = require('../utils');
  33160. var common = require('../common');
  33161. var shaCommon = require('./common');
  33162. var assert = require('minimalistic-assert');
  33163. var sum32 = utils.sum32;
  33164. var sum32_4 = utils.sum32_4;
  33165. var sum32_5 = utils.sum32_5;
  33166. var ch32 = shaCommon.ch32;
  33167. var maj32 = shaCommon.maj32;
  33168. var s0_256 = shaCommon.s0_256;
  33169. var s1_256 = shaCommon.s1_256;
  33170. var g0_256 = shaCommon.g0_256;
  33171. var g1_256 = shaCommon.g1_256;
  33172. var BlockHash = common.BlockHash;
  33173. var sha256_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
  33174. function SHA256() {
  33175. if (!(this instanceof SHA256)) return new SHA256();
  33176. BlockHash.call(this);
  33177. this.h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
  33178. this.k = sha256_K;
  33179. this.W = new Array(64);
  33180. }
  33181. utils.inherits(SHA256, BlockHash);
  33182. module.exports = SHA256;
  33183. SHA256.blockSize = 512;
  33184. SHA256.outSize = 256;
  33185. SHA256.hmacStrength = 192;
  33186. SHA256.padLength = 64;
  33187. SHA256.prototype._update = function _update(msg, start) {
  33188. var W = this.W;
  33189. for (var i = 0; i < 16; i++) W[i] = msg[start + i];
  33190. for (; i < W.length; i++) W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
  33191. var a = this.h[0];
  33192. var b = this.h[1];
  33193. var c = this.h[2];
  33194. var d = this.h[3];
  33195. var e = this.h[4];
  33196. var f = this.h[5];
  33197. var g = this.h[6];
  33198. var h = this.h[7];
  33199. assert(this.k.length === W.length);
  33200. for (i = 0; i < W.length; i++) {
  33201. var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
  33202. var T2 = sum32(s0_256(a), maj32(a, b, c));
  33203. h = g;
  33204. g = f;
  33205. f = e;
  33206. e = sum32(d, T1);
  33207. d = c;
  33208. c = b;
  33209. b = a;
  33210. a = sum32(T1, T2);
  33211. }
  33212. this.h[0] = sum32(this.h[0], a);
  33213. this.h[1] = sum32(this.h[1], b);
  33214. this.h[2] = sum32(this.h[2], c);
  33215. this.h[3] = sum32(this.h[3], d);
  33216. this.h[4] = sum32(this.h[4], e);
  33217. this.h[5] = sum32(this.h[5], f);
  33218. this.h[6] = sum32(this.h[6], g);
  33219. this.h[7] = sum32(this.h[7], h);
  33220. };
  33221. SHA256.prototype._digest = function digest(enc) {
  33222. if (enc === 'hex') return utils.toHex32(this.h, 'big');else return utils.split32(this.h, 'big');
  33223. };
  33224. },{"../common":266,"../utils":276,"./common":275,"minimalistic-assert":292}],273:[function(require,module,exports){
  33225. 'use strict';
  33226. var utils = require('../utils');
  33227. var SHA512 = require('./512');
  33228. function SHA384() {
  33229. if (!(this instanceof SHA384)) return new SHA384();
  33230. SHA512.call(this);
  33231. this.h = [0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4];
  33232. }
  33233. utils.inherits(SHA384, SHA512);
  33234. module.exports = SHA384;
  33235. SHA384.blockSize = 1024;
  33236. SHA384.outSize = 384;
  33237. SHA384.hmacStrength = 192;
  33238. SHA384.padLength = 128;
  33239. SHA384.prototype._digest = function digest(enc) {
  33240. if (enc === 'hex') return utils.toHex32(this.h.slice(0, 12), 'big');else return utils.split32(this.h.slice(0, 12), 'big');
  33241. };
  33242. },{"../utils":276,"./512":274}],274:[function(require,module,exports){
  33243. 'use strict';
  33244. var utils = require('../utils');
  33245. var common = require('../common');
  33246. var assert = require('minimalistic-assert');
  33247. var rotr64_hi = utils.rotr64_hi;
  33248. var rotr64_lo = utils.rotr64_lo;
  33249. var shr64_hi = utils.shr64_hi;
  33250. var shr64_lo = utils.shr64_lo;
  33251. var sum64 = utils.sum64;
  33252. var sum64_hi = utils.sum64_hi;
  33253. var sum64_lo = utils.sum64_lo;
  33254. var sum64_4_hi = utils.sum64_4_hi;
  33255. var sum64_4_lo = utils.sum64_4_lo;
  33256. var sum64_5_hi = utils.sum64_5_hi;
  33257. var sum64_5_lo = utils.sum64_5_lo;
  33258. var BlockHash = common.BlockHash;
  33259. var sha512_K = [0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817];
  33260. function SHA512() {
  33261. if (!(this instanceof SHA512)) return new SHA512();
  33262. BlockHash.call(this);
  33263. this.h = [0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179];
  33264. this.k = sha512_K;
  33265. this.W = new Array(160);
  33266. }
  33267. utils.inherits(SHA512, BlockHash);
  33268. module.exports = SHA512;
  33269. SHA512.blockSize = 1024;
  33270. SHA512.outSize = 512;
  33271. SHA512.hmacStrength = 192;
  33272. SHA512.padLength = 128;
  33273. SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
  33274. var W = this.W;
  33275. // 32 x 32bit words
  33276. for (var i = 0; i < 32; i++) W[i] = msg[start + i];
  33277. for (; i < W.length; i += 2) {
  33278. var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
  33279. var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
  33280. var c1_hi = W[i - 14]; // i - 7
  33281. var c1_lo = W[i - 13];
  33282. var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
  33283. var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
  33284. var c3_hi = W[i - 32]; // i - 16
  33285. var c3_lo = W[i - 31];
  33286. W[i] = sum64_4_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo);
  33287. W[i + 1] = sum64_4_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo);
  33288. }
  33289. };
  33290. SHA512.prototype._update = function _update(msg, start) {
  33291. this._prepareBlock(msg, start);
  33292. var W = this.W;
  33293. var ah = this.h[0];
  33294. var al = this.h[1];
  33295. var bh = this.h[2];
  33296. var bl = this.h[3];
  33297. var ch = this.h[4];
  33298. var cl = this.h[5];
  33299. var dh = this.h[6];
  33300. var dl = this.h[7];
  33301. var eh = this.h[8];
  33302. var el = this.h[9];
  33303. var fh = this.h[10];
  33304. var fl = this.h[11];
  33305. var gh = this.h[12];
  33306. var gl = this.h[13];
  33307. var hh = this.h[14];
  33308. var hl = this.h[15];
  33309. assert(this.k.length === W.length);
  33310. for (var i = 0; i < W.length; i += 2) {
  33311. var c0_hi = hh;
  33312. var c0_lo = hl;
  33313. var c1_hi = s1_512_hi(eh, el);
  33314. var c1_lo = s1_512_lo(eh, el);
  33315. var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
  33316. var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
  33317. var c3_hi = this.k[i];
  33318. var c3_lo = this.k[i + 1];
  33319. var c4_hi = W[i];
  33320. var c4_lo = W[i + 1];
  33321. var T1_hi = sum64_5_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo);
  33322. var T1_lo = sum64_5_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo);
  33323. c0_hi = s0_512_hi(ah, al);
  33324. c0_lo = s0_512_lo(ah, al);
  33325. c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
  33326. c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
  33327. var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
  33328. var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
  33329. hh = gh;
  33330. hl = gl;
  33331. gh = fh;
  33332. gl = fl;
  33333. fh = eh;
  33334. fl = el;
  33335. eh = sum64_hi(dh, dl, T1_hi, T1_lo);
  33336. el = sum64_lo(dl, dl, T1_hi, T1_lo);
  33337. dh = ch;
  33338. dl = cl;
  33339. ch = bh;
  33340. cl = bl;
  33341. bh = ah;
  33342. bl = al;
  33343. ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
  33344. al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
  33345. }
  33346. sum64(this.h, 0, ah, al);
  33347. sum64(this.h, 2, bh, bl);
  33348. sum64(this.h, 4, ch, cl);
  33349. sum64(this.h, 6, dh, dl);
  33350. sum64(this.h, 8, eh, el);
  33351. sum64(this.h, 10, fh, fl);
  33352. sum64(this.h, 12, gh, gl);
  33353. sum64(this.h, 14, hh, hl);
  33354. };
  33355. SHA512.prototype._digest = function digest(enc) {
  33356. if (enc === 'hex') return utils.toHex32(this.h, 'big');else return utils.split32(this.h, 'big');
  33357. };
  33358. function ch64_hi(xh, xl, yh, yl, zh) {
  33359. var r = xh & yh ^ ~xh & zh;
  33360. if (r < 0) r += 0x100000000;
  33361. return r;
  33362. }
  33363. function ch64_lo(xh, xl, yh, yl, zh, zl) {
  33364. var r = xl & yl ^ ~xl & zl;
  33365. if (r < 0) r += 0x100000000;
  33366. return r;
  33367. }
  33368. function maj64_hi(xh, xl, yh, yl, zh) {
  33369. var r = xh & yh ^ xh & zh ^ yh & zh;
  33370. if (r < 0) r += 0x100000000;
  33371. return r;
  33372. }
  33373. function maj64_lo(xh, xl, yh, yl, zh, zl) {
  33374. var r = xl & yl ^ xl & zl ^ yl & zl;
  33375. if (r < 0) r += 0x100000000;
  33376. return r;
  33377. }
  33378. function s0_512_hi(xh, xl) {
  33379. var c0_hi = rotr64_hi(xh, xl, 28);
  33380. var c1_hi = rotr64_hi(xl, xh, 2); // 34
  33381. var c2_hi = rotr64_hi(xl, xh, 7); // 39
  33382. var r = c0_hi ^ c1_hi ^ c2_hi;
  33383. if (r < 0) r += 0x100000000;
  33384. return r;
  33385. }
  33386. function s0_512_lo(xh, xl) {
  33387. var c0_lo = rotr64_lo(xh, xl, 28);
  33388. var c1_lo = rotr64_lo(xl, xh, 2); // 34
  33389. var c2_lo = rotr64_lo(xl, xh, 7); // 39
  33390. var r = c0_lo ^ c1_lo ^ c2_lo;
  33391. if (r < 0) r += 0x100000000;
  33392. return r;
  33393. }
  33394. function s1_512_hi(xh, xl) {
  33395. var c0_hi = rotr64_hi(xh, xl, 14);
  33396. var c1_hi = rotr64_hi(xh, xl, 18);
  33397. var c2_hi = rotr64_hi(xl, xh, 9); // 41
  33398. var r = c0_hi ^ c1_hi ^ c2_hi;
  33399. if (r < 0) r += 0x100000000;
  33400. return r;
  33401. }
  33402. function s1_512_lo(xh, xl) {
  33403. var c0_lo = rotr64_lo(xh, xl, 14);
  33404. var c1_lo = rotr64_lo(xh, xl, 18);
  33405. var c2_lo = rotr64_lo(xl, xh, 9); // 41
  33406. var r = c0_lo ^ c1_lo ^ c2_lo;
  33407. if (r < 0) r += 0x100000000;
  33408. return r;
  33409. }
  33410. function g0_512_hi(xh, xl) {
  33411. var c0_hi = rotr64_hi(xh, xl, 1);
  33412. var c1_hi = rotr64_hi(xh, xl, 8);
  33413. var c2_hi = shr64_hi(xh, xl, 7);
  33414. var r = c0_hi ^ c1_hi ^ c2_hi;
  33415. if (r < 0) r += 0x100000000;
  33416. return r;
  33417. }
  33418. function g0_512_lo(xh, xl) {
  33419. var c0_lo = rotr64_lo(xh, xl, 1);
  33420. var c1_lo = rotr64_lo(xh, xl, 8);
  33421. var c2_lo = shr64_lo(xh, xl, 7);
  33422. var r = c0_lo ^ c1_lo ^ c2_lo;
  33423. if (r < 0) r += 0x100000000;
  33424. return r;
  33425. }
  33426. function g1_512_hi(xh, xl) {
  33427. var c0_hi = rotr64_hi(xh, xl, 19);
  33428. var c1_hi = rotr64_hi(xl, xh, 29); // 61
  33429. var c2_hi = shr64_hi(xh, xl, 6);
  33430. var r = c0_hi ^ c1_hi ^ c2_hi;
  33431. if (r < 0) r += 0x100000000;
  33432. return r;
  33433. }
  33434. function g1_512_lo(xh, xl) {
  33435. var c0_lo = rotr64_lo(xh, xl, 19);
  33436. var c1_lo = rotr64_lo(xl, xh, 29); // 61
  33437. var c2_lo = shr64_lo(xh, xl, 6);
  33438. var r = c0_lo ^ c1_lo ^ c2_lo;
  33439. if (r < 0) r += 0x100000000;
  33440. return r;
  33441. }
  33442. },{"../common":266,"../utils":276,"minimalistic-assert":292}],275:[function(require,module,exports){
  33443. 'use strict';
  33444. var utils = require('../utils');
  33445. var rotr32 = utils.rotr32;
  33446. function ft_1(s, x, y, z) {
  33447. if (s === 0) return ch32(x, y, z);
  33448. if (s === 1 || s === 3) return p32(x, y, z);
  33449. if (s === 2) return maj32(x, y, z);
  33450. }
  33451. exports.ft_1 = ft_1;
  33452. function ch32(x, y, z) {
  33453. return x & y ^ ~x & z;
  33454. }
  33455. exports.ch32 = ch32;
  33456. function maj32(x, y, z) {
  33457. return x & y ^ x & z ^ y & z;
  33458. }
  33459. exports.maj32 = maj32;
  33460. function p32(x, y, z) {
  33461. return x ^ y ^ z;
  33462. }
  33463. exports.p32 = p32;
  33464. function s0_256(x) {
  33465. return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
  33466. }
  33467. exports.s0_256 = s0_256;
  33468. function s1_256(x) {
  33469. return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
  33470. }
  33471. exports.s1_256 = s1_256;
  33472. function g0_256(x) {
  33473. return rotr32(x, 7) ^ rotr32(x, 18) ^ x >>> 3;
  33474. }
  33475. exports.g0_256 = g0_256;
  33476. function g1_256(x) {
  33477. return rotr32(x, 17) ^ rotr32(x, 19) ^ x >>> 10;
  33478. }
  33479. exports.g1_256 = g1_256;
  33480. },{"../utils":276}],276:[function(require,module,exports){
  33481. 'use strict';
  33482. var assert = require('minimalistic-assert');
  33483. var inherits = require('inherits');
  33484. exports.inherits = inherits;
  33485. function isSurrogatePair(msg, i) {
  33486. if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
  33487. return false;
  33488. }
  33489. if (i < 0 || i + 1 >= msg.length) {
  33490. return false;
  33491. }
  33492. return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
  33493. }
  33494. function toArray(msg, enc) {
  33495. if (Array.isArray(msg)) return msg.slice();
  33496. if (!msg) return [];
  33497. var res = [];
  33498. if (typeof msg === 'string') {
  33499. if (!enc) {
  33500. // Inspired by stringToUtf8ByteArray() in closure-library by Google
  33501. // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
  33502. // Apache License 2.0
  33503. // https://github.com/google/closure-library/blob/master/LICENSE
  33504. var p = 0;
  33505. for (var i = 0; i < msg.length; i++) {
  33506. var c = msg.charCodeAt(i);
  33507. if (c < 128) {
  33508. res[p++] = c;
  33509. } else if (c < 2048) {
  33510. res[p++] = c >> 6 | 192;
  33511. res[p++] = c & 63 | 128;
  33512. } else if (isSurrogatePair(msg, i)) {
  33513. c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
  33514. res[p++] = c >> 18 | 240;
  33515. res[p++] = c >> 12 & 63 | 128;
  33516. res[p++] = c >> 6 & 63 | 128;
  33517. res[p++] = c & 63 | 128;
  33518. } else {
  33519. res[p++] = c >> 12 | 224;
  33520. res[p++] = c >> 6 & 63 | 128;
  33521. res[p++] = c & 63 | 128;
  33522. }
  33523. }
  33524. } else if (enc === 'hex') {
  33525. msg = msg.replace(/[^a-z0-9]+/ig, '');
  33526. if (msg.length % 2 !== 0) msg = '0' + msg;
  33527. for (i = 0; i < msg.length; i += 2) res.push(parseInt(msg[i] + msg[i + 1], 16));
  33528. }
  33529. } else {
  33530. for (i = 0; i < msg.length; i++) res[i] = msg[i] | 0;
  33531. }
  33532. return res;
  33533. }
  33534. exports.toArray = toArray;
  33535. function toHex(msg) {
  33536. var res = '';
  33537. for (var i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16));
  33538. return res;
  33539. }
  33540. exports.toHex = toHex;
  33541. function htonl(w) {
  33542. var res = w >>> 24 | w >>> 8 & 0xff00 | w << 8 & 0xff0000 | (w & 0xff) << 24;
  33543. return res >>> 0;
  33544. }
  33545. exports.htonl = htonl;
  33546. function toHex32(msg, endian) {
  33547. var res = '';
  33548. for (var i = 0; i < msg.length; i++) {
  33549. var w = msg[i];
  33550. if (endian === 'little') w = htonl(w);
  33551. res += zero8(w.toString(16));
  33552. }
  33553. return res;
  33554. }
  33555. exports.toHex32 = toHex32;
  33556. function zero2(word) {
  33557. if (word.length === 1) return '0' + word;else return word;
  33558. }
  33559. exports.zero2 = zero2;
  33560. function zero8(word) {
  33561. if (word.length === 7) return '0' + word;else if (word.length === 6) return '00' + word;else if (word.length === 5) return '000' + word;else if (word.length === 4) return '0000' + word;else if (word.length === 3) return '00000' + word;else if (word.length === 2) return '000000' + word;else if (word.length === 1) return '0000000' + word;else return word;
  33562. }
  33563. exports.zero8 = zero8;
  33564. function join32(msg, start, end, endian) {
  33565. var len = end - start;
  33566. assert(len % 4 === 0);
  33567. var res = new Array(len / 4);
  33568. for (var i = 0, k = start; i < res.length; i++, k += 4) {
  33569. var w;
  33570. if (endian === 'big') w = msg[k] << 24 | msg[k + 1] << 16 | msg[k + 2] << 8 | msg[k + 3];else w = msg[k + 3] << 24 | msg[k + 2] << 16 | msg[k + 1] << 8 | msg[k];
  33571. res[i] = w >>> 0;
  33572. }
  33573. return res;
  33574. }
  33575. exports.join32 = join32;
  33576. function split32(msg, endian) {
  33577. var res = new Array(msg.length * 4);
  33578. for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
  33579. var m = msg[i];
  33580. if (endian === 'big') {
  33581. res[k] = m >>> 24;
  33582. res[k + 1] = m >>> 16 & 0xff;
  33583. res[k + 2] = m >>> 8 & 0xff;
  33584. res[k + 3] = m & 0xff;
  33585. } else {
  33586. res[k + 3] = m >>> 24;
  33587. res[k + 2] = m >>> 16 & 0xff;
  33588. res[k + 1] = m >>> 8 & 0xff;
  33589. res[k] = m & 0xff;
  33590. }
  33591. }
  33592. return res;
  33593. }
  33594. exports.split32 = split32;
  33595. function rotr32(w, b) {
  33596. return w >>> b | w << 32 - b;
  33597. }
  33598. exports.rotr32 = rotr32;
  33599. function rotl32(w, b) {
  33600. return w << b | w >>> 32 - b;
  33601. }
  33602. exports.rotl32 = rotl32;
  33603. function sum32(a, b) {
  33604. return a + b >>> 0;
  33605. }
  33606. exports.sum32 = sum32;
  33607. function sum32_3(a, b, c) {
  33608. return a + b + c >>> 0;
  33609. }
  33610. exports.sum32_3 = sum32_3;
  33611. function sum32_4(a, b, c, d) {
  33612. return a + b + c + d >>> 0;
  33613. }
  33614. exports.sum32_4 = sum32_4;
  33615. function sum32_5(a, b, c, d, e) {
  33616. return a + b + c + d + e >>> 0;
  33617. }
  33618. exports.sum32_5 = sum32_5;
  33619. function sum64(buf, pos, ah, al) {
  33620. var bh = buf[pos];
  33621. var bl = buf[pos + 1];
  33622. var lo = al + bl >>> 0;
  33623. var hi = (lo < al ? 1 : 0) + ah + bh;
  33624. buf[pos] = hi >>> 0;
  33625. buf[pos + 1] = lo;
  33626. }
  33627. exports.sum64 = sum64;
  33628. function sum64_hi(ah, al, bh, bl) {
  33629. var lo = al + bl >>> 0;
  33630. var hi = (lo < al ? 1 : 0) + ah + bh;
  33631. return hi >>> 0;
  33632. }
  33633. exports.sum64_hi = sum64_hi;
  33634. function sum64_lo(ah, al, bh, bl) {
  33635. var lo = al + bl;
  33636. return lo >>> 0;
  33637. }
  33638. exports.sum64_lo = sum64_lo;
  33639. function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
  33640. var carry = 0;
  33641. var lo = al;
  33642. lo = lo + bl >>> 0;
  33643. carry += lo < al ? 1 : 0;
  33644. lo = lo + cl >>> 0;
  33645. carry += lo < cl ? 1 : 0;
  33646. lo = lo + dl >>> 0;
  33647. carry += lo < dl ? 1 : 0;
  33648. var hi = ah + bh + ch + dh + carry;
  33649. return hi >>> 0;
  33650. }
  33651. exports.sum64_4_hi = sum64_4_hi;
  33652. function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
  33653. var lo = al + bl + cl + dl;
  33654. return lo >>> 0;
  33655. }
  33656. exports.sum64_4_lo = sum64_4_lo;
  33657. function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  33658. var carry = 0;
  33659. var lo = al;
  33660. lo = lo + bl >>> 0;
  33661. carry += lo < al ? 1 : 0;
  33662. lo = lo + cl >>> 0;
  33663. carry += lo < cl ? 1 : 0;
  33664. lo = lo + dl >>> 0;
  33665. carry += lo < dl ? 1 : 0;
  33666. lo = lo + el >>> 0;
  33667. carry += lo < el ? 1 : 0;
  33668. var hi = ah + bh + ch + dh + eh + carry;
  33669. return hi >>> 0;
  33670. }
  33671. exports.sum64_5_hi = sum64_5_hi;
  33672. function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  33673. var lo = al + bl + cl + dl + el;
  33674. return lo >>> 0;
  33675. }
  33676. exports.sum64_5_lo = sum64_5_lo;
  33677. function rotr64_hi(ah, al, num) {
  33678. var r = al << 32 - num | ah >>> num;
  33679. return r >>> 0;
  33680. }
  33681. exports.rotr64_hi = rotr64_hi;
  33682. function rotr64_lo(ah, al, num) {
  33683. var r = ah << 32 - num | al >>> num;
  33684. return r >>> 0;
  33685. }
  33686. exports.rotr64_lo = rotr64_lo;
  33687. function shr64_hi(ah, al, num) {
  33688. return ah >>> num;
  33689. }
  33690. exports.shr64_hi = shr64_hi;
  33691. function shr64_lo(ah, al, num) {
  33692. var r = ah << 32 - num | al >>> num;
  33693. return r >>> 0;
  33694. }
  33695. exports.shr64_lo = shr64_lo;
  33696. },{"inherits":279,"minimalistic-assert":292}],277:[function(require,module,exports){
  33697. 'use strict';
  33698. var hash = require('hash.js');
  33699. var utils = require('minimalistic-crypto-utils');
  33700. var assert = require('minimalistic-assert');
  33701. function HmacDRBG(options) {
  33702. if (!(this instanceof HmacDRBG)) return new HmacDRBG(options);
  33703. this.hash = options.hash;
  33704. this.predResist = !!options.predResist;
  33705. this.outLen = this.hash.outSize;
  33706. this.minEntropy = options.minEntropy || this.hash.hmacStrength;
  33707. this._reseed = null;
  33708. this.reseedInterval = null;
  33709. this.K = null;
  33710. this.V = null;
  33711. var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
  33712. var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
  33713. var pers = utils.toArray(options.pers, options.persEnc || 'hex');
  33714. assert(entropy.length >= this.minEntropy / 8, 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  33715. this._init(entropy, nonce, pers);
  33716. }
  33717. module.exports = HmacDRBG;
  33718. HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
  33719. var seed = entropy.concat(nonce).concat(pers);
  33720. this.K = new Array(this.outLen / 8);
  33721. this.V = new Array(this.outLen / 8);
  33722. for (var i = 0; i < this.V.length; i++) {
  33723. this.K[i] = 0x00;
  33724. this.V[i] = 0x01;
  33725. }
  33726. this._update(seed);
  33727. this._reseed = 1;
  33728. this.reseedInterval = 0x1000000000000; // 2^48
  33729. };
  33730. HmacDRBG.prototype._hmac = function hmac() {
  33731. return new hash.hmac(this.hash, this.K);
  33732. };
  33733. HmacDRBG.prototype._update = function update(seed) {
  33734. var kmac = this._hmac().update(this.V).update([0x00]);
  33735. if (seed) kmac = kmac.update(seed);
  33736. this.K = kmac.digest();
  33737. this.V = this._hmac().update(this.V).digest();
  33738. if (!seed) return;
  33739. this.K = this._hmac().update(this.V).update([0x01]).update(seed).digest();
  33740. this.V = this._hmac().update(this.V).digest();
  33741. };
  33742. HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
  33743. // Optional entropy enc
  33744. if (typeof entropyEnc !== 'string') {
  33745. addEnc = add;
  33746. add = entropyEnc;
  33747. entropyEnc = null;
  33748. }
  33749. entropy = utils.toArray(entropy, entropyEnc);
  33750. add = utils.toArray(add, addEnc);
  33751. assert(entropy.length >= this.minEntropy / 8, 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  33752. this._update(entropy.concat(add || []));
  33753. this._reseed = 1;
  33754. };
  33755. HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
  33756. if (this._reseed > this.reseedInterval) throw new Error('Reseed is required');
  33757. // Optional encoding
  33758. if (typeof enc !== 'string') {
  33759. addEnc = add;
  33760. add = enc;
  33761. enc = null;
  33762. }
  33763. // Optional additional data
  33764. if (add) {
  33765. add = utils.toArray(add, addEnc || 'hex');
  33766. this._update(add);
  33767. }
  33768. var temp = [];
  33769. while (temp.length < len) {
  33770. this.V = this._hmac().update(this.V).digest();
  33771. temp = temp.concat(this.V);
  33772. }
  33773. var res = temp.slice(0, len);
  33774. this._update(add);
  33775. this._reseed++;
  33776. return utils.encode(res, enc);
  33777. };
  33778. },{"hash.js":265,"minimalistic-assert":292,"minimalistic-crypto-utils":293}],278:[function(require,module,exports){
  33779. "use strict";
  33780. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  33781. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  33782. var e, m;
  33783. var eLen = nBytes * 8 - mLen - 1;
  33784. var eMax = (1 << eLen) - 1;
  33785. var eBias = eMax >> 1;
  33786. var nBits = -7;
  33787. var i = isLE ? nBytes - 1 : 0;
  33788. var d = isLE ? -1 : 1;
  33789. var s = buffer[offset + i];
  33790. i += d;
  33791. e = s & (1 << -nBits) - 1;
  33792. s >>= -nBits;
  33793. nBits += eLen;
  33794. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  33795. m = e & (1 << -nBits) - 1;
  33796. e >>= -nBits;
  33797. nBits += mLen;
  33798. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  33799. if (e === 0) {
  33800. e = 1 - eBias;
  33801. } else if (e === eMax) {
  33802. return m ? NaN : (s ? -1 : 1) * Infinity;
  33803. } else {
  33804. m = m + Math.pow(2, mLen);
  33805. e = e - eBias;
  33806. }
  33807. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  33808. };
  33809. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  33810. var e, m, c;
  33811. var eLen = nBytes * 8 - mLen - 1;
  33812. var eMax = (1 << eLen) - 1;
  33813. var eBias = eMax >> 1;
  33814. var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  33815. var i = isLE ? 0 : nBytes - 1;
  33816. var d = isLE ? 1 : -1;
  33817. var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  33818. value = Math.abs(value);
  33819. if (isNaN(value) || value === Infinity) {
  33820. m = isNaN(value) ? 1 : 0;
  33821. e = eMax;
  33822. } else {
  33823. e = Math.floor(Math.log(value) / Math.LN2);
  33824. if (value * (c = Math.pow(2, -e)) < 1) {
  33825. e--;
  33826. c *= 2;
  33827. }
  33828. if (e + eBias >= 1) {
  33829. value += rt / c;
  33830. } else {
  33831. value += rt * Math.pow(2, 1 - eBias);
  33832. }
  33833. if (value * c >= 2) {
  33834. e++;
  33835. c /= 2;
  33836. }
  33837. if (e + eBias >= eMax) {
  33838. m = 0;
  33839. e = eMax;
  33840. } else if (e + eBias >= 1) {
  33841. m = (value * c - 1) * Math.pow(2, mLen);
  33842. e = e + eBias;
  33843. } else {
  33844. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  33845. e = 0;
  33846. }
  33847. }
  33848. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  33849. e = e << mLen | m;
  33850. eLen += mLen;
  33851. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  33852. buffer[offset + i - d] |= s * 128;
  33853. };
  33854. },{}],279:[function(require,module,exports){
  33855. "use strict";
  33856. if (typeof Object.create === 'function') {
  33857. // implementation from standard node.js 'util' module
  33858. module.exports = function inherits(ctor, superCtor) {
  33859. if (superCtor) {
  33860. ctor.super_ = superCtor;
  33861. ctor.prototype = Object.create(superCtor.prototype, {
  33862. constructor: {
  33863. value: ctor,
  33864. enumerable: false,
  33865. writable: true,
  33866. configurable: true
  33867. }
  33868. });
  33869. }
  33870. };
  33871. } else {
  33872. // old school shim for old browsers
  33873. module.exports = function inherits(ctor, superCtor) {
  33874. if (superCtor) {
  33875. ctor.super_ = superCtor;
  33876. var TempCtor = function () {};
  33877. TempCtor.prototype = superCtor.prototype;
  33878. ctor.prototype = new TempCtor();
  33879. ctor.prototype.constructor = ctor;
  33880. }
  33881. };
  33882. }
  33883. },{}],280:[function(require,module,exports){
  33884. (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,setImmediate){(function (){
  33885. "use strict";
  33886. /*!
  33887. JSZip v3.10.1 - A JavaScript class for generating and reading zip files
  33888. <http://stuartk.com/jszip>
  33889. (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
  33890. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
  33891. JSZip uses the library pako released under the MIT license :
  33892. https://github.com/nodeca/pako/blob/main/LICENSE
  33893. */
  33894. !function (e) {
  33895. if ("object" == typeof exports && "undefined" != typeof module) module.exports = e();else if ("function" == typeof define && define.amd) define([], e);else {
  33896. ("undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : this).JSZip = e();
  33897. }
  33898. }(function () {
  33899. return function s(a, o, h) {
  33900. function u(r, e) {
  33901. if (!o[r]) {
  33902. if (!a[r]) {
  33903. var t = "function" == typeof require && require;
  33904. if (!e && t) return t(r, !0);
  33905. if (l) return l(r, !0);
  33906. var n = new Error("Cannot find module '" + r + "'");
  33907. throw n.code = "MODULE_NOT_FOUND", n;
  33908. }
  33909. var i = o[r] = {
  33910. exports: {}
  33911. };
  33912. a[r][0].call(i.exports, function (e) {
  33913. var t = a[r][1][e];
  33914. return u(t || e);
  33915. }, i, i.exports, s, a, o, h);
  33916. }
  33917. return o[r].exports;
  33918. }
  33919. for (var l = "function" == typeof require && require, e = 0; e < h.length; e++) u(h[e]);
  33920. return u;
  33921. }({
  33922. 1: [function (e, t, r) {
  33923. "use strict";
  33924. var d = e("./utils"),
  33925. c = e("./support"),
  33926. p = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  33927. r.encode = function (e) {
  33928. for (var t, r, n, i, s, a, o, h = [], u = 0, l = e.length, f = l, c = "string" !== d.getTypeOf(e); u < e.length;) f = l - u, n = c ? (t = e[u++], r = u < l ? e[u++] : 0, u < l ? e[u++] : 0) : (t = e.charCodeAt(u++), r = u < l ? e.charCodeAt(u++) : 0, u < l ? e.charCodeAt(u++) : 0), i = t >> 2, s = (3 & t) << 4 | r >> 4, a = 1 < f ? (15 & r) << 2 | n >> 6 : 64, o = 2 < f ? 63 & n : 64, h.push(p.charAt(i) + p.charAt(s) + p.charAt(a) + p.charAt(o));
  33929. return h.join("");
  33930. }, r.decode = function (e) {
  33931. var t,
  33932. r,
  33933. n,
  33934. i,
  33935. s,
  33936. a,
  33937. o = 0,
  33938. h = 0,
  33939. u = "data:";
  33940. if (e.substr(0, u.length) === u) throw new Error("Invalid base64 input, it looks like a data url.");
  33941. var l,
  33942. f = 3 * (e = e.replace(/[^A-Za-z0-9+/=]/g, "")).length / 4;
  33943. if (e.charAt(e.length - 1) === p.charAt(64) && f--, e.charAt(e.length - 2) === p.charAt(64) && f--, f % 1 != 0) throw new Error("Invalid base64 input, bad content length.");
  33944. for (l = c.uint8array ? new Uint8Array(0 | f) : new Array(0 | f); o < e.length;) t = p.indexOf(e.charAt(o++)) << 2 | (i = p.indexOf(e.charAt(o++))) >> 4, r = (15 & i) << 4 | (s = p.indexOf(e.charAt(o++))) >> 2, n = (3 & s) << 6 | (a = p.indexOf(e.charAt(o++))), l[h++] = t, 64 !== s && (l[h++] = r), 64 !== a && (l[h++] = n);
  33945. return l;
  33946. };
  33947. }, {
  33948. "./support": 30,
  33949. "./utils": 32
  33950. }],
  33951. 2: [function (e, t, r) {
  33952. "use strict";
  33953. var n = e("./external"),
  33954. i = e("./stream/DataWorker"),
  33955. s = e("./stream/Crc32Probe"),
  33956. a = e("./stream/DataLengthProbe");
  33957. function o(e, t, r, n, i) {
  33958. this.compressedSize = e, this.uncompressedSize = t, this.crc32 = r, this.compression = n, this.compressedContent = i;
  33959. }
  33960. o.prototype = {
  33961. getContentWorker: function () {
  33962. var e = new i(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")),
  33963. t = this;
  33964. return e.on("end", function () {
  33965. if (this.streamInfo.data_length !== t.uncompressedSize) throw new Error("Bug : uncompressed data size mismatch");
  33966. }), e;
  33967. },
  33968. getCompressedWorker: function () {
  33969. return new i(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression);
  33970. }
  33971. }, o.createWorkerFrom = function (e, t, r) {
  33972. return e.pipe(new s()).pipe(new a("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new a("compressedSize")).withStreamInfo("compression", t);
  33973. }, t.exports = o;
  33974. }, {
  33975. "./external": 6,
  33976. "./stream/Crc32Probe": 25,
  33977. "./stream/DataLengthProbe": 26,
  33978. "./stream/DataWorker": 27
  33979. }],
  33980. 3: [function (e, t, r) {
  33981. "use strict";
  33982. var n = e("./stream/GenericWorker");
  33983. r.STORE = {
  33984. magic: "\0\0",
  33985. compressWorker: function () {
  33986. return new n("STORE compression");
  33987. },
  33988. uncompressWorker: function () {
  33989. return new n("STORE decompression");
  33990. }
  33991. }, r.DEFLATE = e("./flate");
  33992. }, {
  33993. "./flate": 7,
  33994. "./stream/GenericWorker": 28
  33995. }],
  33996. 4: [function (e, t, r) {
  33997. "use strict";
  33998. var n = e("./utils");
  33999. var o = function () {
  34000. for (var e, t = [], r = 0; r < 256; r++) {
  34001. e = r;
  34002. for (var n = 0; n < 8; n++) e = 1 & e ? 3988292384 ^ e >>> 1 : e >>> 1;
  34003. t[r] = e;
  34004. }
  34005. return t;
  34006. }();
  34007. t.exports = function (e, t) {
  34008. return void 0 !== e && e.length ? "string" !== n.getTypeOf(e) ? function (e, t, r, n) {
  34009. var i = o,
  34010. s = n + r;
  34011. e ^= -1;
  34012. for (var a = n; a < s; a++) e = e >>> 8 ^ i[255 & (e ^ t[a])];
  34013. return -1 ^ e;
  34014. }(0 | t, e, e.length, 0) : function (e, t, r, n) {
  34015. var i = o,
  34016. s = n + r;
  34017. e ^= -1;
  34018. for (var a = n; a < s; a++) e = e >>> 8 ^ i[255 & (e ^ t.charCodeAt(a))];
  34019. return -1 ^ e;
  34020. }(0 | t, e, e.length, 0) : 0;
  34021. };
  34022. }, {
  34023. "./utils": 32
  34024. }],
  34025. 5: [function (e, t, r) {
  34026. "use strict";
  34027. r.base64 = !1, r.binary = !1, r.dir = !1, r.createFolders = !0, r.date = null, r.compression = null, r.compressionOptions = null, r.comment = null, r.unixPermissions = null, r.dosPermissions = null;
  34028. }, {}],
  34029. 6: [function (e, t, r) {
  34030. "use strict";
  34031. var n = null;
  34032. n = "undefined" != typeof Promise ? Promise : e("lie"), t.exports = {
  34033. Promise: n
  34034. };
  34035. }, {
  34036. lie: 37
  34037. }],
  34038. 7: [function (e, t, r) {
  34039. "use strict";
  34040. var n = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Uint32Array,
  34041. i = e("pako"),
  34042. s = e("./utils"),
  34043. a = e("./stream/GenericWorker"),
  34044. o = n ? "uint8array" : "array";
  34045. function h(e, t) {
  34046. a.call(this, "FlateWorker/" + e), this._pako = null, this._pakoAction = e, this._pakoOptions = t, this.meta = {};
  34047. }
  34048. r.magic = "\b\0", s.inherits(h, a), h.prototype.processChunk = function (e) {
  34049. this.meta = e.meta, null === this._pako && this._createPako(), this._pako.push(s.transformTo(o, e.data), !1);
  34050. }, h.prototype.flush = function () {
  34051. a.prototype.flush.call(this), null === this._pako && this._createPako(), this._pako.push([], !0);
  34052. }, h.prototype.cleanUp = function () {
  34053. a.prototype.cleanUp.call(this), this._pako = null;
  34054. }, h.prototype._createPako = function () {
  34055. this._pako = new i[this._pakoAction]({
  34056. raw: !0,
  34057. level: this._pakoOptions.level || -1
  34058. });
  34059. var t = this;
  34060. this._pako.onData = function (e) {
  34061. t.push({
  34062. data: e,
  34063. meta: t.meta
  34064. });
  34065. };
  34066. }, r.compressWorker = function (e) {
  34067. return new h("Deflate", e);
  34068. }, r.uncompressWorker = function () {
  34069. return new h("Inflate", {});
  34070. };
  34071. }, {
  34072. "./stream/GenericWorker": 28,
  34073. "./utils": 32,
  34074. pako: 38
  34075. }],
  34076. 8: [function (e, t, r) {
  34077. "use strict";
  34078. function A(e, t) {
  34079. var r,
  34080. n = "";
  34081. for (r = 0; r < t; r++) n += String.fromCharCode(255 & e), e >>>= 8;
  34082. return n;
  34083. }
  34084. function n(e, t, r, n, i, s) {
  34085. var a,
  34086. o,
  34087. h = e.file,
  34088. u = e.compression,
  34089. l = s !== O.utf8encode,
  34090. f = I.transformTo("string", s(h.name)),
  34091. c = I.transformTo("string", O.utf8encode(h.name)),
  34092. d = h.comment,
  34093. p = I.transformTo("string", s(d)),
  34094. m = I.transformTo("string", O.utf8encode(d)),
  34095. _ = c.length !== h.name.length,
  34096. g = m.length !== d.length,
  34097. b = "",
  34098. v = "",
  34099. y = "",
  34100. w = h.dir,
  34101. k = h.date,
  34102. x = {
  34103. crc32: 0,
  34104. compressedSize: 0,
  34105. uncompressedSize: 0
  34106. };
  34107. t && !r || (x.crc32 = e.crc32, x.compressedSize = e.compressedSize, x.uncompressedSize = e.uncompressedSize);
  34108. var S = 0;
  34109. t && (S |= 8), l || !_ && !g || (S |= 2048);
  34110. var z = 0,
  34111. C = 0;
  34112. w && (z |= 16), "UNIX" === i ? (C = 798, z |= function (e, t) {
  34113. var r = e;
  34114. return e || (r = t ? 16893 : 33204), (65535 & r) << 16;
  34115. }(h.unixPermissions, w)) : (C = 20, z |= function (e) {
  34116. return 63 & (e || 0);
  34117. }(h.dosPermissions)), a = k.getUTCHours(), a <<= 6, a |= k.getUTCMinutes(), a <<= 5, a |= k.getUTCSeconds() / 2, o = k.getUTCFullYear() - 1980, o <<= 4, o |= k.getUTCMonth() + 1, o <<= 5, o |= k.getUTCDate(), _ && (v = A(1, 1) + A(B(f), 4) + c, b += "up" + A(v.length, 2) + v), g && (y = A(1, 1) + A(B(p), 4) + m, b += "uc" + A(y.length, 2) + y);
  34118. var E = "";
  34119. return E += "\n\0", E += A(S, 2), E += u.magic, E += A(a, 2), E += A(o, 2), E += A(x.crc32, 4), E += A(x.compressedSize, 4), E += A(x.uncompressedSize, 4), E += A(f.length, 2), E += A(b.length, 2), {
  34120. fileRecord: R.LOCAL_FILE_HEADER + E + f + b,
  34121. dirRecord: R.CENTRAL_FILE_HEADER + A(C, 2) + E + A(p.length, 2) + "\0\0\0\0" + A(z, 4) + A(n, 4) + f + b + p
  34122. };
  34123. }
  34124. var I = e("../utils"),
  34125. i = e("../stream/GenericWorker"),
  34126. O = e("../utf8"),
  34127. B = e("../crc32"),
  34128. R = e("../signature");
  34129. function s(e, t, r, n) {
  34130. i.call(this, "ZipFileWorker"), this.bytesWritten = 0, this.zipComment = t, this.zipPlatform = r, this.encodeFileName = n, this.streamFiles = e, this.accumulate = !1, this.contentBuffer = [], this.dirRecords = [], this.currentSourceOffset = 0, this.entriesCount = 0, this.currentFile = null, this._sources = [];
  34131. }
  34132. I.inherits(s, i), s.prototype.push = function (e) {
  34133. var t = e.meta.percent || 0,
  34134. r = this.entriesCount,
  34135. n = this._sources.length;
  34136. this.accumulate ? this.contentBuffer.push(e) : (this.bytesWritten += e.data.length, i.prototype.push.call(this, {
  34137. data: e.data,
  34138. meta: {
  34139. currentFile: this.currentFile,
  34140. percent: r ? (t + 100 * (r - n - 1)) / r : 100
  34141. }
  34142. }));
  34143. }, s.prototype.openedSource = function (e) {
  34144. this.currentSourceOffset = this.bytesWritten, this.currentFile = e.file.name;
  34145. var t = this.streamFiles && !e.file.dir;
  34146. if (t) {
  34147. var r = n(e, t, !1, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  34148. this.push({
  34149. data: r.fileRecord,
  34150. meta: {
  34151. percent: 0
  34152. }
  34153. });
  34154. } else this.accumulate = !0;
  34155. }, s.prototype.closedSource = function (e) {
  34156. this.accumulate = !1;
  34157. var t = this.streamFiles && !e.file.dir,
  34158. r = n(e, t, !0, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  34159. if (this.dirRecords.push(r.dirRecord), t) this.push({
  34160. data: function (e) {
  34161. return R.DATA_DESCRIPTOR + A(e.crc32, 4) + A(e.compressedSize, 4) + A(e.uncompressedSize, 4);
  34162. }(e),
  34163. meta: {
  34164. percent: 100
  34165. }
  34166. });else for (this.push({
  34167. data: r.fileRecord,
  34168. meta: {
  34169. percent: 0
  34170. }
  34171. }); this.contentBuffer.length;) this.push(this.contentBuffer.shift());
  34172. this.currentFile = null;
  34173. }, s.prototype.flush = function () {
  34174. for (var e = this.bytesWritten, t = 0; t < this.dirRecords.length; t++) this.push({
  34175. data: this.dirRecords[t],
  34176. meta: {
  34177. percent: 100
  34178. }
  34179. });
  34180. var r = this.bytesWritten - e,
  34181. n = function (e, t, r, n, i) {
  34182. var s = I.transformTo("string", i(n));
  34183. return R.CENTRAL_DIRECTORY_END + "\0\0\0\0" + A(e, 2) + A(e, 2) + A(t, 4) + A(r, 4) + A(s.length, 2) + s;
  34184. }(this.dirRecords.length, r, e, this.zipComment, this.encodeFileName);
  34185. this.push({
  34186. data: n,
  34187. meta: {
  34188. percent: 100
  34189. }
  34190. });
  34191. }, s.prototype.prepareNextSource = function () {
  34192. this.previous = this._sources.shift(), this.openedSource(this.previous.streamInfo), this.isPaused ? this.previous.pause() : this.previous.resume();
  34193. }, s.prototype.registerPrevious = function (e) {
  34194. this._sources.push(e);
  34195. var t = this;
  34196. return e.on("data", function (e) {
  34197. t.processChunk(e);
  34198. }), e.on("end", function () {
  34199. t.closedSource(t.previous.streamInfo), t._sources.length ? t.prepareNextSource() : t.end();
  34200. }), e.on("error", function (e) {
  34201. t.error(e);
  34202. }), this;
  34203. }, s.prototype.resume = function () {
  34204. return !!i.prototype.resume.call(this) && (!this.previous && this._sources.length ? (this.prepareNextSource(), !0) : this.previous || this._sources.length || this.generatedError ? void 0 : (this.end(), !0));
  34205. }, s.prototype.error = function (e) {
  34206. var t = this._sources;
  34207. if (!i.prototype.error.call(this, e)) return !1;
  34208. for (var r = 0; r < t.length; r++) try {
  34209. t[r].error(e);
  34210. } catch (e) {}
  34211. return !0;
  34212. }, s.prototype.lock = function () {
  34213. i.prototype.lock.call(this);
  34214. for (var e = this._sources, t = 0; t < e.length; t++) e[t].lock();
  34215. }, t.exports = s;
  34216. }, {
  34217. "../crc32": 4,
  34218. "../signature": 23,
  34219. "../stream/GenericWorker": 28,
  34220. "../utf8": 31,
  34221. "../utils": 32
  34222. }],
  34223. 9: [function (e, t, r) {
  34224. "use strict";
  34225. var u = e("../compressions"),
  34226. n = e("./ZipFileWorker");
  34227. r.generateWorker = function (e, a, t) {
  34228. var o = new n(a.streamFiles, t, a.platform, a.encodeFileName),
  34229. h = 0;
  34230. try {
  34231. e.forEach(function (e, t) {
  34232. h++;
  34233. var r = function (e, t) {
  34234. var r = e || t,
  34235. n = u[r];
  34236. if (!n) throw new Error(r + " is not a valid compression method !");
  34237. return n;
  34238. }(t.options.compression, a.compression),
  34239. n = t.options.compressionOptions || a.compressionOptions || {},
  34240. i = t.dir,
  34241. s = t.date;
  34242. t._compressWorker(r, n).withStreamInfo("file", {
  34243. name: e,
  34244. dir: i,
  34245. date: s,
  34246. comment: t.comment || "",
  34247. unixPermissions: t.unixPermissions,
  34248. dosPermissions: t.dosPermissions
  34249. }).pipe(o);
  34250. }), o.entriesCount = h;
  34251. } catch (e) {
  34252. o.error(e);
  34253. }
  34254. return o;
  34255. };
  34256. }, {
  34257. "../compressions": 3,
  34258. "./ZipFileWorker": 8
  34259. }],
  34260. 10: [function (e, t, r) {
  34261. "use strict";
  34262. function n() {
  34263. if (!(this instanceof n)) return new n();
  34264. if (arguments.length) throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
  34265. this.files = Object.create(null), this.comment = null, this.root = "", this.clone = function () {
  34266. var e = new n();
  34267. for (var t in this) "function" != typeof this[t] && (e[t] = this[t]);
  34268. return e;
  34269. };
  34270. }
  34271. (n.prototype = e("./object")).loadAsync = e("./load"), n.support = e("./support"), n.defaults = e("./defaults"), n.version = "3.10.1", n.loadAsync = function (e, t) {
  34272. return new n().loadAsync(e, t);
  34273. }, n.external = e("./external"), t.exports = n;
  34274. }, {
  34275. "./defaults": 5,
  34276. "./external": 6,
  34277. "./load": 11,
  34278. "./object": 15,
  34279. "./support": 30
  34280. }],
  34281. 11: [function (e, t, r) {
  34282. "use strict";
  34283. var u = e("./utils"),
  34284. i = e("./external"),
  34285. n = e("./utf8"),
  34286. s = e("./zipEntries"),
  34287. a = e("./stream/Crc32Probe"),
  34288. l = e("./nodejsUtils");
  34289. function f(n) {
  34290. return new i.Promise(function (e, t) {
  34291. var r = n.decompressed.getContentWorker().pipe(new a());
  34292. r.on("error", function (e) {
  34293. t(e);
  34294. }).on("end", function () {
  34295. r.streamInfo.crc32 !== n.decompressed.crc32 ? t(new Error("Corrupted zip : CRC32 mismatch")) : e();
  34296. }).resume();
  34297. });
  34298. }
  34299. t.exports = function (e, o) {
  34300. var h = this;
  34301. return o = u.extend(o || {}, {
  34302. base64: !1,
  34303. checkCRC32: !1,
  34304. optimizedBinaryString: !1,
  34305. createFolders: !1,
  34306. decodeFileName: n.utf8decode
  34307. }), l.isNode && l.isStream(e) ? i.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")) : u.prepareContent("the loaded zip file", e, !0, o.optimizedBinaryString, o.base64).then(function (e) {
  34308. var t = new s(o);
  34309. return t.load(e), t;
  34310. }).then(function (e) {
  34311. var t = [i.Promise.resolve(e)],
  34312. r = e.files;
  34313. if (o.checkCRC32) for (var n = 0; n < r.length; n++) t.push(f(r[n]));
  34314. return i.Promise.all(t);
  34315. }).then(function (e) {
  34316. for (var t = e.shift(), r = t.files, n = 0; n < r.length; n++) {
  34317. var i = r[n],
  34318. s = i.fileNameStr,
  34319. a = u.resolve(i.fileNameStr);
  34320. h.file(a, i.decompressed, {
  34321. binary: !0,
  34322. optimizedBinaryString: !0,
  34323. date: i.date,
  34324. dir: i.dir,
  34325. comment: i.fileCommentStr.length ? i.fileCommentStr : null,
  34326. unixPermissions: i.unixPermissions,
  34327. dosPermissions: i.dosPermissions,
  34328. createFolders: o.createFolders
  34329. }), i.dir || (h.file(a).unsafeOriginalName = s);
  34330. }
  34331. return t.zipComment.length && (h.comment = t.zipComment), h;
  34332. });
  34333. };
  34334. }, {
  34335. "./external": 6,
  34336. "./nodejsUtils": 14,
  34337. "./stream/Crc32Probe": 25,
  34338. "./utf8": 31,
  34339. "./utils": 32,
  34340. "./zipEntries": 33
  34341. }],
  34342. 12: [function (e, t, r) {
  34343. "use strict";
  34344. var n = e("../utils"),
  34345. i = e("../stream/GenericWorker");
  34346. function s(e, t) {
  34347. i.call(this, "Nodejs stream input adapter for " + e), this._upstreamEnded = !1, this._bindStream(t);
  34348. }
  34349. n.inherits(s, i), s.prototype._bindStream = function (e) {
  34350. var t = this;
  34351. (this._stream = e).pause(), e.on("data", function (e) {
  34352. t.push({
  34353. data: e,
  34354. meta: {
  34355. percent: 0
  34356. }
  34357. });
  34358. }).on("error", function (e) {
  34359. t.isPaused ? this.generatedError = e : t.error(e);
  34360. }).on("end", function () {
  34361. t.isPaused ? t._upstreamEnded = !0 : t.end();
  34362. });
  34363. }, s.prototype.pause = function () {
  34364. return !!i.prototype.pause.call(this) && (this._stream.pause(), !0);
  34365. }, s.prototype.resume = function () {
  34366. return !!i.prototype.resume.call(this) && (this._upstreamEnded ? this.end() : this._stream.resume(), !0);
  34367. }, t.exports = s;
  34368. }, {
  34369. "../stream/GenericWorker": 28,
  34370. "../utils": 32
  34371. }],
  34372. 13: [function (e, t, r) {
  34373. "use strict";
  34374. var i = e("readable-stream").Readable;
  34375. function n(e, t, r) {
  34376. i.call(this, t), this._helper = e;
  34377. var n = this;
  34378. e.on("data", function (e, t) {
  34379. n.push(e) || n._helper.pause(), r && r(t);
  34380. }).on("error", function (e) {
  34381. n.emit("error", e);
  34382. }).on("end", function () {
  34383. n.push(null);
  34384. });
  34385. }
  34386. e("../utils").inherits(n, i), n.prototype._read = function () {
  34387. this._helper.resume();
  34388. }, t.exports = n;
  34389. }, {
  34390. "../utils": 32,
  34391. "readable-stream": 16
  34392. }],
  34393. 14: [function (e, t, r) {
  34394. "use strict";
  34395. t.exports = {
  34396. isNode: "undefined" != typeof Buffer,
  34397. newBufferFrom: function (e, t) {
  34398. if (Buffer.from && Buffer.from !== Uint8Array.from) return Buffer.from(e, t);
  34399. if ("number" == typeof e) throw new Error('The "data" argument must not be a number');
  34400. return new Buffer(e, t);
  34401. },
  34402. allocBuffer: function (e) {
  34403. if (Buffer.alloc) return Buffer.alloc(e);
  34404. var t = new Buffer(e);
  34405. return t.fill(0), t;
  34406. },
  34407. isBuffer: function (e) {
  34408. return Buffer.isBuffer(e);
  34409. },
  34410. isStream: function (e) {
  34411. return e && "function" == typeof e.on && "function" == typeof e.pause && "function" == typeof e.resume;
  34412. }
  34413. };
  34414. }, {}],
  34415. 15: [function (e, t, r) {
  34416. "use strict";
  34417. function s(e, t, r) {
  34418. var n,
  34419. i = u.getTypeOf(t),
  34420. s = u.extend(r || {}, f);
  34421. s.date = s.date || new Date(), null !== s.compression && (s.compression = s.compression.toUpperCase()), "string" == typeof s.unixPermissions && (s.unixPermissions = parseInt(s.unixPermissions, 8)), s.unixPermissions && 16384 & s.unixPermissions && (s.dir = !0), s.dosPermissions && 16 & s.dosPermissions && (s.dir = !0), s.dir && (e = g(e)), s.createFolders && (n = _(e)) && b.call(this, n, !0);
  34422. var a = "string" === i && !1 === s.binary && !1 === s.base64;
  34423. r && void 0 !== r.binary || (s.binary = !a), (t instanceof c && 0 === t.uncompressedSize || s.dir || !t || 0 === t.length) && (s.base64 = !1, s.binary = !0, t = "", s.compression = "STORE", i = "string");
  34424. var o = null;
  34425. o = t instanceof c || t instanceof l ? t : p.isNode && p.isStream(t) ? new m(e, t) : u.prepareContent(e, t, s.binary, s.optimizedBinaryString, s.base64);
  34426. var h = new d(e, o, s);
  34427. this.files[e] = h;
  34428. }
  34429. var i = e("./utf8"),
  34430. u = e("./utils"),
  34431. l = e("./stream/GenericWorker"),
  34432. a = e("./stream/StreamHelper"),
  34433. f = e("./defaults"),
  34434. c = e("./compressedObject"),
  34435. d = e("./zipObject"),
  34436. o = e("./generate"),
  34437. p = e("./nodejsUtils"),
  34438. m = e("./nodejs/NodejsStreamInputAdapter"),
  34439. _ = function (e) {
  34440. "/" === e.slice(-1) && (e = e.substring(0, e.length - 1));
  34441. var t = e.lastIndexOf("/");
  34442. return 0 < t ? e.substring(0, t) : "";
  34443. },
  34444. g = function (e) {
  34445. return "/" !== e.slice(-1) && (e += "/"), e;
  34446. },
  34447. b = function (e, t) {
  34448. return t = void 0 !== t ? t : f.createFolders, e = g(e), this.files[e] || s.call(this, e, null, {
  34449. dir: !0,
  34450. createFolders: t
  34451. }), this.files[e];
  34452. };
  34453. function h(e) {
  34454. return "[object RegExp]" === Object.prototype.toString.call(e);
  34455. }
  34456. var n = {
  34457. load: function () {
  34458. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  34459. },
  34460. forEach: function (e) {
  34461. var t, r, n;
  34462. for (t in this.files) n = this.files[t], (r = t.slice(this.root.length, t.length)) && t.slice(0, this.root.length) === this.root && e(r, n);
  34463. },
  34464. filter: function (r) {
  34465. var n = [];
  34466. return this.forEach(function (e, t) {
  34467. r(e, t) && n.push(t);
  34468. }), n;
  34469. },
  34470. file: function (e, t, r) {
  34471. if (1 !== arguments.length) return e = this.root + e, s.call(this, e, t, r), this;
  34472. if (h(e)) {
  34473. var n = e;
  34474. return this.filter(function (e, t) {
  34475. return !t.dir && n.test(e);
  34476. });
  34477. }
  34478. var i = this.files[this.root + e];
  34479. return i && !i.dir ? i : null;
  34480. },
  34481. folder: function (r) {
  34482. if (!r) return this;
  34483. if (h(r)) return this.filter(function (e, t) {
  34484. return t.dir && r.test(e);
  34485. });
  34486. var e = this.root + r,
  34487. t = b.call(this, e),
  34488. n = this.clone();
  34489. return n.root = t.name, n;
  34490. },
  34491. remove: function (r) {
  34492. r = this.root + r;
  34493. var e = this.files[r];
  34494. if (e || ("/" !== r.slice(-1) && (r += "/"), e = this.files[r]), e && !e.dir) delete this.files[r];else for (var t = this.filter(function (e, t) {
  34495. return t.name.slice(0, r.length) === r;
  34496. }), n = 0; n < t.length; n++) delete this.files[t[n].name];
  34497. return this;
  34498. },
  34499. generate: function () {
  34500. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  34501. },
  34502. generateInternalStream: function (e) {
  34503. var t,
  34504. r = {};
  34505. try {
  34506. if ((r = u.extend(e || {}, {
  34507. streamFiles: !1,
  34508. compression: "STORE",
  34509. compressionOptions: null,
  34510. type: "",
  34511. platform: "DOS",
  34512. comment: null,
  34513. mimeType: "application/zip",
  34514. encodeFileName: i.utf8encode
  34515. })).type = r.type.toLowerCase(), r.compression = r.compression.toUpperCase(), "binarystring" === r.type && (r.type = "string"), !r.type) throw new Error("No output type specified.");
  34516. u.checkSupport(r.type), "darwin" !== r.platform && "freebsd" !== r.platform && "linux" !== r.platform && "sunos" !== r.platform || (r.platform = "UNIX"), "win32" === r.platform && (r.platform = "DOS");
  34517. var n = r.comment || this.comment || "";
  34518. t = o.generateWorker(this, r, n);
  34519. } catch (e) {
  34520. (t = new l("error")).error(e);
  34521. }
  34522. return new a(t, r.type || "string", r.mimeType);
  34523. },
  34524. generateAsync: function (e, t) {
  34525. return this.generateInternalStream(e).accumulate(t);
  34526. },
  34527. generateNodeStream: function (e, t) {
  34528. return (e = e || {}).type || (e.type = "nodebuffer"), this.generateInternalStream(e).toNodejsStream(t);
  34529. }
  34530. };
  34531. t.exports = n;
  34532. }, {
  34533. "./compressedObject": 2,
  34534. "./defaults": 5,
  34535. "./generate": 9,
  34536. "./nodejs/NodejsStreamInputAdapter": 12,
  34537. "./nodejsUtils": 14,
  34538. "./stream/GenericWorker": 28,
  34539. "./stream/StreamHelper": 29,
  34540. "./utf8": 31,
  34541. "./utils": 32,
  34542. "./zipObject": 35
  34543. }],
  34544. 16: [function (e, t, r) {
  34545. "use strict";
  34546. t.exports = e("stream");
  34547. }, {
  34548. stream: void 0
  34549. }],
  34550. 17: [function (e, t, r) {
  34551. "use strict";
  34552. var n = e("./DataReader");
  34553. function i(e) {
  34554. n.call(this, e);
  34555. for (var t = 0; t < this.data.length; t++) e[t] = 255 & e[t];
  34556. }
  34557. e("../utils").inherits(i, n), i.prototype.byteAt = function (e) {
  34558. return this.data[this.zero + e];
  34559. }, i.prototype.lastIndexOfSignature = function (e) {
  34560. for (var t = e.charCodeAt(0), r = e.charCodeAt(1), n = e.charCodeAt(2), i = e.charCodeAt(3), s = this.length - 4; 0 <= s; --s) if (this.data[s] === t && this.data[s + 1] === r && this.data[s + 2] === n && this.data[s + 3] === i) return s - this.zero;
  34561. return -1;
  34562. }, i.prototype.readAndCheckSignature = function (e) {
  34563. var t = e.charCodeAt(0),
  34564. r = e.charCodeAt(1),
  34565. n = e.charCodeAt(2),
  34566. i = e.charCodeAt(3),
  34567. s = this.readData(4);
  34568. return t === s[0] && r === s[1] && n === s[2] && i === s[3];
  34569. }, i.prototype.readData = function (e) {
  34570. if (this.checkOffset(e), 0 === e) return [];
  34571. var t = this.data.slice(this.zero + this.index, this.zero + this.index + e);
  34572. return this.index += e, t;
  34573. }, t.exports = i;
  34574. }, {
  34575. "../utils": 32,
  34576. "./DataReader": 18
  34577. }],
  34578. 18: [function (e, t, r) {
  34579. "use strict";
  34580. var n = e("../utils");
  34581. function i(e) {
  34582. this.data = e, this.length = e.length, this.index = 0, this.zero = 0;
  34583. }
  34584. i.prototype = {
  34585. checkOffset: function (e) {
  34586. this.checkIndex(this.index + e);
  34587. },
  34588. checkIndex: function (e) {
  34589. if (this.length < this.zero + e || e < 0) throw new Error("End of data reached (data length = " + this.length + ", asked index = " + e + "). Corrupted zip ?");
  34590. },
  34591. setIndex: function (e) {
  34592. this.checkIndex(e), this.index = e;
  34593. },
  34594. skip: function (e) {
  34595. this.setIndex(this.index + e);
  34596. },
  34597. byteAt: function () {},
  34598. readInt: function (e) {
  34599. var t,
  34600. r = 0;
  34601. for (this.checkOffset(e), t = this.index + e - 1; t >= this.index; t--) r = (r << 8) + this.byteAt(t);
  34602. return this.index += e, r;
  34603. },
  34604. readString: function (e) {
  34605. return n.transformTo("string", this.readData(e));
  34606. },
  34607. readData: function () {},
  34608. lastIndexOfSignature: function () {},
  34609. readAndCheckSignature: function () {},
  34610. readDate: function () {
  34611. var e = this.readInt(4);
  34612. return new Date(Date.UTC(1980 + (e >> 25 & 127), (e >> 21 & 15) - 1, e >> 16 & 31, e >> 11 & 31, e >> 5 & 63, (31 & e) << 1));
  34613. }
  34614. }, t.exports = i;
  34615. }, {
  34616. "../utils": 32
  34617. }],
  34618. 19: [function (e, t, r) {
  34619. "use strict";
  34620. var n = e("./Uint8ArrayReader");
  34621. function i(e) {
  34622. n.call(this, e);
  34623. }
  34624. e("../utils").inherits(i, n), i.prototype.readData = function (e) {
  34625. this.checkOffset(e);
  34626. var t = this.data.slice(this.zero + this.index, this.zero + this.index + e);
  34627. return this.index += e, t;
  34628. }, t.exports = i;
  34629. }, {
  34630. "../utils": 32,
  34631. "./Uint8ArrayReader": 21
  34632. }],
  34633. 20: [function (e, t, r) {
  34634. "use strict";
  34635. var n = e("./DataReader");
  34636. function i(e) {
  34637. n.call(this, e);
  34638. }
  34639. e("../utils").inherits(i, n), i.prototype.byteAt = function (e) {
  34640. return this.data.charCodeAt(this.zero + e);
  34641. }, i.prototype.lastIndexOfSignature = function (e) {
  34642. return this.data.lastIndexOf(e) - this.zero;
  34643. }, i.prototype.readAndCheckSignature = function (e) {
  34644. return e === this.readData(4);
  34645. }, i.prototype.readData = function (e) {
  34646. this.checkOffset(e);
  34647. var t = this.data.slice(this.zero + this.index, this.zero + this.index + e);
  34648. return this.index += e, t;
  34649. }, t.exports = i;
  34650. }, {
  34651. "../utils": 32,
  34652. "./DataReader": 18
  34653. }],
  34654. 21: [function (e, t, r) {
  34655. "use strict";
  34656. var n = e("./ArrayReader");
  34657. function i(e) {
  34658. n.call(this, e);
  34659. }
  34660. e("../utils").inherits(i, n), i.prototype.readData = function (e) {
  34661. if (this.checkOffset(e), 0 === e) return new Uint8Array(0);
  34662. var t = this.data.subarray(this.zero + this.index, this.zero + this.index + e);
  34663. return this.index += e, t;
  34664. }, t.exports = i;
  34665. }, {
  34666. "../utils": 32,
  34667. "./ArrayReader": 17
  34668. }],
  34669. 22: [function (e, t, r) {
  34670. "use strict";
  34671. var n = e("../utils"),
  34672. i = e("../support"),
  34673. s = e("./ArrayReader"),
  34674. a = e("./StringReader"),
  34675. o = e("./NodeBufferReader"),
  34676. h = e("./Uint8ArrayReader");
  34677. t.exports = function (e) {
  34678. var t = n.getTypeOf(e);
  34679. return n.checkSupport(t), "string" !== t || i.uint8array ? "nodebuffer" === t ? new o(e) : i.uint8array ? new h(n.transformTo("uint8array", e)) : new s(n.transformTo("array", e)) : new a(e);
  34680. };
  34681. }, {
  34682. "../support": 30,
  34683. "../utils": 32,
  34684. "./ArrayReader": 17,
  34685. "./NodeBufferReader": 19,
  34686. "./StringReader": 20,
  34687. "./Uint8ArrayReader": 21
  34688. }],
  34689. 23: [function (e, t, r) {
  34690. "use strict";
  34691. r.LOCAL_FILE_HEADER = "PK", r.CENTRAL_FILE_HEADER = "PK", r.CENTRAL_DIRECTORY_END = "PK", r.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK", r.ZIP64_CENTRAL_DIRECTORY_END = "PK", r.DATA_DESCRIPTOR = "PK\b";
  34692. }, {}],
  34693. 24: [function (e, t, r) {
  34694. "use strict";
  34695. var n = e("./GenericWorker"),
  34696. i = e("../utils");
  34697. function s(e) {
  34698. n.call(this, "ConvertWorker to " + e), this.destType = e;
  34699. }
  34700. i.inherits(s, n), s.prototype.processChunk = function (e) {
  34701. this.push({
  34702. data: i.transformTo(this.destType, e.data),
  34703. meta: e.meta
  34704. });
  34705. }, t.exports = s;
  34706. }, {
  34707. "../utils": 32,
  34708. "./GenericWorker": 28
  34709. }],
  34710. 25: [function (e, t, r) {
  34711. "use strict";
  34712. var n = e("./GenericWorker"),
  34713. i = e("../crc32");
  34714. function s() {
  34715. n.call(this, "Crc32Probe"), this.withStreamInfo("crc32", 0);
  34716. }
  34717. e("../utils").inherits(s, n), s.prototype.processChunk = function (e) {
  34718. this.streamInfo.crc32 = i(e.data, this.streamInfo.crc32 || 0), this.push(e);
  34719. }, t.exports = s;
  34720. }, {
  34721. "../crc32": 4,
  34722. "../utils": 32,
  34723. "./GenericWorker": 28
  34724. }],
  34725. 26: [function (e, t, r) {
  34726. "use strict";
  34727. var n = e("../utils"),
  34728. i = e("./GenericWorker");
  34729. function s(e) {
  34730. i.call(this, "DataLengthProbe for " + e), this.propName = e, this.withStreamInfo(e, 0);
  34731. }
  34732. n.inherits(s, i), s.prototype.processChunk = function (e) {
  34733. if (e) {
  34734. var t = this.streamInfo[this.propName] || 0;
  34735. this.streamInfo[this.propName] = t + e.data.length;
  34736. }
  34737. i.prototype.processChunk.call(this, e);
  34738. }, t.exports = s;
  34739. }, {
  34740. "../utils": 32,
  34741. "./GenericWorker": 28
  34742. }],
  34743. 27: [function (e, t, r) {
  34744. "use strict";
  34745. var n = e("../utils"),
  34746. i = e("./GenericWorker");
  34747. function s(e) {
  34748. i.call(this, "DataWorker");
  34749. var t = this;
  34750. this.dataIsReady = !1, this.index = 0, this.max = 0, this.data = null, this.type = "", this._tickScheduled = !1, e.then(function (e) {
  34751. t.dataIsReady = !0, t.data = e, t.max = e && e.length || 0, t.type = n.getTypeOf(e), t.isPaused || t._tickAndRepeat();
  34752. }, function (e) {
  34753. t.error(e);
  34754. });
  34755. }
  34756. n.inherits(s, i), s.prototype.cleanUp = function () {
  34757. i.prototype.cleanUp.call(this), this.data = null;
  34758. }, s.prototype.resume = function () {
  34759. return !!i.prototype.resume.call(this) && (!this._tickScheduled && this.dataIsReady && (this._tickScheduled = !0, n.delay(this._tickAndRepeat, [], this)), !0);
  34760. }, s.prototype._tickAndRepeat = function () {
  34761. this._tickScheduled = !1, this.isPaused || this.isFinished || (this._tick(), this.isFinished || (n.delay(this._tickAndRepeat, [], this), this._tickScheduled = !0));
  34762. }, s.prototype._tick = function () {
  34763. if (this.isPaused || this.isFinished) return !1;
  34764. var e = null,
  34765. t = Math.min(this.max, this.index + 16384);
  34766. if (this.index >= this.max) return this.end();
  34767. switch (this.type) {
  34768. case "string":
  34769. e = this.data.substring(this.index, t);
  34770. break;
  34771. case "uint8array":
  34772. e = this.data.subarray(this.index, t);
  34773. break;
  34774. case "array":
  34775. case "nodebuffer":
  34776. e = this.data.slice(this.index, t);
  34777. }
  34778. return this.index = t, this.push({
  34779. data: e,
  34780. meta: {
  34781. percent: this.max ? this.index / this.max * 100 : 0
  34782. }
  34783. });
  34784. }, t.exports = s;
  34785. }, {
  34786. "../utils": 32,
  34787. "./GenericWorker": 28
  34788. }],
  34789. 28: [function (e, t, r) {
  34790. "use strict";
  34791. function n(e) {
  34792. this.name = e || "default", this.streamInfo = {}, this.generatedError = null, this.extraStreamInfo = {}, this.isPaused = !0, this.isFinished = !1, this.isLocked = !1, this._listeners = {
  34793. data: [],
  34794. end: [],
  34795. error: []
  34796. }, this.previous = null;
  34797. }
  34798. n.prototype = {
  34799. push: function (e) {
  34800. this.emit("data", e);
  34801. },
  34802. end: function () {
  34803. if (this.isFinished) return !1;
  34804. this.flush();
  34805. try {
  34806. this.emit("end"), this.cleanUp(), this.isFinished = !0;
  34807. } catch (e) {
  34808. this.emit("error", e);
  34809. }
  34810. return !0;
  34811. },
  34812. error: function (e) {
  34813. return !this.isFinished && (this.isPaused ? this.generatedError = e : (this.isFinished = !0, this.emit("error", e), this.previous && this.previous.error(e), this.cleanUp()), !0);
  34814. },
  34815. on: function (e, t) {
  34816. return this._listeners[e].push(t), this;
  34817. },
  34818. cleanUp: function () {
  34819. this.streamInfo = this.generatedError = this.extraStreamInfo = null, this._listeners = [];
  34820. },
  34821. emit: function (e, t) {
  34822. if (this._listeners[e]) for (var r = 0; r < this._listeners[e].length; r++) this._listeners[e][r].call(this, t);
  34823. },
  34824. pipe: function (e) {
  34825. return e.registerPrevious(this);
  34826. },
  34827. registerPrevious: function (e) {
  34828. if (this.isLocked) throw new Error("The stream '" + this + "' has already been used.");
  34829. this.streamInfo = e.streamInfo, this.mergeStreamInfo(), this.previous = e;
  34830. var t = this;
  34831. return e.on("data", function (e) {
  34832. t.processChunk(e);
  34833. }), e.on("end", function () {
  34834. t.end();
  34835. }), e.on("error", function (e) {
  34836. t.error(e);
  34837. }), this;
  34838. },
  34839. pause: function () {
  34840. return !this.isPaused && !this.isFinished && (this.isPaused = !0, this.previous && this.previous.pause(), !0);
  34841. },
  34842. resume: function () {
  34843. if (!this.isPaused || this.isFinished) return !1;
  34844. var e = this.isPaused = !1;
  34845. return this.generatedError && (this.error(this.generatedError), e = !0), this.previous && this.previous.resume(), !e;
  34846. },
  34847. flush: function () {},
  34848. processChunk: function (e) {
  34849. this.push(e);
  34850. },
  34851. withStreamInfo: function (e, t) {
  34852. return this.extraStreamInfo[e] = t, this.mergeStreamInfo(), this;
  34853. },
  34854. mergeStreamInfo: function () {
  34855. for (var e in this.extraStreamInfo) Object.prototype.hasOwnProperty.call(this.extraStreamInfo, e) && (this.streamInfo[e] = this.extraStreamInfo[e]);
  34856. },
  34857. lock: function () {
  34858. if (this.isLocked) throw new Error("The stream '" + this + "' has already been used.");
  34859. this.isLocked = !0, this.previous && this.previous.lock();
  34860. },
  34861. toString: function () {
  34862. var e = "Worker " + this.name;
  34863. return this.previous ? this.previous + " -> " + e : e;
  34864. }
  34865. }, t.exports = n;
  34866. }, {}],
  34867. 29: [function (e, t, r) {
  34868. "use strict";
  34869. var h = e("../utils"),
  34870. i = e("./ConvertWorker"),
  34871. s = e("./GenericWorker"),
  34872. u = e("../base64"),
  34873. n = e("../support"),
  34874. a = e("../external"),
  34875. o = null;
  34876. if (n.nodestream) try {
  34877. o = e("../nodejs/NodejsStreamOutputAdapter");
  34878. } catch (e) {}
  34879. function l(e, o) {
  34880. return new a.Promise(function (t, r) {
  34881. var n = [],
  34882. i = e._internalType,
  34883. s = e._outputType,
  34884. a = e._mimeType;
  34885. e.on("data", function (e, t) {
  34886. n.push(e), o && o(t);
  34887. }).on("error", function (e) {
  34888. n = [], r(e);
  34889. }).on("end", function () {
  34890. try {
  34891. var e = function (e, t, r) {
  34892. switch (e) {
  34893. case "blob":
  34894. return h.newBlob(h.transformTo("arraybuffer", t), r);
  34895. case "base64":
  34896. return u.encode(t);
  34897. default:
  34898. return h.transformTo(e, t);
  34899. }
  34900. }(s, function (e, t) {
  34901. var r,
  34902. n = 0,
  34903. i = null,
  34904. s = 0;
  34905. for (r = 0; r < t.length; r++) s += t[r].length;
  34906. switch (e) {
  34907. case "string":
  34908. return t.join("");
  34909. case "array":
  34910. return Array.prototype.concat.apply([], t);
  34911. case "uint8array":
  34912. for (i = new Uint8Array(s), r = 0; r < t.length; r++) i.set(t[r], n), n += t[r].length;
  34913. return i;
  34914. case "nodebuffer":
  34915. return Buffer.concat(t);
  34916. default:
  34917. throw new Error("concat : unsupported type '" + e + "'");
  34918. }
  34919. }(i, n), a);
  34920. t(e);
  34921. } catch (e) {
  34922. r(e);
  34923. }
  34924. n = [];
  34925. }).resume();
  34926. });
  34927. }
  34928. function f(e, t, r) {
  34929. var n = t;
  34930. switch (t) {
  34931. case "blob":
  34932. case "arraybuffer":
  34933. n = "uint8array";
  34934. break;
  34935. case "base64":
  34936. n = "string";
  34937. }
  34938. try {
  34939. this._internalType = n, this._outputType = t, this._mimeType = r, h.checkSupport(n), this._worker = e.pipe(new i(n)), e.lock();
  34940. } catch (e) {
  34941. this._worker = new s("error"), this._worker.error(e);
  34942. }
  34943. }
  34944. f.prototype = {
  34945. accumulate: function (e) {
  34946. return l(this, e);
  34947. },
  34948. on: function (e, t) {
  34949. var r = this;
  34950. return "data" === e ? this._worker.on(e, function (e) {
  34951. t.call(r, e.data, e.meta);
  34952. }) : this._worker.on(e, function () {
  34953. h.delay(t, arguments, r);
  34954. }), this;
  34955. },
  34956. resume: function () {
  34957. return h.delay(this._worker.resume, [], this._worker), this;
  34958. },
  34959. pause: function () {
  34960. return this._worker.pause(), this;
  34961. },
  34962. toNodejsStream: function (e) {
  34963. if (h.checkSupport("nodestream"), "nodebuffer" !== this._outputType) throw new Error(this._outputType + " is not supported by this method");
  34964. return new o(this, {
  34965. objectMode: "nodebuffer" !== this._outputType
  34966. }, e);
  34967. }
  34968. }, t.exports = f;
  34969. }, {
  34970. "../base64": 1,
  34971. "../external": 6,
  34972. "../nodejs/NodejsStreamOutputAdapter": 13,
  34973. "../support": 30,
  34974. "../utils": 32,
  34975. "./ConvertWorker": 24,
  34976. "./GenericWorker": 28
  34977. }],
  34978. 30: [function (e, t, r) {
  34979. "use strict";
  34980. if (r.base64 = !0, r.array = !0, r.string = !0, r.arraybuffer = "undefined" != typeof ArrayBuffer && "undefined" != typeof Uint8Array, r.nodebuffer = "undefined" != typeof Buffer, r.uint8array = "undefined" != typeof Uint8Array, "undefined" == typeof ArrayBuffer) r.blob = !1;else {
  34981. var n = new ArrayBuffer(0);
  34982. try {
  34983. r.blob = 0 === new Blob([n], {
  34984. type: "application/zip"
  34985. }).size;
  34986. } catch (e) {
  34987. try {
  34988. var i = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)();
  34989. i.append(n), r.blob = 0 === i.getBlob("application/zip").size;
  34990. } catch (e) {
  34991. r.blob = !1;
  34992. }
  34993. }
  34994. }
  34995. try {
  34996. r.nodestream = !!e("readable-stream").Readable;
  34997. } catch (e) {
  34998. r.nodestream = !1;
  34999. }
  35000. }, {
  35001. "readable-stream": 16
  35002. }],
  35003. 31: [function (e, t, s) {
  35004. "use strict";
  35005. for (var o = e("./utils"), h = e("./support"), r = e("./nodejsUtils"), n = e("./stream/GenericWorker"), u = new Array(256), i = 0; i < 256; i++) u[i] = 252 <= i ? 6 : 248 <= i ? 5 : 240 <= i ? 4 : 224 <= i ? 3 : 192 <= i ? 2 : 1;
  35006. u[254] = u[254] = 1;
  35007. function a() {
  35008. n.call(this, "utf-8 decode"), this.leftOver = null;
  35009. }
  35010. function l() {
  35011. n.call(this, "utf-8 encode");
  35012. }
  35013. s.utf8encode = function (e) {
  35014. return h.nodebuffer ? r.newBufferFrom(e, "utf-8") : function (e) {
  35015. var t,
  35016. r,
  35017. n,
  35018. i,
  35019. s,
  35020. a = e.length,
  35021. o = 0;
  35022. for (i = 0; i < a; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), o += r < 128 ? 1 : r < 2048 ? 2 : r < 65536 ? 3 : 4;
  35023. for (t = h.uint8array ? new Uint8Array(o) : new Array(o), i = s = 0; s < o; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), r < 128 ? t[s++] = r : (r < 2048 ? t[s++] = 192 | r >>> 6 : (r < 65536 ? t[s++] = 224 | r >>> 12 : (t[s++] = 240 | r >>> 18, t[s++] = 128 | r >>> 12 & 63), t[s++] = 128 | r >>> 6 & 63), t[s++] = 128 | 63 & r);
  35024. return t;
  35025. }(e);
  35026. }, s.utf8decode = function (e) {
  35027. return h.nodebuffer ? o.transformTo("nodebuffer", e).toString("utf-8") : function (e) {
  35028. var t,
  35029. r,
  35030. n,
  35031. i,
  35032. s = e.length,
  35033. a = new Array(2 * s);
  35034. for (t = r = 0; t < s;) if ((n = e[t++]) < 128) a[r++] = n;else if (4 < (i = u[n])) a[r++] = 65533, t += i - 1;else {
  35035. for (n &= 2 === i ? 31 : 3 === i ? 15 : 7; 1 < i && t < s;) n = n << 6 | 63 & e[t++], i--;
  35036. 1 < i ? a[r++] = 65533 : n < 65536 ? a[r++] = n : (n -= 65536, a[r++] = 55296 | n >> 10 & 1023, a[r++] = 56320 | 1023 & n);
  35037. }
  35038. return a.length !== r && (a.subarray ? a = a.subarray(0, r) : a.length = r), o.applyFromCharCode(a);
  35039. }(e = o.transformTo(h.uint8array ? "uint8array" : "array", e));
  35040. }, o.inherits(a, n), a.prototype.processChunk = function (e) {
  35041. var t = o.transformTo(h.uint8array ? "uint8array" : "array", e.data);
  35042. if (this.leftOver && this.leftOver.length) {
  35043. if (h.uint8array) {
  35044. var r = t;
  35045. (t = new Uint8Array(r.length + this.leftOver.length)).set(this.leftOver, 0), t.set(r, this.leftOver.length);
  35046. } else t = this.leftOver.concat(t);
  35047. this.leftOver = null;
  35048. }
  35049. var n = function (e, t) {
  35050. var r;
  35051. for ((t = t || e.length) > e.length && (t = e.length), r = t - 1; 0 <= r && 128 == (192 & e[r]);) r--;
  35052. return r < 0 ? t : 0 === r ? t : r + u[e[r]] > t ? r : t;
  35053. }(t),
  35054. i = t;
  35055. n !== t.length && (h.uint8array ? (i = t.subarray(0, n), this.leftOver = t.subarray(n, t.length)) : (i = t.slice(0, n), this.leftOver = t.slice(n, t.length))), this.push({
  35056. data: s.utf8decode(i),
  35057. meta: e.meta
  35058. });
  35059. }, a.prototype.flush = function () {
  35060. this.leftOver && this.leftOver.length && (this.push({
  35061. data: s.utf8decode(this.leftOver),
  35062. meta: {}
  35063. }), this.leftOver = null);
  35064. }, s.Utf8DecodeWorker = a, o.inherits(l, n), l.prototype.processChunk = function (e) {
  35065. this.push({
  35066. data: s.utf8encode(e.data),
  35067. meta: e.meta
  35068. });
  35069. }, s.Utf8EncodeWorker = l;
  35070. }, {
  35071. "./nodejsUtils": 14,
  35072. "./stream/GenericWorker": 28,
  35073. "./support": 30,
  35074. "./utils": 32
  35075. }],
  35076. 32: [function (e, t, a) {
  35077. "use strict";
  35078. var o = e("./support"),
  35079. h = e("./base64"),
  35080. r = e("./nodejsUtils"),
  35081. u = e("./external");
  35082. function n(e) {
  35083. return e;
  35084. }
  35085. function l(e, t) {
  35086. for (var r = 0; r < e.length; ++r) t[r] = 255 & e.charCodeAt(r);
  35087. return t;
  35088. }
  35089. e("setimmediate"), a.newBlob = function (t, r) {
  35090. a.checkSupport("blob");
  35091. try {
  35092. return new Blob([t], {
  35093. type: r
  35094. });
  35095. } catch (e) {
  35096. try {
  35097. var n = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)();
  35098. return n.append(t), n.getBlob(r);
  35099. } catch (e) {
  35100. throw new Error("Bug : can't construct the Blob.");
  35101. }
  35102. }
  35103. };
  35104. var i = {
  35105. stringifyByChunk: function (e, t, r) {
  35106. var n = [],
  35107. i = 0,
  35108. s = e.length;
  35109. if (s <= r) return String.fromCharCode.apply(null, e);
  35110. for (; i < s;) "array" === t || "nodebuffer" === t ? n.push(String.fromCharCode.apply(null, e.slice(i, Math.min(i + r, s)))) : n.push(String.fromCharCode.apply(null, e.subarray(i, Math.min(i + r, s)))), i += r;
  35111. return n.join("");
  35112. },
  35113. stringifyByChar: function (e) {
  35114. for (var t = "", r = 0; r < e.length; r++) t += String.fromCharCode(e[r]);
  35115. return t;
  35116. },
  35117. applyCanBeUsed: {
  35118. uint8array: function () {
  35119. try {
  35120. return o.uint8array && 1 === String.fromCharCode.apply(null, new Uint8Array(1)).length;
  35121. } catch (e) {
  35122. return !1;
  35123. }
  35124. }(),
  35125. nodebuffer: function () {
  35126. try {
  35127. return o.nodebuffer && 1 === String.fromCharCode.apply(null, r.allocBuffer(1)).length;
  35128. } catch (e) {
  35129. return !1;
  35130. }
  35131. }()
  35132. }
  35133. };
  35134. function s(e) {
  35135. var t = 65536,
  35136. r = a.getTypeOf(e),
  35137. n = !0;
  35138. if ("uint8array" === r ? n = i.applyCanBeUsed.uint8array : "nodebuffer" === r && (n = i.applyCanBeUsed.nodebuffer), n) for (; 1 < t;) try {
  35139. return i.stringifyByChunk(e, r, t);
  35140. } catch (e) {
  35141. t = Math.floor(t / 2);
  35142. }
  35143. return i.stringifyByChar(e);
  35144. }
  35145. function f(e, t) {
  35146. for (var r = 0; r < e.length; r++) t[r] = e[r];
  35147. return t;
  35148. }
  35149. a.applyFromCharCode = s;
  35150. var c = {};
  35151. c.string = {
  35152. string: n,
  35153. array: function (e) {
  35154. return l(e, new Array(e.length));
  35155. },
  35156. arraybuffer: function (e) {
  35157. return c.string.uint8array(e).buffer;
  35158. },
  35159. uint8array: function (e) {
  35160. return l(e, new Uint8Array(e.length));
  35161. },
  35162. nodebuffer: function (e) {
  35163. return l(e, r.allocBuffer(e.length));
  35164. }
  35165. }, c.array = {
  35166. string: s,
  35167. array: n,
  35168. arraybuffer: function (e) {
  35169. return new Uint8Array(e).buffer;
  35170. },
  35171. uint8array: function (e) {
  35172. return new Uint8Array(e);
  35173. },
  35174. nodebuffer: function (e) {
  35175. return r.newBufferFrom(e);
  35176. }
  35177. }, c.arraybuffer = {
  35178. string: function (e) {
  35179. return s(new Uint8Array(e));
  35180. },
  35181. array: function (e) {
  35182. return f(new Uint8Array(e), new Array(e.byteLength));
  35183. },
  35184. arraybuffer: n,
  35185. uint8array: function (e) {
  35186. return new Uint8Array(e);
  35187. },
  35188. nodebuffer: function (e) {
  35189. return r.newBufferFrom(new Uint8Array(e));
  35190. }
  35191. }, c.uint8array = {
  35192. string: s,
  35193. array: function (e) {
  35194. return f(e, new Array(e.length));
  35195. },
  35196. arraybuffer: function (e) {
  35197. return e.buffer;
  35198. },
  35199. uint8array: n,
  35200. nodebuffer: function (e) {
  35201. return r.newBufferFrom(e);
  35202. }
  35203. }, c.nodebuffer = {
  35204. string: s,
  35205. array: function (e) {
  35206. return f(e, new Array(e.length));
  35207. },
  35208. arraybuffer: function (e) {
  35209. return c.nodebuffer.uint8array(e).buffer;
  35210. },
  35211. uint8array: function (e) {
  35212. return f(e, new Uint8Array(e.length));
  35213. },
  35214. nodebuffer: n
  35215. }, a.transformTo = function (e, t) {
  35216. if (t = t || "", !e) return t;
  35217. a.checkSupport(e);
  35218. var r = a.getTypeOf(t);
  35219. return c[r][e](t);
  35220. }, a.resolve = function (e) {
  35221. for (var t = e.split("/"), r = [], n = 0; n < t.length; n++) {
  35222. var i = t[n];
  35223. "." === i || "" === i && 0 !== n && n !== t.length - 1 || (".." === i ? r.pop() : r.push(i));
  35224. }
  35225. return r.join("/");
  35226. }, a.getTypeOf = function (e) {
  35227. return "string" == typeof e ? "string" : "[object Array]" === Object.prototype.toString.call(e) ? "array" : o.nodebuffer && r.isBuffer(e) ? "nodebuffer" : o.uint8array && e instanceof Uint8Array ? "uint8array" : o.arraybuffer && e instanceof ArrayBuffer ? "arraybuffer" : void 0;
  35228. }, a.checkSupport = function (e) {
  35229. if (!o[e.toLowerCase()]) throw new Error(e + " is not supported by this platform");
  35230. }, a.MAX_VALUE_16BITS = 65535, a.MAX_VALUE_32BITS = -1, a.pretty = function (e) {
  35231. var t,
  35232. r,
  35233. n = "";
  35234. for (r = 0; r < (e || "").length; r++) n += "\\x" + ((t = e.charCodeAt(r)) < 16 ? "0" : "") + t.toString(16).toUpperCase();
  35235. return n;
  35236. }, a.delay = function (e, t, r) {
  35237. setImmediate(function () {
  35238. e.apply(r || null, t || []);
  35239. });
  35240. }, a.inherits = function (e, t) {
  35241. function r() {}
  35242. r.prototype = t.prototype, e.prototype = new r();
  35243. }, a.extend = function () {
  35244. var e,
  35245. t,
  35246. r = {};
  35247. for (e = 0; e < arguments.length; e++) for (t in arguments[e]) Object.prototype.hasOwnProperty.call(arguments[e], t) && void 0 === r[t] && (r[t] = arguments[e][t]);
  35248. return r;
  35249. }, a.prepareContent = function (r, e, n, i, s) {
  35250. return u.Promise.resolve(e).then(function (n) {
  35251. return o.blob && (n instanceof Blob || -1 !== ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(n))) && "undefined" != typeof FileReader ? new u.Promise(function (t, r) {
  35252. var e = new FileReader();
  35253. e.onload = function (e) {
  35254. t(e.target.result);
  35255. }, e.onerror = function (e) {
  35256. r(e.target.error);
  35257. }, e.readAsArrayBuffer(n);
  35258. }) : n;
  35259. }).then(function (e) {
  35260. var t = a.getTypeOf(e);
  35261. return t ? ("arraybuffer" === t ? e = a.transformTo("uint8array", e) : "string" === t && (s ? e = h.decode(e) : n && !0 !== i && (e = function (e) {
  35262. return l(e, o.uint8array ? new Uint8Array(e.length) : new Array(e.length));
  35263. }(e))), e) : u.Promise.reject(new Error("Can't read the data of '" + r + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"));
  35264. });
  35265. };
  35266. }, {
  35267. "./base64": 1,
  35268. "./external": 6,
  35269. "./nodejsUtils": 14,
  35270. "./support": 30,
  35271. setimmediate: 54
  35272. }],
  35273. 33: [function (e, t, r) {
  35274. "use strict";
  35275. var n = e("./reader/readerFor"),
  35276. i = e("./utils"),
  35277. s = e("./signature"),
  35278. a = e("./zipEntry"),
  35279. o = e("./support");
  35280. function h(e) {
  35281. this.files = [], this.loadOptions = e;
  35282. }
  35283. h.prototype = {
  35284. checkSignature: function (e) {
  35285. if (!this.reader.readAndCheckSignature(e)) {
  35286. this.reader.index -= 4;
  35287. var t = this.reader.readString(4);
  35288. throw new Error("Corrupted zip or bug: unexpected signature (" + i.pretty(t) + ", expected " + i.pretty(e) + ")");
  35289. }
  35290. },
  35291. isSignature: function (e, t) {
  35292. var r = this.reader.index;
  35293. this.reader.setIndex(e);
  35294. var n = this.reader.readString(4) === t;
  35295. return this.reader.setIndex(r), n;
  35296. },
  35297. readBlockEndOfCentral: function () {
  35298. this.diskNumber = this.reader.readInt(2), this.diskWithCentralDirStart = this.reader.readInt(2), this.centralDirRecordsOnThisDisk = this.reader.readInt(2), this.centralDirRecords = this.reader.readInt(2), this.centralDirSize = this.reader.readInt(4), this.centralDirOffset = this.reader.readInt(4), this.zipCommentLength = this.reader.readInt(2);
  35299. var e = this.reader.readData(this.zipCommentLength),
  35300. t = o.uint8array ? "uint8array" : "array",
  35301. r = i.transformTo(t, e);
  35302. this.zipComment = this.loadOptions.decodeFileName(r);
  35303. },
  35304. readBlockZip64EndOfCentral: function () {
  35305. this.zip64EndOfCentralSize = this.reader.readInt(8), this.reader.skip(4), this.diskNumber = this.reader.readInt(4), this.diskWithCentralDirStart = this.reader.readInt(4), this.centralDirRecordsOnThisDisk = this.reader.readInt(8), this.centralDirRecords = this.reader.readInt(8), this.centralDirSize = this.reader.readInt(8), this.centralDirOffset = this.reader.readInt(8), this.zip64ExtensibleData = {};
  35306. for (var e, t, r, n = this.zip64EndOfCentralSize - 44; 0 < n;) e = this.reader.readInt(2), t = this.reader.readInt(4), r = this.reader.readData(t), this.zip64ExtensibleData[e] = {
  35307. id: e,
  35308. length: t,
  35309. value: r
  35310. };
  35311. },
  35312. readBlockZip64EndOfCentralLocator: function () {
  35313. if (this.diskWithZip64CentralDirStart = this.reader.readInt(4), this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8), this.disksCount = this.reader.readInt(4), 1 < this.disksCount) throw new Error("Multi-volumes zip are not supported");
  35314. },
  35315. readLocalFiles: function () {
  35316. var e, t;
  35317. for (e = 0; e < this.files.length; e++) t = this.files[e], this.reader.setIndex(t.localHeaderOffset), this.checkSignature(s.LOCAL_FILE_HEADER), t.readLocalPart(this.reader), t.handleUTF8(), t.processAttributes();
  35318. },
  35319. readCentralDir: function () {
  35320. var e;
  35321. for (this.reader.setIndex(this.centralDirOffset); this.reader.readAndCheckSignature(s.CENTRAL_FILE_HEADER);) (e = new a({
  35322. zip64: this.zip64
  35323. }, this.loadOptions)).readCentralPart(this.reader), this.files.push(e);
  35324. if (this.centralDirRecords !== this.files.length && 0 !== this.centralDirRecords && 0 === this.files.length) throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  35325. },
  35326. readEndOfCentral: function () {
  35327. var e = this.reader.lastIndexOfSignature(s.CENTRAL_DIRECTORY_END);
  35328. if (e < 0) throw !this.isSignature(0, s.LOCAL_FILE_HEADER) ? new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html") : new Error("Corrupted zip: can't find end of central directory");
  35329. this.reader.setIndex(e);
  35330. var t = e;
  35331. if (this.checkSignature(s.CENTRAL_DIRECTORY_END), this.readBlockEndOfCentral(), this.diskNumber === i.MAX_VALUE_16BITS || this.diskWithCentralDirStart === i.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === i.MAX_VALUE_16BITS || this.centralDirRecords === i.MAX_VALUE_16BITS || this.centralDirSize === i.MAX_VALUE_32BITS || this.centralDirOffset === i.MAX_VALUE_32BITS) {
  35332. if (this.zip64 = !0, (e = this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR)) < 0) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
  35333. if (this.reader.setIndex(e), this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR), this.readBlockZip64EndOfCentralLocator(), !this.isSignature(this.relativeOffsetEndOfZip64CentralDir, s.ZIP64_CENTRAL_DIRECTORY_END) && (this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_END), this.relativeOffsetEndOfZip64CentralDir < 0)) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
  35334. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir), this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_END), this.readBlockZip64EndOfCentral();
  35335. }
  35336. var r = this.centralDirOffset + this.centralDirSize;
  35337. this.zip64 && (r += 20, r += 12 + this.zip64EndOfCentralSize);
  35338. var n = t - r;
  35339. if (0 < n) this.isSignature(t, s.CENTRAL_FILE_HEADER) || (this.reader.zero = n);else if (n < 0) throw new Error("Corrupted zip: missing " + Math.abs(n) + " bytes.");
  35340. },
  35341. prepareReader: function (e) {
  35342. this.reader = n(e);
  35343. },
  35344. load: function (e) {
  35345. this.prepareReader(e), this.readEndOfCentral(), this.readCentralDir(), this.readLocalFiles();
  35346. }
  35347. }, t.exports = h;
  35348. }, {
  35349. "./reader/readerFor": 22,
  35350. "./signature": 23,
  35351. "./support": 30,
  35352. "./utils": 32,
  35353. "./zipEntry": 34
  35354. }],
  35355. 34: [function (e, t, r) {
  35356. "use strict";
  35357. var n = e("./reader/readerFor"),
  35358. s = e("./utils"),
  35359. i = e("./compressedObject"),
  35360. a = e("./crc32"),
  35361. o = e("./utf8"),
  35362. h = e("./compressions"),
  35363. u = e("./support");
  35364. function l(e, t) {
  35365. this.options = e, this.loadOptions = t;
  35366. }
  35367. l.prototype = {
  35368. isEncrypted: function () {
  35369. return 1 == (1 & this.bitFlag);
  35370. },
  35371. useUTF8: function () {
  35372. return 2048 == (2048 & this.bitFlag);
  35373. },
  35374. readLocalPart: function (e) {
  35375. var t, r;
  35376. if (e.skip(22), this.fileNameLength = e.readInt(2), r = e.readInt(2), this.fileName = e.readData(this.fileNameLength), e.skip(r), -1 === this.compressedSize || -1 === this.uncompressedSize) throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");
  35377. if (null === (t = function (e) {
  35378. for (var t in h) if (Object.prototype.hasOwnProperty.call(h, t) && h[t].magic === e) return h[t];
  35379. return null;
  35380. }(this.compressionMethod))) throw new Error("Corrupted zip : compression " + s.pretty(this.compressionMethod) + " unknown (inner file : " + s.transformTo("string", this.fileName) + ")");
  35381. this.decompressed = new i(this.compressedSize, this.uncompressedSize, this.crc32, t, e.readData(this.compressedSize));
  35382. },
  35383. readCentralPart: function (e) {
  35384. this.versionMadeBy = e.readInt(2), e.skip(2), this.bitFlag = e.readInt(2), this.compressionMethod = e.readString(2), this.date = e.readDate(), this.crc32 = e.readInt(4), this.compressedSize = e.readInt(4), this.uncompressedSize = e.readInt(4);
  35385. var t = e.readInt(2);
  35386. if (this.extraFieldsLength = e.readInt(2), this.fileCommentLength = e.readInt(2), this.diskNumberStart = e.readInt(2), this.internalFileAttributes = e.readInt(2), this.externalFileAttributes = e.readInt(4), this.localHeaderOffset = e.readInt(4), this.isEncrypted()) throw new Error("Encrypted zip are not supported");
  35387. e.skip(t), this.readExtraFields(e), this.parseZIP64ExtraField(e), this.fileComment = e.readData(this.fileCommentLength);
  35388. },
  35389. processAttributes: function () {
  35390. this.unixPermissions = null, this.dosPermissions = null;
  35391. var e = this.versionMadeBy >> 8;
  35392. this.dir = !!(16 & this.externalFileAttributes), 0 == e && (this.dosPermissions = 63 & this.externalFileAttributes), 3 == e && (this.unixPermissions = this.externalFileAttributes >> 16 & 65535), this.dir || "/" !== this.fileNameStr.slice(-1) || (this.dir = !0);
  35393. },
  35394. parseZIP64ExtraField: function () {
  35395. if (this.extraFields[1]) {
  35396. var e = n(this.extraFields[1].value);
  35397. this.uncompressedSize === s.MAX_VALUE_32BITS && (this.uncompressedSize = e.readInt(8)), this.compressedSize === s.MAX_VALUE_32BITS && (this.compressedSize = e.readInt(8)), this.localHeaderOffset === s.MAX_VALUE_32BITS && (this.localHeaderOffset = e.readInt(8)), this.diskNumberStart === s.MAX_VALUE_32BITS && (this.diskNumberStart = e.readInt(4));
  35398. }
  35399. },
  35400. readExtraFields: function (e) {
  35401. var t,
  35402. r,
  35403. n,
  35404. i = e.index + this.extraFieldsLength;
  35405. for (this.extraFields || (this.extraFields = {}); e.index + 4 < i;) t = e.readInt(2), r = e.readInt(2), n = e.readData(r), this.extraFields[t] = {
  35406. id: t,
  35407. length: r,
  35408. value: n
  35409. };
  35410. e.setIndex(i);
  35411. },
  35412. handleUTF8: function () {
  35413. var e = u.uint8array ? "uint8array" : "array";
  35414. if (this.useUTF8()) this.fileNameStr = o.utf8decode(this.fileName), this.fileCommentStr = o.utf8decode(this.fileComment);else {
  35415. var t = this.findExtraFieldUnicodePath();
  35416. if (null !== t) this.fileNameStr = t;else {
  35417. var r = s.transformTo(e, this.fileName);
  35418. this.fileNameStr = this.loadOptions.decodeFileName(r);
  35419. }
  35420. var n = this.findExtraFieldUnicodeComment();
  35421. if (null !== n) this.fileCommentStr = n;else {
  35422. var i = s.transformTo(e, this.fileComment);
  35423. this.fileCommentStr = this.loadOptions.decodeFileName(i);
  35424. }
  35425. }
  35426. },
  35427. findExtraFieldUnicodePath: function () {
  35428. var e = this.extraFields[28789];
  35429. if (e) {
  35430. var t = n(e.value);
  35431. return 1 !== t.readInt(1) ? null : a(this.fileName) !== t.readInt(4) ? null : o.utf8decode(t.readData(e.length - 5));
  35432. }
  35433. return null;
  35434. },
  35435. findExtraFieldUnicodeComment: function () {
  35436. var e = this.extraFields[25461];
  35437. if (e) {
  35438. var t = n(e.value);
  35439. return 1 !== t.readInt(1) ? null : a(this.fileComment) !== t.readInt(4) ? null : o.utf8decode(t.readData(e.length - 5));
  35440. }
  35441. return null;
  35442. }
  35443. }, t.exports = l;
  35444. }, {
  35445. "./compressedObject": 2,
  35446. "./compressions": 3,
  35447. "./crc32": 4,
  35448. "./reader/readerFor": 22,
  35449. "./support": 30,
  35450. "./utf8": 31,
  35451. "./utils": 32
  35452. }],
  35453. 35: [function (e, t, r) {
  35454. "use strict";
  35455. function n(e, t, r) {
  35456. this.name = e, this.dir = r.dir, this.date = r.date, this.comment = r.comment, this.unixPermissions = r.unixPermissions, this.dosPermissions = r.dosPermissions, this._data = t, this._dataBinary = r.binary, this.options = {
  35457. compression: r.compression,
  35458. compressionOptions: r.compressionOptions
  35459. };
  35460. }
  35461. var s = e("./stream/StreamHelper"),
  35462. i = e("./stream/DataWorker"),
  35463. a = e("./utf8"),
  35464. o = e("./compressedObject"),
  35465. h = e("./stream/GenericWorker");
  35466. n.prototype = {
  35467. internalStream: function (e) {
  35468. var t = null,
  35469. r = "string";
  35470. try {
  35471. if (!e) throw new Error("No output type specified.");
  35472. var n = "string" === (r = e.toLowerCase()) || "text" === r;
  35473. "binarystring" !== r && "text" !== r || (r = "string"), t = this._decompressWorker();
  35474. var i = !this._dataBinary;
  35475. i && !n && (t = t.pipe(new a.Utf8EncodeWorker())), !i && n && (t = t.pipe(new a.Utf8DecodeWorker()));
  35476. } catch (e) {
  35477. (t = new h("error")).error(e);
  35478. }
  35479. return new s(t, r, "");
  35480. },
  35481. async: function (e, t) {
  35482. return this.internalStream(e).accumulate(t);
  35483. },
  35484. nodeStream: function (e, t) {
  35485. return this.internalStream(e || "nodebuffer").toNodejsStream(t);
  35486. },
  35487. _compressWorker: function (e, t) {
  35488. if (this._data instanceof o && this._data.compression.magic === e.magic) return this._data.getCompressedWorker();
  35489. var r = this._decompressWorker();
  35490. return this._dataBinary || (r = r.pipe(new a.Utf8EncodeWorker())), o.createWorkerFrom(r, e, t);
  35491. },
  35492. _decompressWorker: function () {
  35493. return this._data instanceof o ? this._data.getContentWorker() : this._data instanceof h ? this._data : new i(this._data);
  35494. }
  35495. };
  35496. for (var u = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"], l = function () {
  35497. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  35498. }, f = 0; f < u.length; f++) n.prototype[u[f]] = l;
  35499. t.exports = n;
  35500. }, {
  35501. "./compressedObject": 2,
  35502. "./stream/DataWorker": 27,
  35503. "./stream/GenericWorker": 28,
  35504. "./stream/StreamHelper": 29,
  35505. "./utf8": 31
  35506. }],
  35507. 36: [function (e, l, t) {
  35508. (function (t) {
  35509. "use strict";
  35510. var r,
  35511. n,
  35512. e = t.MutationObserver || t.WebKitMutationObserver;
  35513. if (e) {
  35514. var i = 0,
  35515. s = new e(u),
  35516. a = t.document.createTextNode("");
  35517. s.observe(a, {
  35518. characterData: !0
  35519. }), r = function () {
  35520. a.data = i = ++i % 2;
  35521. };
  35522. } else if (t.setImmediate || void 0 === t.MessageChannel) r = "document" in t && "onreadystatechange" in t.document.createElement("script") ? function () {
  35523. var e = t.document.createElement("script");
  35524. e.onreadystatechange = function () {
  35525. u(), e.onreadystatechange = null, e.parentNode.removeChild(e), e = null;
  35526. }, t.document.documentElement.appendChild(e);
  35527. } : function () {
  35528. setTimeout(u, 0);
  35529. };else {
  35530. var o = new t.MessageChannel();
  35531. o.port1.onmessage = u, r = function () {
  35532. o.port2.postMessage(0);
  35533. };
  35534. }
  35535. var h = [];
  35536. function u() {
  35537. var e, t;
  35538. n = !0;
  35539. for (var r = h.length; r;) {
  35540. for (t = h, h = [], e = -1; ++e < r;) t[e]();
  35541. r = h.length;
  35542. }
  35543. n = !1;
  35544. }
  35545. l.exports = function (e) {
  35546. 1 !== h.push(e) || n || r();
  35547. };
  35548. }).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
  35549. }, {}],
  35550. 37: [function (e, t, r) {
  35551. "use strict";
  35552. var i = e("immediate");
  35553. function u() {}
  35554. var l = {},
  35555. s = ["REJECTED"],
  35556. a = ["FULFILLED"],
  35557. n = ["PENDING"];
  35558. function o(e) {
  35559. if ("function" != typeof e) throw new TypeError("resolver must be a function");
  35560. this.state = n, this.queue = [], this.outcome = void 0, e !== u && d(this, e);
  35561. }
  35562. function h(e, t, r) {
  35563. this.promise = e, "function" == typeof t && (this.onFulfilled = t, this.callFulfilled = this.otherCallFulfilled), "function" == typeof r && (this.onRejected = r, this.callRejected = this.otherCallRejected);
  35564. }
  35565. function f(t, r, n) {
  35566. i(function () {
  35567. var e;
  35568. try {
  35569. e = r(n);
  35570. } catch (e) {
  35571. return l.reject(t, e);
  35572. }
  35573. e === t ? l.reject(t, new TypeError("Cannot resolve promise with itself")) : l.resolve(t, e);
  35574. });
  35575. }
  35576. function c(e) {
  35577. var t = e && e.then;
  35578. if (e && ("object" == typeof e || "function" == typeof e) && "function" == typeof t) return function () {
  35579. t.apply(e, arguments);
  35580. };
  35581. }
  35582. function d(t, e) {
  35583. var r = !1;
  35584. function n(e) {
  35585. r || (r = !0, l.reject(t, e));
  35586. }
  35587. function i(e) {
  35588. r || (r = !0, l.resolve(t, e));
  35589. }
  35590. var s = p(function () {
  35591. e(i, n);
  35592. });
  35593. "error" === s.status && n(s.value);
  35594. }
  35595. function p(e, t) {
  35596. var r = {};
  35597. try {
  35598. r.value = e(t), r.status = "success";
  35599. } catch (e) {
  35600. r.status = "error", r.value = e;
  35601. }
  35602. return r;
  35603. }
  35604. (t.exports = o).prototype.finally = function (t) {
  35605. if ("function" != typeof t) return this;
  35606. var r = this.constructor;
  35607. return this.then(function (e) {
  35608. return r.resolve(t()).then(function () {
  35609. return e;
  35610. });
  35611. }, function (e) {
  35612. return r.resolve(t()).then(function () {
  35613. throw e;
  35614. });
  35615. });
  35616. }, o.prototype.catch = function (e) {
  35617. return this.then(null, e);
  35618. }, o.prototype.then = function (e, t) {
  35619. if ("function" != typeof e && this.state === a || "function" != typeof t && this.state === s) return this;
  35620. var r = new this.constructor(u);
  35621. this.state !== n ? f(r, this.state === a ? e : t, this.outcome) : this.queue.push(new h(r, e, t));
  35622. return r;
  35623. }, h.prototype.callFulfilled = function (e) {
  35624. l.resolve(this.promise, e);
  35625. }, h.prototype.otherCallFulfilled = function (e) {
  35626. f(this.promise, this.onFulfilled, e);
  35627. }, h.prototype.callRejected = function (e) {
  35628. l.reject(this.promise, e);
  35629. }, h.prototype.otherCallRejected = function (e) {
  35630. f(this.promise, this.onRejected, e);
  35631. }, l.resolve = function (e, t) {
  35632. var r = p(c, t);
  35633. if ("error" === r.status) return l.reject(e, r.value);
  35634. var n = r.value;
  35635. if (n) d(e, n);else {
  35636. e.state = a, e.outcome = t;
  35637. for (var i = -1, s = e.queue.length; ++i < s;) e.queue[i].callFulfilled(t);
  35638. }
  35639. return e;
  35640. }, l.reject = function (e, t) {
  35641. e.state = s, e.outcome = t;
  35642. for (var r = -1, n = e.queue.length; ++r < n;) e.queue[r].callRejected(t);
  35643. return e;
  35644. }, o.resolve = function (e) {
  35645. if (e instanceof this) return e;
  35646. return l.resolve(new this(u), e);
  35647. }, o.reject = function (e) {
  35648. var t = new this(u);
  35649. return l.reject(t, e);
  35650. }, o.all = function (e) {
  35651. var r = this;
  35652. if ("[object Array]" !== Object.prototype.toString.call(e)) return this.reject(new TypeError("must be an array"));
  35653. var n = e.length,
  35654. i = !1;
  35655. if (!n) return this.resolve([]);
  35656. var s = new Array(n),
  35657. a = 0,
  35658. t = -1,
  35659. o = new this(u);
  35660. for (; ++t < n;) h(e[t], t);
  35661. return o;
  35662. function h(e, t) {
  35663. r.resolve(e).then(function (e) {
  35664. s[t] = e, ++a !== n || i || (i = !0, l.resolve(o, s));
  35665. }, function (e) {
  35666. i || (i = !0, l.reject(o, e));
  35667. });
  35668. }
  35669. }, o.race = function (e) {
  35670. var t = this;
  35671. if ("[object Array]" !== Object.prototype.toString.call(e)) return this.reject(new TypeError("must be an array"));
  35672. var r = e.length,
  35673. n = !1;
  35674. if (!r) return this.resolve([]);
  35675. var i = -1,
  35676. s = new this(u);
  35677. for (; ++i < r;) a = e[i], t.resolve(a).then(function (e) {
  35678. n || (n = !0, l.resolve(s, e));
  35679. }, function (e) {
  35680. n || (n = !0, l.reject(s, e));
  35681. });
  35682. var a;
  35683. return s;
  35684. };
  35685. }, {
  35686. immediate: 36
  35687. }],
  35688. 38: [function (e, t, r) {
  35689. "use strict";
  35690. var n = {};
  35691. (0, e("./lib/utils/common").assign)(n, e("./lib/deflate"), e("./lib/inflate"), e("./lib/zlib/constants")), t.exports = n;
  35692. }, {
  35693. "./lib/deflate": 39,
  35694. "./lib/inflate": 40,
  35695. "./lib/utils/common": 41,
  35696. "./lib/zlib/constants": 44
  35697. }],
  35698. 39: [function (e, t, r) {
  35699. "use strict";
  35700. var a = e("./zlib/deflate"),
  35701. o = e("./utils/common"),
  35702. h = e("./utils/strings"),
  35703. i = e("./zlib/messages"),
  35704. s = e("./zlib/zstream"),
  35705. u = Object.prototype.toString,
  35706. l = 0,
  35707. f = -1,
  35708. c = 0,
  35709. d = 8;
  35710. function p(e) {
  35711. if (!(this instanceof p)) return new p(e);
  35712. this.options = o.assign({
  35713. level: f,
  35714. method: d,
  35715. chunkSize: 16384,
  35716. windowBits: 15,
  35717. memLevel: 8,
  35718. strategy: c,
  35719. to: ""
  35720. }, e || {});
  35721. var t = this.options;
  35722. t.raw && 0 < t.windowBits ? t.windowBits = -t.windowBits : t.gzip && 0 < t.windowBits && t.windowBits < 16 && (t.windowBits += 16), this.err = 0, this.msg = "", this.ended = !1, this.chunks = [], this.strm = new s(), this.strm.avail_out = 0;
  35723. var r = a.deflateInit2(this.strm, t.level, t.method, t.windowBits, t.memLevel, t.strategy);
  35724. if (r !== l) throw new Error(i[r]);
  35725. if (t.header && a.deflateSetHeader(this.strm, t.header), t.dictionary) {
  35726. var n;
  35727. if (n = "string" == typeof t.dictionary ? h.string2buf(t.dictionary) : "[object ArrayBuffer]" === u.call(t.dictionary) ? new Uint8Array(t.dictionary) : t.dictionary, (r = a.deflateSetDictionary(this.strm, n)) !== l) throw new Error(i[r]);
  35728. this._dict_set = !0;
  35729. }
  35730. }
  35731. function n(e, t) {
  35732. var r = new p(t);
  35733. if (r.push(e, !0), r.err) throw r.msg || i[r.err];
  35734. return r.result;
  35735. }
  35736. p.prototype.push = function (e, t) {
  35737. var r,
  35738. n,
  35739. i = this.strm,
  35740. s = this.options.chunkSize;
  35741. if (this.ended) return !1;
  35742. n = t === ~~t ? t : !0 === t ? 4 : 0, "string" == typeof e ? i.input = h.string2buf(e) : "[object ArrayBuffer]" === u.call(e) ? i.input = new Uint8Array(e) : i.input = e, i.next_in = 0, i.avail_in = i.input.length;
  35743. do {
  35744. if (0 === i.avail_out && (i.output = new o.Buf8(s), i.next_out = 0, i.avail_out = s), 1 !== (r = a.deflate(i, n)) && r !== l) return this.onEnd(r), !(this.ended = !0);
  35745. 0 !== i.avail_out && (0 !== i.avail_in || 4 !== n && 2 !== n) || ("string" === this.options.to ? this.onData(h.buf2binstring(o.shrinkBuf(i.output, i.next_out))) : this.onData(o.shrinkBuf(i.output, i.next_out)));
  35746. } while ((0 < i.avail_in || 0 === i.avail_out) && 1 !== r);
  35747. return 4 === n ? (r = a.deflateEnd(this.strm), this.onEnd(r), this.ended = !0, r === l) : 2 !== n || (this.onEnd(l), !(i.avail_out = 0));
  35748. }, p.prototype.onData = function (e) {
  35749. this.chunks.push(e);
  35750. }, p.prototype.onEnd = function (e) {
  35751. e === l && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = o.flattenChunks(this.chunks)), this.chunks = [], this.err = e, this.msg = this.strm.msg;
  35752. }, r.Deflate = p, r.deflate = n, r.deflateRaw = function (e, t) {
  35753. return (t = t || {}).raw = !0, n(e, t);
  35754. }, r.gzip = function (e, t) {
  35755. return (t = t || {}).gzip = !0, n(e, t);
  35756. };
  35757. }, {
  35758. "./utils/common": 41,
  35759. "./utils/strings": 42,
  35760. "./zlib/deflate": 46,
  35761. "./zlib/messages": 51,
  35762. "./zlib/zstream": 53
  35763. }],
  35764. 40: [function (e, t, r) {
  35765. "use strict";
  35766. var c = e("./zlib/inflate"),
  35767. d = e("./utils/common"),
  35768. p = e("./utils/strings"),
  35769. m = e("./zlib/constants"),
  35770. n = e("./zlib/messages"),
  35771. i = e("./zlib/zstream"),
  35772. s = e("./zlib/gzheader"),
  35773. _ = Object.prototype.toString;
  35774. function a(e) {
  35775. if (!(this instanceof a)) return new a(e);
  35776. this.options = d.assign({
  35777. chunkSize: 16384,
  35778. windowBits: 0,
  35779. to: ""
  35780. }, e || {});
  35781. var t = this.options;
  35782. t.raw && 0 <= t.windowBits && t.windowBits < 16 && (t.windowBits = -t.windowBits, 0 === t.windowBits && (t.windowBits = -15)), !(0 <= t.windowBits && t.windowBits < 16) || e && e.windowBits || (t.windowBits += 32), 15 < t.windowBits && t.windowBits < 48 && 0 == (15 & t.windowBits) && (t.windowBits |= 15), this.err = 0, this.msg = "", this.ended = !1, this.chunks = [], this.strm = new i(), this.strm.avail_out = 0;
  35783. var r = c.inflateInit2(this.strm, t.windowBits);
  35784. if (r !== m.Z_OK) throw new Error(n[r]);
  35785. this.header = new s(), c.inflateGetHeader(this.strm, this.header);
  35786. }
  35787. function o(e, t) {
  35788. var r = new a(t);
  35789. if (r.push(e, !0), r.err) throw r.msg || n[r.err];
  35790. return r.result;
  35791. }
  35792. a.prototype.push = function (e, t) {
  35793. var r,
  35794. n,
  35795. i,
  35796. s,
  35797. a,
  35798. o,
  35799. h = this.strm,
  35800. u = this.options.chunkSize,
  35801. l = this.options.dictionary,
  35802. f = !1;
  35803. if (this.ended) return !1;
  35804. n = t === ~~t ? t : !0 === t ? m.Z_FINISH : m.Z_NO_FLUSH, "string" == typeof e ? h.input = p.binstring2buf(e) : "[object ArrayBuffer]" === _.call(e) ? h.input = new Uint8Array(e) : h.input = e, h.next_in = 0, h.avail_in = h.input.length;
  35805. do {
  35806. if (0 === h.avail_out && (h.output = new d.Buf8(u), h.next_out = 0, h.avail_out = u), (r = c.inflate(h, m.Z_NO_FLUSH)) === m.Z_NEED_DICT && l && (o = "string" == typeof l ? p.string2buf(l) : "[object ArrayBuffer]" === _.call(l) ? new Uint8Array(l) : l, r = c.inflateSetDictionary(this.strm, o)), r === m.Z_BUF_ERROR && !0 === f && (r = m.Z_OK, f = !1), r !== m.Z_STREAM_END && r !== m.Z_OK) return this.onEnd(r), !(this.ended = !0);
  35807. h.next_out && (0 !== h.avail_out && r !== m.Z_STREAM_END && (0 !== h.avail_in || n !== m.Z_FINISH && n !== m.Z_SYNC_FLUSH) || ("string" === this.options.to ? (i = p.utf8border(h.output, h.next_out), s = h.next_out - i, a = p.buf2string(h.output, i), h.next_out = s, h.avail_out = u - s, s && d.arraySet(h.output, h.output, i, s, 0), this.onData(a)) : this.onData(d.shrinkBuf(h.output, h.next_out)))), 0 === h.avail_in && 0 === h.avail_out && (f = !0);
  35808. } while ((0 < h.avail_in || 0 === h.avail_out) && r !== m.Z_STREAM_END);
  35809. return r === m.Z_STREAM_END && (n = m.Z_FINISH), n === m.Z_FINISH ? (r = c.inflateEnd(this.strm), this.onEnd(r), this.ended = !0, r === m.Z_OK) : n !== m.Z_SYNC_FLUSH || (this.onEnd(m.Z_OK), !(h.avail_out = 0));
  35810. }, a.prototype.onData = function (e) {
  35811. this.chunks.push(e);
  35812. }, a.prototype.onEnd = function (e) {
  35813. e === m.Z_OK && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = d.flattenChunks(this.chunks)), this.chunks = [], this.err = e, this.msg = this.strm.msg;
  35814. }, r.Inflate = a, r.inflate = o, r.inflateRaw = function (e, t) {
  35815. return (t = t || {}).raw = !0, o(e, t);
  35816. }, r.ungzip = o;
  35817. }, {
  35818. "./utils/common": 41,
  35819. "./utils/strings": 42,
  35820. "./zlib/constants": 44,
  35821. "./zlib/gzheader": 47,
  35822. "./zlib/inflate": 49,
  35823. "./zlib/messages": 51,
  35824. "./zlib/zstream": 53
  35825. }],
  35826. 41: [function (e, t, r) {
  35827. "use strict";
  35828. var n = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Int32Array;
  35829. r.assign = function (e) {
  35830. for (var t = Array.prototype.slice.call(arguments, 1); t.length;) {
  35831. var r = t.shift();
  35832. if (r) {
  35833. if ("object" != typeof r) throw new TypeError(r + "must be non-object");
  35834. for (var n in r) r.hasOwnProperty(n) && (e[n] = r[n]);
  35835. }
  35836. }
  35837. return e;
  35838. }, r.shrinkBuf = function (e, t) {
  35839. return e.length === t ? e : e.subarray ? e.subarray(0, t) : (e.length = t, e);
  35840. };
  35841. var i = {
  35842. arraySet: function (e, t, r, n, i) {
  35843. if (t.subarray && e.subarray) e.set(t.subarray(r, r + n), i);else for (var s = 0; s < n; s++) e[i + s] = t[r + s];
  35844. },
  35845. flattenChunks: function (e) {
  35846. var t, r, n, i, s, a;
  35847. for (t = n = 0, r = e.length; t < r; t++) n += e[t].length;
  35848. for (a = new Uint8Array(n), t = i = 0, r = e.length; t < r; t++) s = e[t], a.set(s, i), i += s.length;
  35849. return a;
  35850. }
  35851. },
  35852. s = {
  35853. arraySet: function (e, t, r, n, i) {
  35854. for (var s = 0; s < n; s++) e[i + s] = t[r + s];
  35855. },
  35856. flattenChunks: function (e) {
  35857. return [].concat.apply([], e);
  35858. }
  35859. };
  35860. r.setTyped = function (e) {
  35861. e ? (r.Buf8 = Uint8Array, r.Buf16 = Uint16Array, r.Buf32 = Int32Array, r.assign(r, i)) : (r.Buf8 = Array, r.Buf16 = Array, r.Buf32 = Array, r.assign(r, s));
  35862. }, r.setTyped(n);
  35863. }, {}],
  35864. 42: [function (e, t, r) {
  35865. "use strict";
  35866. var h = e("./common"),
  35867. i = !0,
  35868. s = !0;
  35869. try {
  35870. String.fromCharCode.apply(null, [0]);
  35871. } catch (e) {
  35872. i = !1;
  35873. }
  35874. try {
  35875. String.fromCharCode.apply(null, new Uint8Array(1));
  35876. } catch (e) {
  35877. s = !1;
  35878. }
  35879. for (var u = new h.Buf8(256), n = 0; n < 256; n++) u[n] = 252 <= n ? 6 : 248 <= n ? 5 : 240 <= n ? 4 : 224 <= n ? 3 : 192 <= n ? 2 : 1;
  35880. function l(e, t) {
  35881. if (t < 65537 && (e.subarray && s || !e.subarray && i)) return String.fromCharCode.apply(null, h.shrinkBuf(e, t));
  35882. for (var r = "", n = 0; n < t; n++) r += String.fromCharCode(e[n]);
  35883. return r;
  35884. }
  35885. u[254] = u[254] = 1, r.string2buf = function (e) {
  35886. var t,
  35887. r,
  35888. n,
  35889. i,
  35890. s,
  35891. a = e.length,
  35892. o = 0;
  35893. for (i = 0; i < a; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), o += r < 128 ? 1 : r < 2048 ? 2 : r < 65536 ? 3 : 4;
  35894. for (t = new h.Buf8(o), i = s = 0; s < o; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), r < 128 ? t[s++] = r : (r < 2048 ? t[s++] = 192 | r >>> 6 : (r < 65536 ? t[s++] = 224 | r >>> 12 : (t[s++] = 240 | r >>> 18, t[s++] = 128 | r >>> 12 & 63), t[s++] = 128 | r >>> 6 & 63), t[s++] = 128 | 63 & r);
  35895. return t;
  35896. }, r.buf2binstring = function (e) {
  35897. return l(e, e.length);
  35898. }, r.binstring2buf = function (e) {
  35899. for (var t = new h.Buf8(e.length), r = 0, n = t.length; r < n; r++) t[r] = e.charCodeAt(r);
  35900. return t;
  35901. }, r.buf2string = function (e, t) {
  35902. var r,
  35903. n,
  35904. i,
  35905. s,
  35906. a = t || e.length,
  35907. o = new Array(2 * a);
  35908. for (r = n = 0; r < a;) if ((i = e[r++]) < 128) o[n++] = i;else if (4 < (s = u[i])) o[n++] = 65533, r += s - 1;else {
  35909. for (i &= 2 === s ? 31 : 3 === s ? 15 : 7; 1 < s && r < a;) i = i << 6 | 63 & e[r++], s--;
  35910. 1 < s ? o[n++] = 65533 : i < 65536 ? o[n++] = i : (i -= 65536, o[n++] = 55296 | i >> 10 & 1023, o[n++] = 56320 | 1023 & i);
  35911. }
  35912. return l(o, n);
  35913. }, r.utf8border = function (e, t) {
  35914. var r;
  35915. for ((t = t || e.length) > e.length && (t = e.length), r = t - 1; 0 <= r && 128 == (192 & e[r]);) r--;
  35916. return r < 0 ? t : 0 === r ? t : r + u[e[r]] > t ? r : t;
  35917. };
  35918. }, {
  35919. "./common": 41
  35920. }],
  35921. 43: [function (e, t, r) {
  35922. "use strict";
  35923. t.exports = function (e, t, r, n) {
  35924. for (var i = 65535 & e | 0, s = e >>> 16 & 65535 | 0, a = 0; 0 !== r;) {
  35925. for (r -= a = 2e3 < r ? 2e3 : r; s = s + (i = i + t[n++] | 0) | 0, --a;);
  35926. i %= 65521, s %= 65521;
  35927. }
  35928. return i | s << 16 | 0;
  35929. };
  35930. }, {}],
  35931. 44: [function (e, t, r) {
  35932. "use strict";
  35933. t.exports = {
  35934. Z_NO_FLUSH: 0,
  35935. Z_PARTIAL_FLUSH: 1,
  35936. Z_SYNC_FLUSH: 2,
  35937. Z_FULL_FLUSH: 3,
  35938. Z_FINISH: 4,
  35939. Z_BLOCK: 5,
  35940. Z_TREES: 6,
  35941. Z_OK: 0,
  35942. Z_STREAM_END: 1,
  35943. Z_NEED_DICT: 2,
  35944. Z_ERRNO: -1,
  35945. Z_STREAM_ERROR: -2,
  35946. Z_DATA_ERROR: -3,
  35947. Z_BUF_ERROR: -5,
  35948. Z_NO_COMPRESSION: 0,
  35949. Z_BEST_SPEED: 1,
  35950. Z_BEST_COMPRESSION: 9,
  35951. Z_DEFAULT_COMPRESSION: -1,
  35952. Z_FILTERED: 1,
  35953. Z_HUFFMAN_ONLY: 2,
  35954. Z_RLE: 3,
  35955. Z_FIXED: 4,
  35956. Z_DEFAULT_STRATEGY: 0,
  35957. Z_BINARY: 0,
  35958. Z_TEXT: 1,
  35959. Z_UNKNOWN: 2,
  35960. Z_DEFLATED: 8
  35961. };
  35962. }, {}],
  35963. 45: [function (e, t, r) {
  35964. "use strict";
  35965. var o = function () {
  35966. for (var e, t = [], r = 0; r < 256; r++) {
  35967. e = r;
  35968. for (var n = 0; n < 8; n++) e = 1 & e ? 3988292384 ^ e >>> 1 : e >>> 1;
  35969. t[r] = e;
  35970. }
  35971. return t;
  35972. }();
  35973. t.exports = function (e, t, r, n) {
  35974. var i = o,
  35975. s = n + r;
  35976. e ^= -1;
  35977. for (var a = n; a < s; a++) e = e >>> 8 ^ i[255 & (e ^ t[a])];
  35978. return -1 ^ e;
  35979. };
  35980. }, {}],
  35981. 46: [function (e, t, r) {
  35982. "use strict";
  35983. var h,
  35984. c = e("../utils/common"),
  35985. u = e("./trees"),
  35986. d = e("./adler32"),
  35987. p = e("./crc32"),
  35988. n = e("./messages"),
  35989. l = 0,
  35990. f = 4,
  35991. m = 0,
  35992. _ = -2,
  35993. g = -1,
  35994. b = 4,
  35995. i = 2,
  35996. v = 8,
  35997. y = 9,
  35998. s = 286,
  35999. a = 30,
  36000. o = 19,
  36001. w = 2 * s + 1,
  36002. k = 15,
  36003. x = 3,
  36004. S = 258,
  36005. z = S + x + 1,
  36006. C = 42,
  36007. E = 113,
  36008. A = 1,
  36009. I = 2,
  36010. O = 3,
  36011. B = 4;
  36012. function R(e, t) {
  36013. return e.msg = n[t], t;
  36014. }
  36015. function T(e) {
  36016. return (e << 1) - (4 < e ? 9 : 0);
  36017. }
  36018. function D(e) {
  36019. for (var t = e.length; 0 <= --t;) e[t] = 0;
  36020. }
  36021. function F(e) {
  36022. var t = e.state,
  36023. r = t.pending;
  36024. r > e.avail_out && (r = e.avail_out), 0 !== r && (c.arraySet(e.output, t.pending_buf, t.pending_out, r, e.next_out), e.next_out += r, t.pending_out += r, e.total_out += r, e.avail_out -= r, t.pending -= r, 0 === t.pending && (t.pending_out = 0));
  36025. }
  36026. function N(e, t) {
  36027. u._tr_flush_block(e, 0 <= e.block_start ? e.block_start : -1, e.strstart - e.block_start, t), e.block_start = e.strstart, F(e.strm);
  36028. }
  36029. function U(e, t) {
  36030. e.pending_buf[e.pending++] = t;
  36031. }
  36032. function P(e, t) {
  36033. e.pending_buf[e.pending++] = t >>> 8 & 255, e.pending_buf[e.pending++] = 255 & t;
  36034. }
  36035. function L(e, t) {
  36036. var r,
  36037. n,
  36038. i = e.max_chain_length,
  36039. s = e.strstart,
  36040. a = e.prev_length,
  36041. o = e.nice_match,
  36042. h = e.strstart > e.w_size - z ? e.strstart - (e.w_size - z) : 0,
  36043. u = e.window,
  36044. l = e.w_mask,
  36045. f = e.prev,
  36046. c = e.strstart + S,
  36047. d = u[s + a - 1],
  36048. p = u[s + a];
  36049. e.prev_length >= e.good_match && (i >>= 2), o > e.lookahead && (o = e.lookahead);
  36050. do {
  36051. if (u[(r = t) + a] === p && u[r + a - 1] === d && u[r] === u[s] && u[++r] === u[s + 1]) {
  36052. s += 2, r++;
  36053. do {} while (u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && s < c);
  36054. if (n = S - (c - s), s = c - S, a < n) {
  36055. if (e.match_start = t, o <= (a = n)) break;
  36056. d = u[s + a - 1], p = u[s + a];
  36057. }
  36058. }
  36059. } while ((t = f[t & l]) > h && 0 != --i);
  36060. return a <= e.lookahead ? a : e.lookahead;
  36061. }
  36062. function j(e) {
  36063. var t,
  36064. r,
  36065. n,
  36066. i,
  36067. s,
  36068. a,
  36069. o,
  36070. h,
  36071. u,
  36072. l,
  36073. f = e.w_size;
  36074. do {
  36075. if (i = e.window_size - e.lookahead - e.strstart, e.strstart >= f + (f - z)) {
  36076. for (c.arraySet(e.window, e.window, f, f, 0), e.match_start -= f, e.strstart -= f, e.block_start -= f, t = r = e.hash_size; n = e.head[--t], e.head[t] = f <= n ? n - f : 0, --r;);
  36077. for (t = r = f; n = e.prev[--t], e.prev[t] = f <= n ? n - f : 0, --r;);
  36078. i += f;
  36079. }
  36080. if (0 === e.strm.avail_in) break;
  36081. if (a = e.strm, o = e.window, h = e.strstart + e.lookahead, u = i, l = void 0, l = a.avail_in, u < l && (l = u), r = 0 === l ? 0 : (a.avail_in -= l, c.arraySet(o, a.input, a.next_in, l, h), 1 === a.state.wrap ? a.adler = d(a.adler, o, l, h) : 2 === a.state.wrap && (a.adler = p(a.adler, o, l, h)), a.next_in += l, a.total_in += l, l), e.lookahead += r, e.lookahead + e.insert >= x) for (s = e.strstart - e.insert, e.ins_h = e.window[s], e.ins_h = (e.ins_h << e.hash_shift ^ e.window[s + 1]) & e.hash_mask; e.insert && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[s + x - 1]) & e.hash_mask, e.prev[s & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = s, s++, e.insert--, !(e.lookahead + e.insert < x)););
  36082. } while (e.lookahead < z && 0 !== e.strm.avail_in);
  36083. }
  36084. function Z(e, t) {
  36085. for (var r, n;;) {
  36086. if (e.lookahead < z) {
  36087. if (j(e), e.lookahead < z && t === l) return A;
  36088. if (0 === e.lookahead) break;
  36089. }
  36090. if (r = 0, e.lookahead >= x && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart), 0 !== r && e.strstart - r <= e.w_size - z && (e.match_length = L(e, r)), e.match_length >= x) {
  36091. if (n = u._tr_tally(e, e.strstart - e.match_start, e.match_length - x), e.lookahead -= e.match_length, e.match_length <= e.max_lazy_match && e.lookahead >= x) {
  36092. for (e.match_length--; e.strstart++, e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart, 0 != --e.match_length;);
  36093. e.strstart++;
  36094. } else e.strstart += e.match_length, e.match_length = 0, e.ins_h = e.window[e.strstart], e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + 1]) & e.hash_mask;
  36095. } else n = u._tr_tally(e, 0, e.window[e.strstart]), e.lookahead--, e.strstart++;
  36096. if (n && (N(e, !1), 0 === e.strm.avail_out)) return A;
  36097. }
  36098. return e.insert = e.strstart < x - 1 ? e.strstart : x - 1, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I;
  36099. }
  36100. function W(e, t) {
  36101. for (var r, n, i;;) {
  36102. if (e.lookahead < z) {
  36103. if (j(e), e.lookahead < z && t === l) return A;
  36104. if (0 === e.lookahead) break;
  36105. }
  36106. if (r = 0, e.lookahead >= x && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart), e.prev_length = e.match_length, e.prev_match = e.match_start, e.match_length = x - 1, 0 !== r && e.prev_length < e.max_lazy_match && e.strstart - r <= e.w_size - z && (e.match_length = L(e, r), e.match_length <= 5 && (1 === e.strategy || e.match_length === x && 4096 < e.strstart - e.match_start) && (e.match_length = x - 1)), e.prev_length >= x && e.match_length <= e.prev_length) {
  36107. for (i = e.strstart + e.lookahead - x, n = u._tr_tally(e, e.strstart - 1 - e.prev_match, e.prev_length - x), e.lookahead -= e.prev_length - 1, e.prev_length -= 2; ++e.strstart <= i && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart), 0 != --e.prev_length;);
  36108. if (e.match_available = 0, e.match_length = x - 1, e.strstart++, n && (N(e, !1), 0 === e.strm.avail_out)) return A;
  36109. } else if (e.match_available) {
  36110. if ((n = u._tr_tally(e, 0, e.window[e.strstart - 1])) && N(e, !1), e.strstart++, e.lookahead--, 0 === e.strm.avail_out) return A;
  36111. } else e.match_available = 1, e.strstart++, e.lookahead--;
  36112. }
  36113. return e.match_available && (n = u._tr_tally(e, 0, e.window[e.strstart - 1]), e.match_available = 0), e.insert = e.strstart < x - 1 ? e.strstart : x - 1, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I;
  36114. }
  36115. function M(e, t, r, n, i) {
  36116. this.good_length = e, this.max_lazy = t, this.nice_length = r, this.max_chain = n, this.func = i;
  36117. }
  36118. function H() {
  36119. this.strm = null, this.status = 0, this.pending_buf = null, this.pending_buf_size = 0, this.pending_out = 0, this.pending = 0, this.wrap = 0, this.gzhead = null, this.gzindex = 0, this.method = v, this.last_flush = -1, this.w_size = 0, this.w_bits = 0, this.w_mask = 0, this.window = null, this.window_size = 0, this.prev = null, this.head = null, this.ins_h = 0, this.hash_size = 0, this.hash_bits = 0, this.hash_mask = 0, this.hash_shift = 0, this.block_start = 0, this.match_length = 0, this.prev_match = 0, this.match_available = 0, this.strstart = 0, this.match_start = 0, this.lookahead = 0, this.prev_length = 0, this.max_chain_length = 0, this.max_lazy_match = 0, this.level = 0, this.strategy = 0, this.good_match = 0, this.nice_match = 0, this.dyn_ltree = new c.Buf16(2 * w), this.dyn_dtree = new c.Buf16(2 * (2 * a + 1)), this.bl_tree = new c.Buf16(2 * (2 * o + 1)), D(this.dyn_ltree), D(this.dyn_dtree), D(this.bl_tree), this.l_desc = null, this.d_desc = null, this.bl_desc = null, this.bl_count = new c.Buf16(k + 1), this.heap = new c.Buf16(2 * s + 1), D(this.heap), this.heap_len = 0, this.heap_max = 0, this.depth = new c.Buf16(2 * s + 1), D(this.depth), this.l_buf = 0, this.lit_bufsize = 0, this.last_lit = 0, this.d_buf = 0, this.opt_len = 0, this.static_len = 0, this.matches = 0, this.insert = 0, this.bi_buf = 0, this.bi_valid = 0;
  36120. }
  36121. function G(e) {
  36122. var t;
  36123. return e && e.state ? (e.total_in = e.total_out = 0, e.data_type = i, (t = e.state).pending = 0, t.pending_out = 0, t.wrap < 0 && (t.wrap = -t.wrap), t.status = t.wrap ? C : E, e.adler = 2 === t.wrap ? 0 : 1, t.last_flush = l, u._tr_init(t), m) : R(e, _);
  36124. }
  36125. function K(e) {
  36126. var t = G(e);
  36127. return t === m && function (e) {
  36128. e.window_size = 2 * e.w_size, D(e.head), e.max_lazy_match = h[e.level].max_lazy, e.good_match = h[e.level].good_length, e.nice_match = h[e.level].nice_length, e.max_chain_length = h[e.level].max_chain, e.strstart = 0, e.block_start = 0, e.lookahead = 0, e.insert = 0, e.match_length = e.prev_length = x - 1, e.match_available = 0, e.ins_h = 0;
  36129. }(e.state), t;
  36130. }
  36131. function Y(e, t, r, n, i, s) {
  36132. if (!e) return _;
  36133. var a = 1;
  36134. if (t === g && (t = 6), n < 0 ? (a = 0, n = -n) : 15 < n && (a = 2, n -= 16), i < 1 || y < i || r !== v || n < 8 || 15 < n || t < 0 || 9 < t || s < 0 || b < s) return R(e, _);
  36135. 8 === n && (n = 9);
  36136. var o = new H();
  36137. return (e.state = o).strm = e, o.wrap = a, o.gzhead = null, o.w_bits = n, o.w_size = 1 << o.w_bits, o.w_mask = o.w_size - 1, o.hash_bits = i + 7, o.hash_size = 1 << o.hash_bits, o.hash_mask = o.hash_size - 1, o.hash_shift = ~~((o.hash_bits + x - 1) / x), o.window = new c.Buf8(2 * o.w_size), o.head = new c.Buf16(o.hash_size), o.prev = new c.Buf16(o.w_size), o.lit_bufsize = 1 << i + 6, o.pending_buf_size = 4 * o.lit_bufsize, o.pending_buf = new c.Buf8(o.pending_buf_size), o.d_buf = 1 * o.lit_bufsize, o.l_buf = 3 * o.lit_bufsize, o.level = t, o.strategy = s, o.method = r, K(e);
  36138. }
  36139. h = [new M(0, 0, 0, 0, function (e, t) {
  36140. var r = 65535;
  36141. for (r > e.pending_buf_size - 5 && (r = e.pending_buf_size - 5);;) {
  36142. if (e.lookahead <= 1) {
  36143. if (j(e), 0 === e.lookahead && t === l) return A;
  36144. if (0 === e.lookahead) break;
  36145. }
  36146. e.strstart += e.lookahead, e.lookahead = 0;
  36147. var n = e.block_start + r;
  36148. if ((0 === e.strstart || e.strstart >= n) && (e.lookahead = e.strstart - n, e.strstart = n, N(e, !1), 0 === e.strm.avail_out)) return A;
  36149. if (e.strstart - e.block_start >= e.w_size - z && (N(e, !1), 0 === e.strm.avail_out)) return A;
  36150. }
  36151. return e.insert = 0, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : (e.strstart > e.block_start && (N(e, !1), e.strm.avail_out), A);
  36152. }), new M(4, 4, 8, 4, Z), new M(4, 5, 16, 8, Z), new M(4, 6, 32, 32, Z), new M(4, 4, 16, 16, W), new M(8, 16, 32, 32, W), new M(8, 16, 128, 128, W), new M(8, 32, 128, 256, W), new M(32, 128, 258, 1024, W), new M(32, 258, 258, 4096, W)], r.deflateInit = function (e, t) {
  36153. return Y(e, t, v, 15, 8, 0);
  36154. }, r.deflateInit2 = Y, r.deflateReset = K, r.deflateResetKeep = G, r.deflateSetHeader = function (e, t) {
  36155. return e && e.state ? 2 !== e.state.wrap ? _ : (e.state.gzhead = t, m) : _;
  36156. }, r.deflate = function (e, t) {
  36157. var r, n, i, s;
  36158. if (!e || !e.state || 5 < t || t < 0) return e ? R(e, _) : _;
  36159. if (n = e.state, !e.output || !e.input && 0 !== e.avail_in || 666 === n.status && t !== f) return R(e, 0 === e.avail_out ? -5 : _);
  36160. if (n.strm = e, r = n.last_flush, n.last_flush = t, n.status === C) if (2 === n.wrap) e.adler = 0, U(n, 31), U(n, 139), U(n, 8), n.gzhead ? (U(n, (n.gzhead.text ? 1 : 0) + (n.gzhead.hcrc ? 2 : 0) + (n.gzhead.extra ? 4 : 0) + (n.gzhead.name ? 8 : 0) + (n.gzhead.comment ? 16 : 0)), U(n, 255 & n.gzhead.time), U(n, n.gzhead.time >> 8 & 255), U(n, n.gzhead.time >> 16 & 255), U(n, n.gzhead.time >> 24 & 255), U(n, 9 === n.level ? 2 : 2 <= n.strategy || n.level < 2 ? 4 : 0), U(n, 255 & n.gzhead.os), n.gzhead.extra && n.gzhead.extra.length && (U(n, 255 & n.gzhead.extra.length), U(n, n.gzhead.extra.length >> 8 & 255)), n.gzhead.hcrc && (e.adler = p(e.adler, n.pending_buf, n.pending, 0)), n.gzindex = 0, n.status = 69) : (U(n, 0), U(n, 0), U(n, 0), U(n, 0), U(n, 0), U(n, 9 === n.level ? 2 : 2 <= n.strategy || n.level < 2 ? 4 : 0), U(n, 3), n.status = E);else {
  36161. var a = v + (n.w_bits - 8 << 4) << 8;
  36162. a |= (2 <= n.strategy || n.level < 2 ? 0 : n.level < 6 ? 1 : 6 === n.level ? 2 : 3) << 6, 0 !== n.strstart && (a |= 32), a += 31 - a % 31, n.status = E, P(n, a), 0 !== n.strstart && (P(n, e.adler >>> 16), P(n, 65535 & e.adler)), e.adler = 1;
  36163. }
  36164. if (69 === n.status) if (n.gzhead.extra) {
  36165. for (i = n.pending; n.gzindex < (65535 & n.gzhead.extra.length) && (n.pending !== n.pending_buf_size || (n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), F(e), i = n.pending, n.pending !== n.pending_buf_size));) U(n, 255 & n.gzhead.extra[n.gzindex]), n.gzindex++;
  36166. n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), n.gzindex === n.gzhead.extra.length && (n.gzindex = 0, n.status = 73);
  36167. } else n.status = 73;
  36168. if (73 === n.status) if (n.gzhead.name) {
  36169. i = n.pending;
  36170. do {
  36171. if (n.pending === n.pending_buf_size && (n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), F(e), i = n.pending, n.pending === n.pending_buf_size)) {
  36172. s = 1;
  36173. break;
  36174. }
  36175. s = n.gzindex < n.gzhead.name.length ? 255 & n.gzhead.name.charCodeAt(n.gzindex++) : 0, U(n, s);
  36176. } while (0 !== s);
  36177. n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), 0 === s && (n.gzindex = 0, n.status = 91);
  36178. } else n.status = 91;
  36179. if (91 === n.status) if (n.gzhead.comment) {
  36180. i = n.pending;
  36181. do {
  36182. if (n.pending === n.pending_buf_size && (n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), F(e), i = n.pending, n.pending === n.pending_buf_size)) {
  36183. s = 1;
  36184. break;
  36185. }
  36186. s = n.gzindex < n.gzhead.comment.length ? 255 & n.gzhead.comment.charCodeAt(n.gzindex++) : 0, U(n, s);
  36187. } while (0 !== s);
  36188. n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), 0 === s && (n.status = 103);
  36189. } else n.status = 103;
  36190. if (103 === n.status && (n.gzhead.hcrc ? (n.pending + 2 > n.pending_buf_size && F(e), n.pending + 2 <= n.pending_buf_size && (U(n, 255 & e.adler), U(n, e.adler >> 8 & 255), e.adler = 0, n.status = E)) : n.status = E), 0 !== n.pending) {
  36191. if (F(e), 0 === e.avail_out) return n.last_flush = -1, m;
  36192. } else if (0 === e.avail_in && T(t) <= T(r) && t !== f) return R(e, -5);
  36193. if (666 === n.status && 0 !== e.avail_in) return R(e, -5);
  36194. if (0 !== e.avail_in || 0 !== n.lookahead || t !== l && 666 !== n.status) {
  36195. var o = 2 === n.strategy ? function (e, t) {
  36196. for (var r;;) {
  36197. if (0 === e.lookahead && (j(e), 0 === e.lookahead)) {
  36198. if (t === l) return A;
  36199. break;
  36200. }
  36201. if (e.match_length = 0, r = u._tr_tally(e, 0, e.window[e.strstart]), e.lookahead--, e.strstart++, r && (N(e, !1), 0 === e.strm.avail_out)) return A;
  36202. }
  36203. return e.insert = 0, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I;
  36204. }(n, t) : 3 === n.strategy ? function (e, t) {
  36205. for (var r, n, i, s, a = e.window;;) {
  36206. if (e.lookahead <= S) {
  36207. if (j(e), e.lookahead <= S && t === l) return A;
  36208. if (0 === e.lookahead) break;
  36209. }
  36210. if (e.match_length = 0, e.lookahead >= x && 0 < e.strstart && (n = a[i = e.strstart - 1]) === a[++i] && n === a[++i] && n === a[++i]) {
  36211. s = e.strstart + S;
  36212. do {} while (n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && i < s);
  36213. e.match_length = S - (s - i), e.match_length > e.lookahead && (e.match_length = e.lookahead);
  36214. }
  36215. if (e.match_length >= x ? (r = u._tr_tally(e, 1, e.match_length - x), e.lookahead -= e.match_length, e.strstart += e.match_length, e.match_length = 0) : (r = u._tr_tally(e, 0, e.window[e.strstart]), e.lookahead--, e.strstart++), r && (N(e, !1), 0 === e.strm.avail_out)) return A;
  36216. }
  36217. return e.insert = 0, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I;
  36218. }(n, t) : h[n.level].func(n, t);
  36219. if (o !== O && o !== B || (n.status = 666), o === A || o === O) return 0 === e.avail_out && (n.last_flush = -1), m;
  36220. if (o === I && (1 === t ? u._tr_align(n) : 5 !== t && (u._tr_stored_block(n, 0, 0, !1), 3 === t && (D(n.head), 0 === n.lookahead && (n.strstart = 0, n.block_start = 0, n.insert = 0))), F(e), 0 === e.avail_out)) return n.last_flush = -1, m;
  36221. }
  36222. return t !== f ? m : n.wrap <= 0 ? 1 : (2 === n.wrap ? (U(n, 255 & e.adler), U(n, e.adler >> 8 & 255), U(n, e.adler >> 16 & 255), U(n, e.adler >> 24 & 255), U(n, 255 & e.total_in), U(n, e.total_in >> 8 & 255), U(n, e.total_in >> 16 & 255), U(n, e.total_in >> 24 & 255)) : (P(n, e.adler >>> 16), P(n, 65535 & e.adler)), F(e), 0 < n.wrap && (n.wrap = -n.wrap), 0 !== n.pending ? m : 1);
  36223. }, r.deflateEnd = function (e) {
  36224. var t;
  36225. return e && e.state ? (t = e.state.status) !== C && 69 !== t && 73 !== t && 91 !== t && 103 !== t && t !== E && 666 !== t ? R(e, _) : (e.state = null, t === E ? R(e, -3) : m) : _;
  36226. }, r.deflateSetDictionary = function (e, t) {
  36227. var r,
  36228. n,
  36229. i,
  36230. s,
  36231. a,
  36232. o,
  36233. h,
  36234. u,
  36235. l = t.length;
  36236. if (!e || !e.state) return _;
  36237. if (2 === (s = (r = e.state).wrap) || 1 === s && r.status !== C || r.lookahead) return _;
  36238. for (1 === s && (e.adler = d(e.adler, t, l, 0)), r.wrap = 0, l >= r.w_size && (0 === s && (D(r.head), r.strstart = 0, r.block_start = 0, r.insert = 0), u = new c.Buf8(r.w_size), c.arraySet(u, t, l - r.w_size, r.w_size, 0), t = u, l = r.w_size), a = e.avail_in, o = e.next_in, h = e.input, e.avail_in = l, e.next_in = 0, e.input = t, j(r); r.lookahead >= x;) {
  36239. for (n = r.strstart, i = r.lookahead - (x - 1); r.ins_h = (r.ins_h << r.hash_shift ^ r.window[n + x - 1]) & r.hash_mask, r.prev[n & r.w_mask] = r.head[r.ins_h], r.head[r.ins_h] = n, n++, --i;);
  36240. r.strstart = n, r.lookahead = x - 1, j(r);
  36241. }
  36242. return r.strstart += r.lookahead, r.block_start = r.strstart, r.insert = r.lookahead, r.lookahead = 0, r.match_length = r.prev_length = x - 1, r.match_available = 0, e.next_in = o, e.input = h, e.avail_in = a, r.wrap = s, m;
  36243. }, r.deflateInfo = "pako deflate (from Nodeca project)";
  36244. }, {
  36245. "../utils/common": 41,
  36246. "./adler32": 43,
  36247. "./crc32": 45,
  36248. "./messages": 51,
  36249. "./trees": 52
  36250. }],
  36251. 47: [function (e, t, r) {
  36252. "use strict";
  36253. t.exports = function () {
  36254. this.text = 0, this.time = 0, this.xflags = 0, this.os = 0, this.extra = null, this.extra_len = 0, this.name = "", this.comment = "", this.hcrc = 0, this.done = !1;
  36255. };
  36256. }, {}],
  36257. 48: [function (e, t, r) {
  36258. "use strict";
  36259. t.exports = function (e, t) {
  36260. var r, n, i, s, a, o, h, u, l, f, c, d, p, m, _, g, b, v, y, w, k, x, S, z, C;
  36261. r = e.state, n = e.next_in, z = e.input, i = n + (e.avail_in - 5), s = e.next_out, C = e.output, a = s - (t - e.avail_out), o = s + (e.avail_out - 257), h = r.dmax, u = r.wsize, l = r.whave, f = r.wnext, c = r.window, d = r.hold, p = r.bits, m = r.lencode, _ = r.distcode, g = (1 << r.lenbits) - 1, b = (1 << r.distbits) - 1;
  36262. e: do {
  36263. p < 15 && (d += z[n++] << p, p += 8, d += z[n++] << p, p += 8), v = m[d & g];
  36264. t: for (;;) {
  36265. if (d >>>= y = v >>> 24, p -= y, 0 === (y = v >>> 16 & 255)) C[s++] = 65535 & v;else {
  36266. if (!(16 & y)) {
  36267. if (0 == (64 & y)) {
  36268. v = m[(65535 & v) + (d & (1 << y) - 1)];
  36269. continue t;
  36270. }
  36271. if (32 & y) {
  36272. r.mode = 12;
  36273. break e;
  36274. }
  36275. e.msg = "invalid literal/length code", r.mode = 30;
  36276. break e;
  36277. }
  36278. w = 65535 & v, (y &= 15) && (p < y && (d += z[n++] << p, p += 8), w += d & (1 << y) - 1, d >>>= y, p -= y), p < 15 && (d += z[n++] << p, p += 8, d += z[n++] << p, p += 8), v = _[d & b];
  36279. r: for (;;) {
  36280. if (d >>>= y = v >>> 24, p -= y, !(16 & (y = v >>> 16 & 255))) {
  36281. if (0 == (64 & y)) {
  36282. v = _[(65535 & v) + (d & (1 << y) - 1)];
  36283. continue r;
  36284. }
  36285. e.msg = "invalid distance code", r.mode = 30;
  36286. break e;
  36287. }
  36288. if (k = 65535 & v, p < (y &= 15) && (d += z[n++] << p, (p += 8) < y && (d += z[n++] << p, p += 8)), h < (k += d & (1 << y) - 1)) {
  36289. e.msg = "invalid distance too far back", r.mode = 30;
  36290. break e;
  36291. }
  36292. if (d >>>= y, p -= y, (y = s - a) < k) {
  36293. if (l < (y = k - y) && r.sane) {
  36294. e.msg = "invalid distance too far back", r.mode = 30;
  36295. break e;
  36296. }
  36297. if (S = c, (x = 0) === f) {
  36298. if (x += u - y, y < w) {
  36299. for (w -= y; C[s++] = c[x++], --y;);
  36300. x = s - k, S = C;
  36301. }
  36302. } else if (f < y) {
  36303. if (x += u + f - y, (y -= f) < w) {
  36304. for (w -= y; C[s++] = c[x++], --y;);
  36305. if (x = 0, f < w) {
  36306. for (w -= y = f; C[s++] = c[x++], --y;);
  36307. x = s - k, S = C;
  36308. }
  36309. }
  36310. } else if (x += f - y, y < w) {
  36311. for (w -= y; C[s++] = c[x++], --y;);
  36312. x = s - k, S = C;
  36313. }
  36314. for (; 2 < w;) C[s++] = S[x++], C[s++] = S[x++], C[s++] = S[x++], w -= 3;
  36315. w && (C[s++] = S[x++], 1 < w && (C[s++] = S[x++]));
  36316. } else {
  36317. for (x = s - k; C[s++] = C[x++], C[s++] = C[x++], C[s++] = C[x++], 2 < (w -= 3););
  36318. w && (C[s++] = C[x++], 1 < w && (C[s++] = C[x++]));
  36319. }
  36320. break;
  36321. }
  36322. }
  36323. break;
  36324. }
  36325. } while (n < i && s < o);
  36326. n -= w = p >> 3, d &= (1 << (p -= w << 3)) - 1, e.next_in = n, e.next_out = s, e.avail_in = n < i ? i - n + 5 : 5 - (n - i), e.avail_out = s < o ? o - s + 257 : 257 - (s - o), r.hold = d, r.bits = p;
  36327. };
  36328. }, {}],
  36329. 49: [function (e, t, r) {
  36330. "use strict";
  36331. var I = e("../utils/common"),
  36332. O = e("./adler32"),
  36333. B = e("./crc32"),
  36334. R = e("./inffast"),
  36335. T = e("./inftrees"),
  36336. D = 1,
  36337. F = 2,
  36338. N = 0,
  36339. U = -2,
  36340. P = 1,
  36341. n = 852,
  36342. i = 592;
  36343. function L(e) {
  36344. return (e >>> 24 & 255) + (e >>> 8 & 65280) + ((65280 & e) << 8) + ((255 & e) << 24);
  36345. }
  36346. function s() {
  36347. this.mode = 0, this.last = !1, this.wrap = 0, this.havedict = !1, this.flags = 0, this.dmax = 0, this.check = 0, this.total = 0, this.head = null, this.wbits = 0, this.wsize = 0, this.whave = 0, this.wnext = 0, this.window = null, this.hold = 0, this.bits = 0, this.length = 0, this.offset = 0, this.extra = 0, this.lencode = null, this.distcode = null, this.lenbits = 0, this.distbits = 0, this.ncode = 0, this.nlen = 0, this.ndist = 0, this.have = 0, this.next = null, this.lens = new I.Buf16(320), this.work = new I.Buf16(288), this.lendyn = null, this.distdyn = null, this.sane = 0, this.back = 0, this.was = 0;
  36348. }
  36349. function a(e) {
  36350. var t;
  36351. return e && e.state ? (t = e.state, e.total_in = e.total_out = t.total = 0, e.msg = "", t.wrap && (e.adler = 1 & t.wrap), t.mode = P, t.last = 0, t.havedict = 0, t.dmax = 32768, t.head = null, t.hold = 0, t.bits = 0, t.lencode = t.lendyn = new I.Buf32(n), t.distcode = t.distdyn = new I.Buf32(i), t.sane = 1, t.back = -1, N) : U;
  36352. }
  36353. function o(e) {
  36354. var t;
  36355. return e && e.state ? ((t = e.state).wsize = 0, t.whave = 0, t.wnext = 0, a(e)) : U;
  36356. }
  36357. function h(e, t) {
  36358. var r, n;
  36359. return e && e.state ? (n = e.state, t < 0 ? (r = 0, t = -t) : (r = 1 + (t >> 4), t < 48 && (t &= 15)), t && (t < 8 || 15 < t) ? U : (null !== n.window && n.wbits !== t && (n.window = null), n.wrap = r, n.wbits = t, o(e))) : U;
  36360. }
  36361. function u(e, t) {
  36362. var r, n;
  36363. return e ? (n = new s(), (e.state = n).window = null, (r = h(e, t)) !== N && (e.state = null), r) : U;
  36364. }
  36365. var l,
  36366. f,
  36367. c = !0;
  36368. function j(e) {
  36369. if (c) {
  36370. var t;
  36371. for (l = new I.Buf32(512), f = new I.Buf32(32), t = 0; t < 144;) e.lens[t++] = 8;
  36372. for (; t < 256;) e.lens[t++] = 9;
  36373. for (; t < 280;) e.lens[t++] = 7;
  36374. for (; t < 288;) e.lens[t++] = 8;
  36375. for (T(D, e.lens, 0, 288, l, 0, e.work, {
  36376. bits: 9
  36377. }), t = 0; t < 32;) e.lens[t++] = 5;
  36378. T(F, e.lens, 0, 32, f, 0, e.work, {
  36379. bits: 5
  36380. }), c = !1;
  36381. }
  36382. e.lencode = l, e.lenbits = 9, e.distcode = f, e.distbits = 5;
  36383. }
  36384. function Z(e, t, r, n) {
  36385. var i,
  36386. s = e.state;
  36387. return null === s.window && (s.wsize = 1 << s.wbits, s.wnext = 0, s.whave = 0, s.window = new I.Buf8(s.wsize)), n >= s.wsize ? (I.arraySet(s.window, t, r - s.wsize, s.wsize, 0), s.wnext = 0, s.whave = s.wsize) : (n < (i = s.wsize - s.wnext) && (i = n), I.arraySet(s.window, t, r - n, i, s.wnext), (n -= i) ? (I.arraySet(s.window, t, r - n, n, 0), s.wnext = n, s.whave = s.wsize) : (s.wnext += i, s.wnext === s.wsize && (s.wnext = 0), s.whave < s.wsize && (s.whave += i))), 0;
  36388. }
  36389. r.inflateReset = o, r.inflateReset2 = h, r.inflateResetKeep = a, r.inflateInit = function (e) {
  36390. return u(e, 15);
  36391. }, r.inflateInit2 = u, r.inflate = function (e, t) {
  36392. var r,
  36393. n,
  36394. i,
  36395. s,
  36396. a,
  36397. o,
  36398. h,
  36399. u,
  36400. l,
  36401. f,
  36402. c,
  36403. d,
  36404. p,
  36405. m,
  36406. _,
  36407. g,
  36408. b,
  36409. v,
  36410. y,
  36411. w,
  36412. k,
  36413. x,
  36414. S,
  36415. z,
  36416. C = 0,
  36417. E = new I.Buf8(4),
  36418. A = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  36419. if (!e || !e.state || !e.output || !e.input && 0 !== e.avail_in) return U;
  36420. 12 === (r = e.state).mode && (r.mode = 13), a = e.next_out, i = e.output, h = e.avail_out, s = e.next_in, n = e.input, o = e.avail_in, u = r.hold, l = r.bits, f = o, c = h, x = N;
  36421. e: for (;;) switch (r.mode) {
  36422. case P:
  36423. if (0 === r.wrap) {
  36424. r.mode = 13;
  36425. break;
  36426. }
  36427. for (; l < 16;) {
  36428. if (0 === o) break e;
  36429. o--, u += n[s++] << l, l += 8;
  36430. }
  36431. if (2 & r.wrap && 35615 === u) {
  36432. E[r.check = 0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0), l = u = 0, r.mode = 2;
  36433. break;
  36434. }
  36435. if (r.flags = 0, r.head && (r.head.done = !1), !(1 & r.wrap) || (((255 & u) << 8) + (u >> 8)) % 31) {
  36436. e.msg = "incorrect header check", r.mode = 30;
  36437. break;
  36438. }
  36439. if (8 != (15 & u)) {
  36440. e.msg = "unknown compression method", r.mode = 30;
  36441. break;
  36442. }
  36443. if (l -= 4, k = 8 + (15 & (u >>>= 4)), 0 === r.wbits) r.wbits = k;else if (k > r.wbits) {
  36444. e.msg = "invalid window size", r.mode = 30;
  36445. break;
  36446. }
  36447. r.dmax = 1 << k, e.adler = r.check = 1, r.mode = 512 & u ? 10 : 12, l = u = 0;
  36448. break;
  36449. case 2:
  36450. for (; l < 16;) {
  36451. if (0 === o) break e;
  36452. o--, u += n[s++] << l, l += 8;
  36453. }
  36454. if (r.flags = u, 8 != (255 & r.flags)) {
  36455. e.msg = "unknown compression method", r.mode = 30;
  36456. break;
  36457. }
  36458. if (57344 & r.flags) {
  36459. e.msg = "unknown header flags set", r.mode = 30;
  36460. break;
  36461. }
  36462. r.head && (r.head.text = u >> 8 & 1), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0)), l = u = 0, r.mode = 3;
  36463. case 3:
  36464. for (; l < 32;) {
  36465. if (0 === o) break e;
  36466. o--, u += n[s++] << l, l += 8;
  36467. }
  36468. r.head && (r.head.time = u), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, E[2] = u >>> 16 & 255, E[3] = u >>> 24 & 255, r.check = B(r.check, E, 4, 0)), l = u = 0, r.mode = 4;
  36469. case 4:
  36470. for (; l < 16;) {
  36471. if (0 === o) break e;
  36472. o--, u += n[s++] << l, l += 8;
  36473. }
  36474. r.head && (r.head.xflags = 255 & u, r.head.os = u >> 8), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0)), l = u = 0, r.mode = 5;
  36475. case 5:
  36476. if (1024 & r.flags) {
  36477. for (; l < 16;) {
  36478. if (0 === o) break e;
  36479. o--, u += n[s++] << l, l += 8;
  36480. }
  36481. r.length = u, r.head && (r.head.extra_len = u), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0)), l = u = 0;
  36482. } else r.head && (r.head.extra = null);
  36483. r.mode = 6;
  36484. case 6:
  36485. if (1024 & r.flags && (o < (d = r.length) && (d = o), d && (r.head && (k = r.head.extra_len - r.length, r.head.extra || (r.head.extra = new Array(r.head.extra_len)), I.arraySet(r.head.extra, n, s, d, k)), 512 & r.flags && (r.check = B(r.check, n, d, s)), o -= d, s += d, r.length -= d), r.length)) break e;
  36486. r.length = 0, r.mode = 7;
  36487. case 7:
  36488. if (2048 & r.flags) {
  36489. if (0 === o) break e;
  36490. for (d = 0; k = n[s + d++], r.head && k && r.length < 65536 && (r.head.name += String.fromCharCode(k)), k && d < o;);
  36491. if (512 & r.flags && (r.check = B(r.check, n, d, s)), o -= d, s += d, k) break e;
  36492. } else r.head && (r.head.name = null);
  36493. r.length = 0, r.mode = 8;
  36494. case 8:
  36495. if (4096 & r.flags) {
  36496. if (0 === o) break e;
  36497. for (d = 0; k = n[s + d++], r.head && k && r.length < 65536 && (r.head.comment += String.fromCharCode(k)), k && d < o;);
  36498. if (512 & r.flags && (r.check = B(r.check, n, d, s)), o -= d, s += d, k) break e;
  36499. } else r.head && (r.head.comment = null);
  36500. r.mode = 9;
  36501. case 9:
  36502. if (512 & r.flags) {
  36503. for (; l < 16;) {
  36504. if (0 === o) break e;
  36505. o--, u += n[s++] << l, l += 8;
  36506. }
  36507. if (u !== (65535 & r.check)) {
  36508. e.msg = "header crc mismatch", r.mode = 30;
  36509. break;
  36510. }
  36511. l = u = 0;
  36512. }
  36513. r.head && (r.head.hcrc = r.flags >> 9 & 1, r.head.done = !0), e.adler = r.check = 0, r.mode = 12;
  36514. break;
  36515. case 10:
  36516. for (; l < 32;) {
  36517. if (0 === o) break e;
  36518. o--, u += n[s++] << l, l += 8;
  36519. }
  36520. e.adler = r.check = L(u), l = u = 0, r.mode = 11;
  36521. case 11:
  36522. if (0 === r.havedict) return e.next_out = a, e.avail_out = h, e.next_in = s, e.avail_in = o, r.hold = u, r.bits = l, 2;
  36523. e.adler = r.check = 1, r.mode = 12;
  36524. case 12:
  36525. if (5 === t || 6 === t) break e;
  36526. case 13:
  36527. if (r.last) {
  36528. u >>>= 7 & l, l -= 7 & l, r.mode = 27;
  36529. break;
  36530. }
  36531. for (; l < 3;) {
  36532. if (0 === o) break e;
  36533. o--, u += n[s++] << l, l += 8;
  36534. }
  36535. switch (r.last = 1 & u, l -= 1, 3 & (u >>>= 1)) {
  36536. case 0:
  36537. r.mode = 14;
  36538. break;
  36539. case 1:
  36540. if (j(r), r.mode = 20, 6 !== t) break;
  36541. u >>>= 2, l -= 2;
  36542. break e;
  36543. case 2:
  36544. r.mode = 17;
  36545. break;
  36546. case 3:
  36547. e.msg = "invalid block type", r.mode = 30;
  36548. }
  36549. u >>>= 2, l -= 2;
  36550. break;
  36551. case 14:
  36552. for (u >>>= 7 & l, l -= 7 & l; l < 32;) {
  36553. if (0 === o) break e;
  36554. o--, u += n[s++] << l, l += 8;
  36555. }
  36556. if ((65535 & u) != (u >>> 16 ^ 65535)) {
  36557. e.msg = "invalid stored block lengths", r.mode = 30;
  36558. break;
  36559. }
  36560. if (r.length = 65535 & u, l = u = 0, r.mode = 15, 6 === t) break e;
  36561. case 15:
  36562. r.mode = 16;
  36563. case 16:
  36564. if (d = r.length) {
  36565. if (o < d && (d = o), h < d && (d = h), 0 === d) break e;
  36566. I.arraySet(i, n, s, d, a), o -= d, s += d, h -= d, a += d, r.length -= d;
  36567. break;
  36568. }
  36569. r.mode = 12;
  36570. break;
  36571. case 17:
  36572. for (; l < 14;) {
  36573. if (0 === o) break e;
  36574. o--, u += n[s++] << l, l += 8;
  36575. }
  36576. if (r.nlen = 257 + (31 & u), u >>>= 5, l -= 5, r.ndist = 1 + (31 & u), u >>>= 5, l -= 5, r.ncode = 4 + (15 & u), u >>>= 4, l -= 4, 286 < r.nlen || 30 < r.ndist) {
  36577. e.msg = "too many length or distance symbols", r.mode = 30;
  36578. break;
  36579. }
  36580. r.have = 0, r.mode = 18;
  36581. case 18:
  36582. for (; r.have < r.ncode;) {
  36583. for (; l < 3;) {
  36584. if (0 === o) break e;
  36585. o--, u += n[s++] << l, l += 8;
  36586. }
  36587. r.lens[A[r.have++]] = 7 & u, u >>>= 3, l -= 3;
  36588. }
  36589. for (; r.have < 19;) r.lens[A[r.have++]] = 0;
  36590. if (r.lencode = r.lendyn, r.lenbits = 7, S = {
  36591. bits: r.lenbits
  36592. }, x = T(0, r.lens, 0, 19, r.lencode, 0, r.work, S), r.lenbits = S.bits, x) {
  36593. e.msg = "invalid code lengths set", r.mode = 30;
  36594. break;
  36595. }
  36596. r.have = 0, r.mode = 19;
  36597. case 19:
  36598. for (; r.have < r.nlen + r.ndist;) {
  36599. for (; g = (C = r.lencode[u & (1 << r.lenbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l);) {
  36600. if (0 === o) break e;
  36601. o--, u += n[s++] << l, l += 8;
  36602. }
  36603. if (b < 16) u >>>= _, l -= _, r.lens[r.have++] = b;else {
  36604. if (16 === b) {
  36605. for (z = _ + 2; l < z;) {
  36606. if (0 === o) break e;
  36607. o--, u += n[s++] << l, l += 8;
  36608. }
  36609. if (u >>>= _, l -= _, 0 === r.have) {
  36610. e.msg = "invalid bit length repeat", r.mode = 30;
  36611. break;
  36612. }
  36613. k = r.lens[r.have - 1], d = 3 + (3 & u), u >>>= 2, l -= 2;
  36614. } else if (17 === b) {
  36615. for (z = _ + 3; l < z;) {
  36616. if (0 === o) break e;
  36617. o--, u += n[s++] << l, l += 8;
  36618. }
  36619. l -= _, k = 0, d = 3 + (7 & (u >>>= _)), u >>>= 3, l -= 3;
  36620. } else {
  36621. for (z = _ + 7; l < z;) {
  36622. if (0 === o) break e;
  36623. o--, u += n[s++] << l, l += 8;
  36624. }
  36625. l -= _, k = 0, d = 11 + (127 & (u >>>= _)), u >>>= 7, l -= 7;
  36626. }
  36627. if (r.have + d > r.nlen + r.ndist) {
  36628. e.msg = "invalid bit length repeat", r.mode = 30;
  36629. break;
  36630. }
  36631. for (; d--;) r.lens[r.have++] = k;
  36632. }
  36633. }
  36634. if (30 === r.mode) break;
  36635. if (0 === r.lens[256]) {
  36636. e.msg = "invalid code -- missing end-of-block", r.mode = 30;
  36637. break;
  36638. }
  36639. if (r.lenbits = 9, S = {
  36640. bits: r.lenbits
  36641. }, x = T(D, r.lens, 0, r.nlen, r.lencode, 0, r.work, S), r.lenbits = S.bits, x) {
  36642. e.msg = "invalid literal/lengths set", r.mode = 30;
  36643. break;
  36644. }
  36645. if (r.distbits = 6, r.distcode = r.distdyn, S = {
  36646. bits: r.distbits
  36647. }, x = T(F, r.lens, r.nlen, r.ndist, r.distcode, 0, r.work, S), r.distbits = S.bits, x) {
  36648. e.msg = "invalid distances set", r.mode = 30;
  36649. break;
  36650. }
  36651. if (r.mode = 20, 6 === t) break e;
  36652. case 20:
  36653. r.mode = 21;
  36654. case 21:
  36655. if (6 <= o && 258 <= h) {
  36656. e.next_out = a, e.avail_out = h, e.next_in = s, e.avail_in = o, r.hold = u, r.bits = l, R(e, c), a = e.next_out, i = e.output, h = e.avail_out, s = e.next_in, n = e.input, o = e.avail_in, u = r.hold, l = r.bits, 12 === r.mode && (r.back = -1);
  36657. break;
  36658. }
  36659. for (r.back = 0; g = (C = r.lencode[u & (1 << r.lenbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l);) {
  36660. if (0 === o) break e;
  36661. o--, u += n[s++] << l, l += 8;
  36662. }
  36663. if (g && 0 == (240 & g)) {
  36664. for (v = _, y = g, w = b; g = (C = r.lencode[w + ((u & (1 << v + y) - 1) >> v)]) >>> 16 & 255, b = 65535 & C, !(v + (_ = C >>> 24) <= l);) {
  36665. if (0 === o) break e;
  36666. o--, u += n[s++] << l, l += 8;
  36667. }
  36668. u >>>= v, l -= v, r.back += v;
  36669. }
  36670. if (u >>>= _, l -= _, r.back += _, r.length = b, 0 === g) {
  36671. r.mode = 26;
  36672. break;
  36673. }
  36674. if (32 & g) {
  36675. r.back = -1, r.mode = 12;
  36676. break;
  36677. }
  36678. if (64 & g) {
  36679. e.msg = "invalid literal/length code", r.mode = 30;
  36680. break;
  36681. }
  36682. r.extra = 15 & g, r.mode = 22;
  36683. case 22:
  36684. if (r.extra) {
  36685. for (z = r.extra; l < z;) {
  36686. if (0 === o) break e;
  36687. o--, u += n[s++] << l, l += 8;
  36688. }
  36689. r.length += u & (1 << r.extra) - 1, u >>>= r.extra, l -= r.extra, r.back += r.extra;
  36690. }
  36691. r.was = r.length, r.mode = 23;
  36692. case 23:
  36693. for (; g = (C = r.distcode[u & (1 << r.distbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l);) {
  36694. if (0 === o) break e;
  36695. o--, u += n[s++] << l, l += 8;
  36696. }
  36697. if (0 == (240 & g)) {
  36698. for (v = _, y = g, w = b; g = (C = r.distcode[w + ((u & (1 << v + y) - 1) >> v)]) >>> 16 & 255, b = 65535 & C, !(v + (_ = C >>> 24) <= l);) {
  36699. if (0 === o) break e;
  36700. o--, u += n[s++] << l, l += 8;
  36701. }
  36702. u >>>= v, l -= v, r.back += v;
  36703. }
  36704. if (u >>>= _, l -= _, r.back += _, 64 & g) {
  36705. e.msg = "invalid distance code", r.mode = 30;
  36706. break;
  36707. }
  36708. r.offset = b, r.extra = 15 & g, r.mode = 24;
  36709. case 24:
  36710. if (r.extra) {
  36711. for (z = r.extra; l < z;) {
  36712. if (0 === o) break e;
  36713. o--, u += n[s++] << l, l += 8;
  36714. }
  36715. r.offset += u & (1 << r.extra) - 1, u >>>= r.extra, l -= r.extra, r.back += r.extra;
  36716. }
  36717. if (r.offset > r.dmax) {
  36718. e.msg = "invalid distance too far back", r.mode = 30;
  36719. break;
  36720. }
  36721. r.mode = 25;
  36722. case 25:
  36723. if (0 === h) break e;
  36724. if (d = c - h, r.offset > d) {
  36725. if ((d = r.offset - d) > r.whave && r.sane) {
  36726. e.msg = "invalid distance too far back", r.mode = 30;
  36727. break;
  36728. }
  36729. p = d > r.wnext ? (d -= r.wnext, r.wsize - d) : r.wnext - d, d > r.length && (d = r.length), m = r.window;
  36730. } else m = i, p = a - r.offset, d = r.length;
  36731. for (h < d && (d = h), h -= d, r.length -= d; i[a++] = m[p++], --d;);
  36732. 0 === r.length && (r.mode = 21);
  36733. break;
  36734. case 26:
  36735. if (0 === h) break e;
  36736. i[a++] = r.length, h--, r.mode = 21;
  36737. break;
  36738. case 27:
  36739. if (r.wrap) {
  36740. for (; l < 32;) {
  36741. if (0 === o) break e;
  36742. o--, u |= n[s++] << l, l += 8;
  36743. }
  36744. if (c -= h, e.total_out += c, r.total += c, c && (e.adler = r.check = r.flags ? B(r.check, i, c, a - c) : O(r.check, i, c, a - c)), c = h, (r.flags ? u : L(u)) !== r.check) {
  36745. e.msg = "incorrect data check", r.mode = 30;
  36746. break;
  36747. }
  36748. l = u = 0;
  36749. }
  36750. r.mode = 28;
  36751. case 28:
  36752. if (r.wrap && r.flags) {
  36753. for (; l < 32;) {
  36754. if (0 === o) break e;
  36755. o--, u += n[s++] << l, l += 8;
  36756. }
  36757. if (u !== (4294967295 & r.total)) {
  36758. e.msg = "incorrect length check", r.mode = 30;
  36759. break;
  36760. }
  36761. l = u = 0;
  36762. }
  36763. r.mode = 29;
  36764. case 29:
  36765. x = 1;
  36766. break e;
  36767. case 30:
  36768. x = -3;
  36769. break e;
  36770. case 31:
  36771. return -4;
  36772. case 32:
  36773. default:
  36774. return U;
  36775. }
  36776. return e.next_out = a, e.avail_out = h, e.next_in = s, e.avail_in = o, r.hold = u, r.bits = l, (r.wsize || c !== e.avail_out && r.mode < 30 && (r.mode < 27 || 4 !== t)) && Z(e, e.output, e.next_out, c - e.avail_out) ? (r.mode = 31, -4) : (f -= e.avail_in, c -= e.avail_out, e.total_in += f, e.total_out += c, r.total += c, r.wrap && c && (e.adler = r.check = r.flags ? B(r.check, i, c, e.next_out - c) : O(r.check, i, c, e.next_out - c)), e.data_type = r.bits + (r.last ? 64 : 0) + (12 === r.mode ? 128 : 0) + (20 === r.mode || 15 === r.mode ? 256 : 0), (0 == f && 0 === c || 4 === t) && x === N && (x = -5), x);
  36777. }, r.inflateEnd = function (e) {
  36778. if (!e || !e.state) return U;
  36779. var t = e.state;
  36780. return t.window && (t.window = null), e.state = null, N;
  36781. }, r.inflateGetHeader = function (e, t) {
  36782. var r;
  36783. return e && e.state ? 0 == (2 & (r = e.state).wrap) ? U : ((r.head = t).done = !1, N) : U;
  36784. }, r.inflateSetDictionary = function (e, t) {
  36785. var r,
  36786. n = t.length;
  36787. return e && e.state ? 0 !== (r = e.state).wrap && 11 !== r.mode ? U : 11 === r.mode && O(1, t, n, 0) !== r.check ? -3 : Z(e, t, n, n) ? (r.mode = 31, -4) : (r.havedict = 1, N) : U;
  36788. }, r.inflateInfo = "pako inflate (from Nodeca project)";
  36789. }, {
  36790. "../utils/common": 41,
  36791. "./adler32": 43,
  36792. "./crc32": 45,
  36793. "./inffast": 48,
  36794. "./inftrees": 50
  36795. }],
  36796. 50: [function (e, t, r) {
  36797. "use strict";
  36798. var D = e("../utils/common"),
  36799. F = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0],
  36800. N = [16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78],
  36801. U = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0],
  36802. P = [16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64];
  36803. t.exports = function (e, t, r, n, i, s, a, o) {
  36804. var h,
  36805. u,
  36806. l,
  36807. f,
  36808. c,
  36809. d,
  36810. p,
  36811. m,
  36812. _,
  36813. g = o.bits,
  36814. b = 0,
  36815. v = 0,
  36816. y = 0,
  36817. w = 0,
  36818. k = 0,
  36819. x = 0,
  36820. S = 0,
  36821. z = 0,
  36822. C = 0,
  36823. E = 0,
  36824. A = null,
  36825. I = 0,
  36826. O = new D.Buf16(16),
  36827. B = new D.Buf16(16),
  36828. R = null,
  36829. T = 0;
  36830. for (b = 0; b <= 15; b++) O[b] = 0;
  36831. for (v = 0; v < n; v++) O[t[r + v]]++;
  36832. for (k = g, w = 15; 1 <= w && 0 === O[w]; w--);
  36833. if (w < k && (k = w), 0 === w) return i[s++] = 20971520, i[s++] = 20971520, o.bits = 1, 0;
  36834. for (y = 1; y < w && 0 === O[y]; y++);
  36835. for (k < y && (k = y), b = z = 1; b <= 15; b++) if (z <<= 1, (z -= O[b]) < 0) return -1;
  36836. if (0 < z && (0 === e || 1 !== w)) return -1;
  36837. for (B[1] = 0, b = 1; b < 15; b++) B[b + 1] = B[b] + O[b];
  36838. for (v = 0; v < n; v++) 0 !== t[r + v] && (a[B[t[r + v]]++] = v);
  36839. if (d = 0 === e ? (A = R = a, 19) : 1 === e ? (A = F, I -= 257, R = N, T -= 257, 256) : (A = U, R = P, -1), b = y, c = s, S = v = E = 0, l = -1, f = (C = 1 << (x = k)) - 1, 1 === e && 852 < C || 2 === e && 592 < C) return 1;
  36840. for (;;) {
  36841. for (p = b - S, _ = a[v] < d ? (m = 0, a[v]) : a[v] > d ? (m = R[T + a[v]], A[I + a[v]]) : (m = 96, 0), h = 1 << b - S, y = u = 1 << x; i[c + (E >> S) + (u -= h)] = p << 24 | m << 16 | _ | 0, 0 !== u;);
  36842. for (h = 1 << b - 1; E & h;) h >>= 1;
  36843. if (0 !== h ? (E &= h - 1, E += h) : E = 0, v++, 0 == --O[b]) {
  36844. if (b === w) break;
  36845. b = t[r + a[v]];
  36846. }
  36847. if (k < b && (E & f) !== l) {
  36848. for (0 === S && (S = k), c += y, z = 1 << (x = b - S); x + S < w && !((z -= O[x + S]) <= 0);) x++, z <<= 1;
  36849. if (C += 1 << x, 1 === e && 852 < C || 2 === e && 592 < C) return 1;
  36850. i[l = E & f] = k << 24 | x << 16 | c - s | 0;
  36851. }
  36852. }
  36853. return 0 !== E && (i[c + E] = b - S << 24 | 64 << 16 | 0), o.bits = k, 0;
  36854. };
  36855. }, {
  36856. "../utils/common": 41
  36857. }],
  36858. 51: [function (e, t, r) {
  36859. "use strict";
  36860. t.exports = {
  36861. 2: "need dictionary",
  36862. 1: "stream end",
  36863. 0: "",
  36864. "-1": "file error",
  36865. "-2": "stream error",
  36866. "-3": "data error",
  36867. "-4": "insufficient memory",
  36868. "-5": "buffer error",
  36869. "-6": "incompatible version"
  36870. };
  36871. }, {}],
  36872. 52: [function (e, t, r) {
  36873. "use strict";
  36874. var i = e("../utils/common"),
  36875. o = 0,
  36876. h = 1;
  36877. function n(e) {
  36878. for (var t = e.length; 0 <= --t;) e[t] = 0;
  36879. }
  36880. var s = 0,
  36881. a = 29,
  36882. u = 256,
  36883. l = u + 1 + a,
  36884. f = 30,
  36885. c = 19,
  36886. _ = 2 * l + 1,
  36887. g = 15,
  36888. d = 16,
  36889. p = 7,
  36890. m = 256,
  36891. b = 16,
  36892. v = 17,
  36893. y = 18,
  36894. w = [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],
  36895. k = [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],
  36896. x = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7],
  36897. S = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15],
  36898. z = new Array(2 * (l + 2));
  36899. n(z);
  36900. var C = new Array(2 * f);
  36901. n(C);
  36902. var E = new Array(512);
  36903. n(E);
  36904. var A = new Array(256);
  36905. n(A);
  36906. var I = new Array(a);
  36907. n(I);
  36908. var O,
  36909. B,
  36910. R,
  36911. T = new Array(f);
  36912. function D(e, t, r, n, i) {
  36913. this.static_tree = e, this.extra_bits = t, this.extra_base = r, this.elems = n, this.max_length = i, this.has_stree = e && e.length;
  36914. }
  36915. function F(e, t) {
  36916. this.dyn_tree = e, this.max_code = 0, this.stat_desc = t;
  36917. }
  36918. function N(e) {
  36919. return e < 256 ? E[e] : E[256 + (e >>> 7)];
  36920. }
  36921. function U(e, t) {
  36922. e.pending_buf[e.pending++] = 255 & t, e.pending_buf[e.pending++] = t >>> 8 & 255;
  36923. }
  36924. function P(e, t, r) {
  36925. e.bi_valid > d - r ? (e.bi_buf |= t << e.bi_valid & 65535, U(e, e.bi_buf), e.bi_buf = t >> d - e.bi_valid, e.bi_valid += r - d) : (e.bi_buf |= t << e.bi_valid & 65535, e.bi_valid += r);
  36926. }
  36927. function L(e, t, r) {
  36928. P(e, r[2 * t], r[2 * t + 1]);
  36929. }
  36930. function j(e, t) {
  36931. for (var r = 0; r |= 1 & e, e >>>= 1, r <<= 1, 0 < --t;);
  36932. return r >>> 1;
  36933. }
  36934. function Z(e, t, r) {
  36935. var n,
  36936. i,
  36937. s = new Array(g + 1),
  36938. a = 0;
  36939. for (n = 1; n <= g; n++) s[n] = a = a + r[n - 1] << 1;
  36940. for (i = 0; i <= t; i++) {
  36941. var o = e[2 * i + 1];
  36942. 0 !== o && (e[2 * i] = j(s[o]++, o));
  36943. }
  36944. }
  36945. function W(e) {
  36946. var t;
  36947. for (t = 0; t < l; t++) e.dyn_ltree[2 * t] = 0;
  36948. for (t = 0; t < f; t++) e.dyn_dtree[2 * t] = 0;
  36949. for (t = 0; t < c; t++) e.bl_tree[2 * t] = 0;
  36950. e.dyn_ltree[2 * m] = 1, e.opt_len = e.static_len = 0, e.last_lit = e.matches = 0;
  36951. }
  36952. function M(e) {
  36953. 8 < e.bi_valid ? U(e, e.bi_buf) : 0 < e.bi_valid && (e.pending_buf[e.pending++] = e.bi_buf), e.bi_buf = 0, e.bi_valid = 0;
  36954. }
  36955. function H(e, t, r, n) {
  36956. var i = 2 * t,
  36957. s = 2 * r;
  36958. return e[i] < e[s] || e[i] === e[s] && n[t] <= n[r];
  36959. }
  36960. function G(e, t, r) {
  36961. for (var n = e.heap[r], i = r << 1; i <= e.heap_len && (i < e.heap_len && H(t, e.heap[i + 1], e.heap[i], e.depth) && i++, !H(t, n, e.heap[i], e.depth));) e.heap[r] = e.heap[i], r = i, i <<= 1;
  36962. e.heap[r] = n;
  36963. }
  36964. function K(e, t, r) {
  36965. var n,
  36966. i,
  36967. s,
  36968. a,
  36969. o = 0;
  36970. if (0 !== e.last_lit) for (; n = e.pending_buf[e.d_buf + 2 * o] << 8 | e.pending_buf[e.d_buf + 2 * o + 1], i = e.pending_buf[e.l_buf + o], o++, 0 === n ? L(e, i, t) : (L(e, (s = A[i]) + u + 1, t), 0 !== (a = w[s]) && P(e, i -= I[s], a), L(e, s = N(--n), r), 0 !== (a = k[s]) && P(e, n -= T[s], a)), o < e.last_lit;);
  36971. L(e, m, t);
  36972. }
  36973. function Y(e, t) {
  36974. var r,
  36975. n,
  36976. i,
  36977. s = t.dyn_tree,
  36978. a = t.stat_desc.static_tree,
  36979. o = t.stat_desc.has_stree,
  36980. h = t.stat_desc.elems,
  36981. u = -1;
  36982. for (e.heap_len = 0, e.heap_max = _, r = 0; r < h; r++) 0 !== s[2 * r] ? (e.heap[++e.heap_len] = u = r, e.depth[r] = 0) : s[2 * r + 1] = 0;
  36983. for (; e.heap_len < 2;) s[2 * (i = e.heap[++e.heap_len] = u < 2 ? ++u : 0)] = 1, e.depth[i] = 0, e.opt_len--, o && (e.static_len -= a[2 * i + 1]);
  36984. for (t.max_code = u, r = e.heap_len >> 1; 1 <= r; r--) G(e, s, r);
  36985. for (i = h; r = e.heap[1], e.heap[1] = e.heap[e.heap_len--], G(e, s, 1), n = e.heap[1], e.heap[--e.heap_max] = r, e.heap[--e.heap_max] = n, s[2 * i] = s[2 * r] + s[2 * n], e.depth[i] = (e.depth[r] >= e.depth[n] ? e.depth[r] : e.depth[n]) + 1, s[2 * r + 1] = s[2 * n + 1] = i, e.heap[1] = i++, G(e, s, 1), 2 <= e.heap_len;);
  36986. e.heap[--e.heap_max] = e.heap[1], function (e, t) {
  36987. var r,
  36988. n,
  36989. i,
  36990. s,
  36991. a,
  36992. o,
  36993. h = t.dyn_tree,
  36994. u = t.max_code,
  36995. l = t.stat_desc.static_tree,
  36996. f = t.stat_desc.has_stree,
  36997. c = t.stat_desc.extra_bits,
  36998. d = t.stat_desc.extra_base,
  36999. p = t.stat_desc.max_length,
  37000. m = 0;
  37001. for (s = 0; s <= g; s++) e.bl_count[s] = 0;
  37002. for (h[2 * e.heap[e.heap_max] + 1] = 0, r = e.heap_max + 1; r < _; r++) p < (s = h[2 * h[2 * (n = e.heap[r]) + 1] + 1] + 1) && (s = p, m++), h[2 * n + 1] = s, u < n || (e.bl_count[s]++, a = 0, d <= n && (a = c[n - d]), o = h[2 * n], e.opt_len += o * (s + a), f && (e.static_len += o * (l[2 * n + 1] + a)));
  37003. if (0 !== m) {
  37004. do {
  37005. for (s = p - 1; 0 === e.bl_count[s];) s--;
  37006. e.bl_count[s]--, e.bl_count[s + 1] += 2, e.bl_count[p]--, m -= 2;
  37007. } while (0 < m);
  37008. for (s = p; 0 !== s; s--) for (n = e.bl_count[s]; 0 !== n;) u < (i = e.heap[--r]) || (h[2 * i + 1] !== s && (e.opt_len += (s - h[2 * i + 1]) * h[2 * i], h[2 * i + 1] = s), n--);
  37009. }
  37010. }(e, t), Z(s, u, e.bl_count);
  37011. }
  37012. function X(e, t, r) {
  37013. var n,
  37014. i,
  37015. s = -1,
  37016. a = t[1],
  37017. o = 0,
  37018. h = 7,
  37019. u = 4;
  37020. for (0 === a && (h = 138, u = 3), t[2 * (r + 1) + 1] = 65535, n = 0; n <= r; n++) i = a, a = t[2 * (n + 1) + 1], ++o < h && i === a || (o < u ? e.bl_tree[2 * i] += o : 0 !== i ? (i !== s && e.bl_tree[2 * i]++, e.bl_tree[2 * b]++) : o <= 10 ? e.bl_tree[2 * v]++ : e.bl_tree[2 * y]++, s = i, u = (o = 0) === a ? (h = 138, 3) : i === a ? (h = 6, 3) : (h = 7, 4));
  37021. }
  37022. function V(e, t, r) {
  37023. var n,
  37024. i,
  37025. s = -1,
  37026. a = t[1],
  37027. o = 0,
  37028. h = 7,
  37029. u = 4;
  37030. for (0 === a && (h = 138, u = 3), n = 0; n <= r; n++) if (i = a, a = t[2 * (n + 1) + 1], !(++o < h && i === a)) {
  37031. if (o < u) for (; L(e, i, e.bl_tree), 0 != --o;);else 0 !== i ? (i !== s && (L(e, i, e.bl_tree), o--), L(e, b, e.bl_tree), P(e, o - 3, 2)) : o <= 10 ? (L(e, v, e.bl_tree), P(e, o - 3, 3)) : (L(e, y, e.bl_tree), P(e, o - 11, 7));
  37032. s = i, u = (o = 0) === a ? (h = 138, 3) : i === a ? (h = 6, 3) : (h = 7, 4);
  37033. }
  37034. }
  37035. n(T);
  37036. var q = !1;
  37037. function J(e, t, r, n) {
  37038. P(e, (s << 1) + (n ? 1 : 0), 3), function (e, t, r, n) {
  37039. M(e), n && (U(e, r), U(e, ~r)), i.arraySet(e.pending_buf, e.window, t, r, e.pending), e.pending += r;
  37040. }(e, t, r, !0);
  37041. }
  37042. r._tr_init = function (e) {
  37043. q || (function () {
  37044. var e,
  37045. t,
  37046. r,
  37047. n,
  37048. i,
  37049. s = new Array(g + 1);
  37050. for (n = r = 0; n < a - 1; n++) for (I[n] = r, e = 0; e < 1 << w[n]; e++) A[r++] = n;
  37051. for (A[r - 1] = n, n = i = 0; n < 16; n++) for (T[n] = i, e = 0; e < 1 << k[n]; e++) E[i++] = n;
  37052. for (i >>= 7; n < f; n++) for (T[n] = i << 7, e = 0; e < 1 << k[n] - 7; e++) E[256 + i++] = n;
  37053. for (t = 0; t <= g; t++) s[t] = 0;
  37054. for (e = 0; e <= 143;) z[2 * e + 1] = 8, e++, s[8]++;
  37055. for (; e <= 255;) z[2 * e + 1] = 9, e++, s[9]++;
  37056. for (; e <= 279;) z[2 * e + 1] = 7, e++, s[7]++;
  37057. for (; e <= 287;) z[2 * e + 1] = 8, e++, s[8]++;
  37058. for (Z(z, l + 1, s), e = 0; e < f; e++) C[2 * e + 1] = 5, C[2 * e] = j(e, 5);
  37059. O = new D(z, w, u + 1, l, g), B = new D(C, k, 0, f, g), R = new D(new Array(0), x, 0, c, p);
  37060. }(), q = !0), e.l_desc = new F(e.dyn_ltree, O), e.d_desc = new F(e.dyn_dtree, B), e.bl_desc = new F(e.bl_tree, R), e.bi_buf = 0, e.bi_valid = 0, W(e);
  37061. }, r._tr_stored_block = J, r._tr_flush_block = function (e, t, r, n) {
  37062. var i,
  37063. s,
  37064. a = 0;
  37065. 0 < e.level ? (2 === e.strm.data_type && (e.strm.data_type = function (e) {
  37066. var t,
  37067. r = 4093624447;
  37068. for (t = 0; t <= 31; t++, r >>>= 1) if (1 & r && 0 !== e.dyn_ltree[2 * t]) return o;
  37069. if (0 !== e.dyn_ltree[18] || 0 !== e.dyn_ltree[20] || 0 !== e.dyn_ltree[26]) return h;
  37070. for (t = 32; t < u; t++) if (0 !== e.dyn_ltree[2 * t]) return h;
  37071. return o;
  37072. }(e)), Y(e, e.l_desc), Y(e, e.d_desc), a = function (e) {
  37073. var t;
  37074. for (X(e, e.dyn_ltree, e.l_desc.max_code), X(e, e.dyn_dtree, e.d_desc.max_code), Y(e, e.bl_desc), t = c - 1; 3 <= t && 0 === e.bl_tree[2 * S[t] + 1]; t--);
  37075. return e.opt_len += 3 * (t + 1) + 5 + 5 + 4, t;
  37076. }(e), i = e.opt_len + 3 + 7 >>> 3, (s = e.static_len + 3 + 7 >>> 3) <= i && (i = s)) : i = s = r + 5, r + 4 <= i && -1 !== t ? J(e, t, r, n) : 4 === e.strategy || s === i ? (P(e, 2 + (n ? 1 : 0), 3), K(e, z, C)) : (P(e, 4 + (n ? 1 : 0), 3), function (e, t, r, n) {
  37077. var i;
  37078. for (P(e, t - 257, 5), P(e, r - 1, 5), P(e, n - 4, 4), i = 0; i < n; i++) P(e, e.bl_tree[2 * S[i] + 1], 3);
  37079. V(e, e.dyn_ltree, t - 1), V(e, e.dyn_dtree, r - 1);
  37080. }(e, e.l_desc.max_code + 1, e.d_desc.max_code + 1, a + 1), K(e, e.dyn_ltree, e.dyn_dtree)), W(e), n && M(e);
  37081. }, r._tr_tally = function (e, t, r) {
  37082. return e.pending_buf[e.d_buf + 2 * e.last_lit] = t >>> 8 & 255, e.pending_buf[e.d_buf + 2 * e.last_lit + 1] = 255 & t, e.pending_buf[e.l_buf + e.last_lit] = 255 & r, e.last_lit++, 0 === t ? e.dyn_ltree[2 * r]++ : (e.matches++, t--, e.dyn_ltree[2 * (A[r] + u + 1)]++, e.dyn_dtree[2 * N(t)]++), e.last_lit === e.lit_bufsize - 1;
  37083. }, r._tr_align = function (e) {
  37084. P(e, 2, 3), L(e, m, z), function (e) {
  37085. 16 === e.bi_valid ? (U(e, e.bi_buf), e.bi_buf = 0, e.bi_valid = 0) : 8 <= e.bi_valid && (e.pending_buf[e.pending++] = 255 & e.bi_buf, e.bi_buf >>= 8, e.bi_valid -= 8);
  37086. }(e);
  37087. };
  37088. }, {
  37089. "../utils/common": 41
  37090. }],
  37091. 53: [function (e, t, r) {
  37092. "use strict";
  37093. t.exports = function () {
  37094. this.input = null, this.next_in = 0, this.avail_in = 0, this.total_in = 0, this.output = null, this.next_out = 0, this.avail_out = 0, this.total_out = 0, this.msg = "", this.state = null, this.data_type = 2, this.adler = 0;
  37095. };
  37096. }, {}],
  37097. 54: [function (e, t, r) {
  37098. (function (e) {
  37099. !function (r, n) {
  37100. "use strict";
  37101. if (!r.setImmediate) {
  37102. var i,
  37103. s,
  37104. t,
  37105. a,
  37106. o = 1,
  37107. h = {},
  37108. u = !1,
  37109. l = r.document,
  37110. e = Object.getPrototypeOf && Object.getPrototypeOf(r);
  37111. e = e && e.setTimeout ? e : r, i = "[object process]" === {}.toString.call(r.process) ? function (e) {
  37112. process.nextTick(function () {
  37113. c(e);
  37114. });
  37115. } : function () {
  37116. if (r.postMessage && !r.importScripts) {
  37117. var e = !0,
  37118. t = r.onmessage;
  37119. return r.onmessage = function () {
  37120. e = !1;
  37121. }, r.postMessage("", "*"), r.onmessage = t, e;
  37122. }
  37123. }() ? (a = "setImmediate$" + Math.random() + "$", r.addEventListener ? r.addEventListener("message", d, !1) : r.attachEvent("onmessage", d), function (e) {
  37124. r.postMessage(a + e, "*");
  37125. }) : r.MessageChannel ? ((t = new MessageChannel()).port1.onmessage = function (e) {
  37126. c(e.data);
  37127. }, function (e) {
  37128. t.port2.postMessage(e);
  37129. }) : l && "onreadystatechange" in l.createElement("script") ? (s = l.documentElement, function (e) {
  37130. var t = l.createElement("script");
  37131. t.onreadystatechange = function () {
  37132. c(e), t.onreadystatechange = null, s.removeChild(t), t = null;
  37133. }, s.appendChild(t);
  37134. }) : function (e) {
  37135. setTimeout(c, 0, e);
  37136. }, e.setImmediate = function (e) {
  37137. "function" != typeof e && (e = new Function("" + e));
  37138. for (var t = new Array(arguments.length - 1), r = 0; r < t.length; r++) t[r] = arguments[r + 1];
  37139. var n = {
  37140. callback: e,
  37141. args: t
  37142. };
  37143. return h[o] = n, i(o), o++;
  37144. }, e.clearImmediate = f;
  37145. }
  37146. function f(e) {
  37147. delete h[e];
  37148. }
  37149. function c(e) {
  37150. if (u) setTimeout(c, 0, e);else {
  37151. var t = h[e];
  37152. if (t) {
  37153. u = !0;
  37154. try {
  37155. !function (e) {
  37156. var t = e.callback,
  37157. r = e.args;
  37158. switch (r.length) {
  37159. case 0:
  37160. t();
  37161. break;
  37162. case 1:
  37163. t(r[0]);
  37164. break;
  37165. case 2:
  37166. t(r[0], r[1]);
  37167. break;
  37168. case 3:
  37169. t(r[0], r[1], r[2]);
  37170. break;
  37171. default:
  37172. t.apply(n, r);
  37173. }
  37174. }(t);
  37175. } finally {
  37176. f(e), u = !1;
  37177. }
  37178. }
  37179. }
  37180. }
  37181. function d(e) {
  37182. e.source === r && "string" == typeof e.data && 0 === e.data.indexOf(a) && c(+e.data.slice(a.length));
  37183. }
  37184. }("undefined" == typeof self ? void 0 === e ? this : e : self);
  37185. }).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
  37186. }, {}]
  37187. }, {}, [10])(10);
  37188. });
  37189. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],require("timers").setImmediate)
  37190. },{"_process":306,"buffer":220,"timers":361}],281:[function(require,module,exports){
  37191. (function (global){(function (){
  37192. "use strict";
  37193. /**
  37194. * lodash (Custom Build) <https://lodash.com/>
  37195. * Build: `lodash modularize exports="npm" -o ./`
  37196. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  37197. * Released under MIT license <https://lodash.com/license>
  37198. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  37199. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  37200. */
  37201. /** Used as references for various `Number` constants. */
  37202. var INFINITY = 1 / 0;
  37203. /** `Object#toString` result references. */
  37204. var symbolTag = '[object Symbol]';
  37205. /**
  37206. * Used to match `RegExp`
  37207. * [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns).
  37208. */
  37209. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
  37210. reHasRegExpChar = RegExp(reRegExpChar.source);
  37211. /** Detect free variable `global` from Node.js. */
  37212. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  37213. /** Detect free variable `self`. */
  37214. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  37215. /** Used as a reference to the global object. */
  37216. var root = freeGlobal || freeSelf || Function('return this')();
  37217. /** Used for built-in method references. */
  37218. var objectProto = Object.prototype;
  37219. /**
  37220. * Used to resolve the
  37221. * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  37222. * of values.
  37223. */
  37224. var objectToString = objectProto.toString;
  37225. /** Built-in value references. */
  37226. var Symbol = root.Symbol;
  37227. /** Used to convert symbols to primitives and strings. */
  37228. var symbolProto = Symbol ? Symbol.prototype : undefined,
  37229. symbolToString = symbolProto ? symbolProto.toString : undefined;
  37230. /**
  37231. * The base implementation of `_.toString` which doesn't convert nullish
  37232. * values to empty strings.
  37233. *
  37234. * @private
  37235. * @param {*} value The value to process.
  37236. * @returns {string} Returns the string.
  37237. */
  37238. function baseToString(value) {
  37239. // Exit early for strings to avoid a performance hit in some environments.
  37240. if (typeof value == 'string') {
  37241. return value;
  37242. }
  37243. if (isSymbol(value)) {
  37244. return symbolToString ? symbolToString.call(value) : '';
  37245. }
  37246. var result = value + '';
  37247. return result == '0' && 1 / value == -INFINITY ? '-0' : result;
  37248. }
  37249. /**
  37250. * Checks if `value` is object-like. A value is object-like if it's not `null`
  37251. * and has a `typeof` result of "object".
  37252. *
  37253. * @static
  37254. * @memberOf _
  37255. * @since 4.0.0
  37256. * @category Lang
  37257. * @param {*} value The value to check.
  37258. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  37259. * @example
  37260. *
  37261. * _.isObjectLike({});
  37262. * // => true
  37263. *
  37264. * _.isObjectLike([1, 2, 3]);
  37265. * // => true
  37266. *
  37267. * _.isObjectLike(_.noop);
  37268. * // => false
  37269. *
  37270. * _.isObjectLike(null);
  37271. * // => false
  37272. */
  37273. function isObjectLike(value) {
  37274. return !!value && typeof value == 'object';
  37275. }
  37276. /**
  37277. * Checks if `value` is classified as a `Symbol` primitive or object.
  37278. *
  37279. * @static
  37280. * @memberOf _
  37281. * @since 4.0.0
  37282. * @category Lang
  37283. * @param {*} value The value to check.
  37284. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  37285. * @example
  37286. *
  37287. * _.isSymbol(Symbol.iterator);
  37288. * // => true
  37289. *
  37290. * _.isSymbol('abc');
  37291. * // => false
  37292. */
  37293. function isSymbol(value) {
  37294. return typeof value == 'symbol' || isObjectLike(value) && objectToString.call(value) == symbolTag;
  37295. }
  37296. /**
  37297. * Converts `value` to a string. An empty string is returned for `null`
  37298. * and `undefined` values. The sign of `-0` is preserved.
  37299. *
  37300. * @static
  37301. * @memberOf _
  37302. * @since 4.0.0
  37303. * @category Lang
  37304. * @param {*} value The value to process.
  37305. * @returns {string} Returns the string.
  37306. * @example
  37307. *
  37308. * _.toString(null);
  37309. * // => ''
  37310. *
  37311. * _.toString(-0);
  37312. * // => '-0'
  37313. *
  37314. * _.toString([1, 2, 3]);
  37315. * // => '1,2,3'
  37316. */
  37317. function toString(value) {
  37318. return value == null ? '' : baseToString(value);
  37319. }
  37320. /**
  37321. * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
  37322. * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
  37323. *
  37324. * @static
  37325. * @memberOf _
  37326. * @since 3.0.0
  37327. * @category String
  37328. * @param {string} [string=''] The string to escape.
  37329. * @returns {string} Returns the escaped string.
  37330. * @example
  37331. *
  37332. * _.escapeRegExp('[lodash](https://lodash.com/)');
  37333. * // => '\[lodash\]\(https://lodash\.com/\)'
  37334. */
  37335. function escapeRegExp(string) {
  37336. string = toString(string);
  37337. return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, '\\$&') : string;
  37338. }
  37339. module.exports = escapeRegExp;
  37340. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  37341. },{}],282:[function(require,module,exports){
  37342. (function (global){(function (){
  37343. "use strict";
  37344. /**
  37345. * lodash (Custom Build) <https://lodash.com/>
  37346. * Build: `lodash modularize exports="npm" -o ./`
  37347. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  37348. * Released under MIT license <https://lodash.com/license>
  37349. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  37350. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  37351. */
  37352. /** Used as the size to enable large array optimizations. */
  37353. var LARGE_ARRAY_SIZE = 200;
  37354. /** Used as the `TypeError` message for "Functions" methods. */
  37355. var FUNC_ERROR_TEXT = 'Expected a function';
  37356. /** Used to stand-in for `undefined` hash values. */
  37357. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  37358. /** Used to compose bitmasks for comparison styles. */
  37359. var UNORDERED_COMPARE_FLAG = 1,
  37360. PARTIAL_COMPARE_FLAG = 2;
  37361. /** Used as references for various `Number` constants. */
  37362. var INFINITY = 1 / 0,
  37363. MAX_SAFE_INTEGER = 9007199254740991;
  37364. /** `Object#toString` result references. */
  37365. var argsTag = '[object Arguments]',
  37366. arrayTag = '[object Array]',
  37367. boolTag = '[object Boolean]',
  37368. dateTag = '[object Date]',
  37369. errorTag = '[object Error]',
  37370. funcTag = '[object Function]',
  37371. genTag = '[object GeneratorFunction]',
  37372. mapTag = '[object Map]',
  37373. numberTag = '[object Number]',
  37374. objectTag = '[object Object]',
  37375. promiseTag = '[object Promise]',
  37376. regexpTag = '[object RegExp]',
  37377. setTag = '[object Set]',
  37378. stringTag = '[object String]',
  37379. symbolTag = '[object Symbol]',
  37380. weakMapTag = '[object WeakMap]';
  37381. var arrayBufferTag = '[object ArrayBuffer]',
  37382. dataViewTag = '[object DataView]',
  37383. float32Tag = '[object Float32Array]',
  37384. float64Tag = '[object Float64Array]',
  37385. int8Tag = '[object Int8Array]',
  37386. int16Tag = '[object Int16Array]',
  37387. int32Tag = '[object Int32Array]',
  37388. uint8Tag = '[object Uint8Array]',
  37389. uint8ClampedTag = '[object Uint8ClampedArray]',
  37390. uint16Tag = '[object Uint16Array]',
  37391. uint32Tag = '[object Uint32Array]';
  37392. /** Used to match property names within property paths. */
  37393. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  37394. reIsPlainProp = /^\w*$/,
  37395. reLeadingDot = /^\./,
  37396. rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  37397. /**
  37398. * Used to match `RegExp`
  37399. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  37400. */
  37401. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  37402. /** Used to match backslashes in property paths. */
  37403. var reEscapeChar = /\\(\\)?/g;
  37404. /** Used to detect host constructors (Safari). */
  37405. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  37406. /** Used to detect unsigned integer values. */
  37407. var reIsUint = /^(?:0|[1-9]\d*)$/;
  37408. /** Used to identify `toStringTag` values of typed arrays. */
  37409. var typedArrayTags = {};
  37410. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
  37411. typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
  37412. /** Detect free variable `global` from Node.js. */
  37413. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  37414. /** Detect free variable `self`. */
  37415. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  37416. /** Used as a reference to the global object. */
  37417. var root = freeGlobal || freeSelf || Function('return this')();
  37418. /** Detect free variable `exports`. */
  37419. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  37420. /** Detect free variable `module`. */
  37421. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  37422. /** Detect the popular CommonJS extension `module.exports`. */
  37423. var moduleExports = freeModule && freeModule.exports === freeExports;
  37424. /** Detect free variable `process` from Node.js. */
  37425. var freeProcess = moduleExports && freeGlobal.process;
  37426. /** Used to access faster Node.js helpers. */
  37427. var nodeUtil = function () {
  37428. try {
  37429. return freeProcess && freeProcess.binding('util');
  37430. } catch (e) {}
  37431. }();
  37432. /* Node.js helper references. */
  37433. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  37434. /**
  37435. * A specialized version of `baseAggregator` for arrays.
  37436. *
  37437. * @private
  37438. * @param {Array} [array] The array to iterate over.
  37439. * @param {Function} setter The function to set `accumulator` values.
  37440. * @param {Function} iteratee The iteratee to transform keys.
  37441. * @param {Object} accumulator The initial aggregated object.
  37442. * @returns {Function} Returns `accumulator`.
  37443. */
  37444. function arrayAggregator(array, setter, iteratee, accumulator) {
  37445. var index = -1,
  37446. length = array ? array.length : 0;
  37447. while (++index < length) {
  37448. var value = array[index];
  37449. setter(accumulator, value, iteratee(value), array);
  37450. }
  37451. return accumulator;
  37452. }
  37453. /**
  37454. * A specialized version of `_.some` for arrays without support for iteratee
  37455. * shorthands.
  37456. *
  37457. * @private
  37458. * @param {Array} [array] The array to iterate over.
  37459. * @param {Function} predicate The function invoked per iteration.
  37460. * @returns {boolean} Returns `true` if any element passes the predicate check,
  37461. * else `false`.
  37462. */
  37463. function arraySome(array, predicate) {
  37464. var index = -1,
  37465. length = array ? array.length : 0;
  37466. while (++index < length) {
  37467. if (predicate(array[index], index, array)) {
  37468. return true;
  37469. }
  37470. }
  37471. return false;
  37472. }
  37473. /**
  37474. * The base implementation of `_.property` without support for deep paths.
  37475. *
  37476. * @private
  37477. * @param {string} key The key of the property to get.
  37478. * @returns {Function} Returns the new accessor function.
  37479. */
  37480. function baseProperty(key) {
  37481. return function (object) {
  37482. return object == null ? undefined : object[key];
  37483. };
  37484. }
  37485. /**
  37486. * The base implementation of `_.times` without support for iteratee shorthands
  37487. * or max array length checks.
  37488. *
  37489. * @private
  37490. * @param {number} n The number of times to invoke `iteratee`.
  37491. * @param {Function} iteratee The function invoked per iteration.
  37492. * @returns {Array} Returns the array of results.
  37493. */
  37494. function baseTimes(n, iteratee) {
  37495. var index = -1,
  37496. result = Array(n);
  37497. while (++index < n) {
  37498. result[index] = iteratee(index);
  37499. }
  37500. return result;
  37501. }
  37502. /**
  37503. * The base implementation of `_.unary` without support for storing metadata.
  37504. *
  37505. * @private
  37506. * @param {Function} func The function to cap arguments for.
  37507. * @returns {Function} Returns the new capped function.
  37508. */
  37509. function baseUnary(func) {
  37510. return function (value) {
  37511. return func(value);
  37512. };
  37513. }
  37514. /**
  37515. * Gets the value at `key` of `object`.
  37516. *
  37517. * @private
  37518. * @param {Object} [object] The object to query.
  37519. * @param {string} key The key of the property to get.
  37520. * @returns {*} Returns the property value.
  37521. */
  37522. function getValue(object, key) {
  37523. return object == null ? undefined : object[key];
  37524. }
  37525. /**
  37526. * Checks if `value` is a host object in IE < 9.
  37527. *
  37528. * @private
  37529. * @param {*} value The value to check.
  37530. * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
  37531. */
  37532. function isHostObject(value) {
  37533. // Many host objects are `Object` objects that can coerce to strings
  37534. // despite having improperly defined `toString` methods.
  37535. var result = false;
  37536. if (value != null && typeof value.toString != 'function') {
  37537. try {
  37538. result = !!(value + '');
  37539. } catch (e) {}
  37540. }
  37541. return result;
  37542. }
  37543. /**
  37544. * Converts `map` to its key-value pairs.
  37545. *
  37546. * @private
  37547. * @param {Object} map The map to convert.
  37548. * @returns {Array} Returns the key-value pairs.
  37549. */
  37550. function mapToArray(map) {
  37551. var index = -1,
  37552. result = Array(map.size);
  37553. map.forEach(function (value, key) {
  37554. result[++index] = [key, value];
  37555. });
  37556. return result;
  37557. }
  37558. /**
  37559. * Creates a unary function that invokes `func` with its argument transformed.
  37560. *
  37561. * @private
  37562. * @param {Function} func The function to wrap.
  37563. * @param {Function} transform The argument transform.
  37564. * @returns {Function} Returns the new function.
  37565. */
  37566. function overArg(func, transform) {
  37567. return function (arg) {
  37568. return func(transform(arg));
  37569. };
  37570. }
  37571. /**
  37572. * Converts `set` to an array of its values.
  37573. *
  37574. * @private
  37575. * @param {Object} set The set to convert.
  37576. * @returns {Array} Returns the values.
  37577. */
  37578. function setToArray(set) {
  37579. var index = -1,
  37580. result = Array(set.size);
  37581. set.forEach(function (value) {
  37582. result[++index] = value;
  37583. });
  37584. return result;
  37585. }
  37586. /** Used for built-in method references. */
  37587. var arrayProto = Array.prototype,
  37588. funcProto = Function.prototype,
  37589. objectProto = Object.prototype;
  37590. /** Used to detect overreaching core-js shims. */
  37591. var coreJsData = root['__core-js_shared__'];
  37592. /** Used to detect methods masquerading as native. */
  37593. var maskSrcKey = function () {
  37594. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  37595. return uid ? 'Symbol(src)_1.' + uid : '';
  37596. }();
  37597. /** Used to resolve the decompiled source of functions. */
  37598. var funcToString = funcProto.toString;
  37599. /** Used to check objects for own properties. */
  37600. var hasOwnProperty = objectProto.hasOwnProperty;
  37601. /**
  37602. * Used to resolve the
  37603. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  37604. * of values.
  37605. */
  37606. var objectToString = objectProto.toString;
  37607. /** Used to detect if a method is native. */
  37608. var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
  37609. /** Built-in value references. */
  37610. var Symbol = root.Symbol,
  37611. Uint8Array = root.Uint8Array,
  37612. propertyIsEnumerable = objectProto.propertyIsEnumerable,
  37613. splice = arrayProto.splice;
  37614. /* Built-in method references for those with the same name as other `lodash` methods. */
  37615. var nativeKeys = overArg(Object.keys, Object);
  37616. /* Built-in method references that are verified to be native. */
  37617. var DataView = getNative(root, 'DataView'),
  37618. Map = getNative(root, 'Map'),
  37619. Promise = getNative(root, 'Promise'),
  37620. Set = getNative(root, 'Set'),
  37621. WeakMap = getNative(root, 'WeakMap'),
  37622. nativeCreate = getNative(Object, 'create');
  37623. /** Used to detect maps, sets, and weakmaps. */
  37624. var dataViewCtorString = toSource(DataView),
  37625. mapCtorString = toSource(Map),
  37626. promiseCtorString = toSource(Promise),
  37627. setCtorString = toSource(Set),
  37628. weakMapCtorString = toSource(WeakMap);
  37629. /** Used to convert symbols to primitives and strings. */
  37630. var symbolProto = Symbol ? Symbol.prototype : undefined,
  37631. symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
  37632. symbolToString = symbolProto ? symbolProto.toString : undefined;
  37633. /**
  37634. * Creates a hash object.
  37635. *
  37636. * @private
  37637. * @constructor
  37638. * @param {Array} [entries] The key-value pairs to cache.
  37639. */
  37640. function Hash(entries) {
  37641. var index = -1,
  37642. length = entries ? entries.length : 0;
  37643. this.clear();
  37644. while (++index < length) {
  37645. var entry = entries[index];
  37646. this.set(entry[0], entry[1]);
  37647. }
  37648. }
  37649. /**
  37650. * Removes all key-value entries from the hash.
  37651. *
  37652. * @private
  37653. * @name clear
  37654. * @memberOf Hash
  37655. */
  37656. function hashClear() {
  37657. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  37658. }
  37659. /**
  37660. * Removes `key` and its value from the hash.
  37661. *
  37662. * @private
  37663. * @name delete
  37664. * @memberOf Hash
  37665. * @param {Object} hash The hash to modify.
  37666. * @param {string} key The key of the value to remove.
  37667. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  37668. */
  37669. function hashDelete(key) {
  37670. return this.has(key) && delete this.__data__[key];
  37671. }
  37672. /**
  37673. * Gets the hash value for `key`.
  37674. *
  37675. * @private
  37676. * @name get
  37677. * @memberOf Hash
  37678. * @param {string} key The key of the value to get.
  37679. * @returns {*} Returns the entry value.
  37680. */
  37681. function hashGet(key) {
  37682. var data = this.__data__;
  37683. if (nativeCreate) {
  37684. var result = data[key];
  37685. return result === HASH_UNDEFINED ? undefined : result;
  37686. }
  37687. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  37688. }
  37689. /**
  37690. * Checks if a hash value for `key` exists.
  37691. *
  37692. * @private
  37693. * @name has
  37694. * @memberOf Hash
  37695. * @param {string} key The key of the entry to check.
  37696. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  37697. */
  37698. function hashHas(key) {
  37699. var data = this.__data__;
  37700. return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
  37701. }
  37702. /**
  37703. * Sets the hash `key` to `value`.
  37704. *
  37705. * @private
  37706. * @name set
  37707. * @memberOf Hash
  37708. * @param {string} key The key of the value to set.
  37709. * @param {*} value The value to set.
  37710. * @returns {Object} Returns the hash instance.
  37711. */
  37712. function hashSet(key, value) {
  37713. var data = this.__data__;
  37714. data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value;
  37715. return this;
  37716. }
  37717. // Add methods to `Hash`.
  37718. Hash.prototype.clear = hashClear;
  37719. Hash.prototype['delete'] = hashDelete;
  37720. Hash.prototype.get = hashGet;
  37721. Hash.prototype.has = hashHas;
  37722. Hash.prototype.set = hashSet;
  37723. /**
  37724. * Creates an list cache object.
  37725. *
  37726. * @private
  37727. * @constructor
  37728. * @param {Array} [entries] The key-value pairs to cache.
  37729. */
  37730. function ListCache(entries) {
  37731. var index = -1,
  37732. length = entries ? entries.length : 0;
  37733. this.clear();
  37734. while (++index < length) {
  37735. var entry = entries[index];
  37736. this.set(entry[0], entry[1]);
  37737. }
  37738. }
  37739. /**
  37740. * Removes all key-value entries from the list cache.
  37741. *
  37742. * @private
  37743. * @name clear
  37744. * @memberOf ListCache
  37745. */
  37746. function listCacheClear() {
  37747. this.__data__ = [];
  37748. }
  37749. /**
  37750. * Removes `key` and its value from the list cache.
  37751. *
  37752. * @private
  37753. * @name delete
  37754. * @memberOf ListCache
  37755. * @param {string} key The key of the value to remove.
  37756. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  37757. */
  37758. function listCacheDelete(key) {
  37759. var data = this.__data__,
  37760. index = assocIndexOf(data, key);
  37761. if (index < 0) {
  37762. return false;
  37763. }
  37764. var lastIndex = data.length - 1;
  37765. if (index == lastIndex) {
  37766. data.pop();
  37767. } else {
  37768. splice.call(data, index, 1);
  37769. }
  37770. return true;
  37771. }
  37772. /**
  37773. * Gets the list cache value for `key`.
  37774. *
  37775. * @private
  37776. * @name get
  37777. * @memberOf ListCache
  37778. * @param {string} key The key of the value to get.
  37779. * @returns {*} Returns the entry value.
  37780. */
  37781. function listCacheGet(key) {
  37782. var data = this.__data__,
  37783. index = assocIndexOf(data, key);
  37784. return index < 0 ? undefined : data[index][1];
  37785. }
  37786. /**
  37787. * Checks if a list cache value for `key` exists.
  37788. *
  37789. * @private
  37790. * @name has
  37791. * @memberOf ListCache
  37792. * @param {string} key The key of the entry to check.
  37793. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  37794. */
  37795. function listCacheHas(key) {
  37796. return assocIndexOf(this.__data__, key) > -1;
  37797. }
  37798. /**
  37799. * Sets the list cache `key` to `value`.
  37800. *
  37801. * @private
  37802. * @name set
  37803. * @memberOf ListCache
  37804. * @param {string} key The key of the value to set.
  37805. * @param {*} value The value to set.
  37806. * @returns {Object} Returns the list cache instance.
  37807. */
  37808. function listCacheSet(key, value) {
  37809. var data = this.__data__,
  37810. index = assocIndexOf(data, key);
  37811. if (index < 0) {
  37812. data.push([key, value]);
  37813. } else {
  37814. data[index][1] = value;
  37815. }
  37816. return this;
  37817. }
  37818. // Add methods to `ListCache`.
  37819. ListCache.prototype.clear = listCacheClear;
  37820. ListCache.prototype['delete'] = listCacheDelete;
  37821. ListCache.prototype.get = listCacheGet;
  37822. ListCache.prototype.has = listCacheHas;
  37823. ListCache.prototype.set = listCacheSet;
  37824. /**
  37825. * Creates a map cache object to store key-value pairs.
  37826. *
  37827. * @private
  37828. * @constructor
  37829. * @param {Array} [entries] The key-value pairs to cache.
  37830. */
  37831. function MapCache(entries) {
  37832. var index = -1,
  37833. length = entries ? entries.length : 0;
  37834. this.clear();
  37835. while (++index < length) {
  37836. var entry = entries[index];
  37837. this.set(entry[0], entry[1]);
  37838. }
  37839. }
  37840. /**
  37841. * Removes all key-value entries from the map.
  37842. *
  37843. * @private
  37844. * @name clear
  37845. * @memberOf MapCache
  37846. */
  37847. function mapCacheClear() {
  37848. this.__data__ = {
  37849. 'hash': new Hash(),
  37850. 'map': new (Map || ListCache)(),
  37851. 'string': new Hash()
  37852. };
  37853. }
  37854. /**
  37855. * Removes `key` and its value from the map.
  37856. *
  37857. * @private
  37858. * @name delete
  37859. * @memberOf MapCache
  37860. * @param {string} key The key of the value to remove.
  37861. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  37862. */
  37863. function mapCacheDelete(key) {
  37864. return getMapData(this, key)['delete'](key);
  37865. }
  37866. /**
  37867. * Gets the map value for `key`.
  37868. *
  37869. * @private
  37870. * @name get
  37871. * @memberOf MapCache
  37872. * @param {string} key The key of the value to get.
  37873. * @returns {*} Returns the entry value.
  37874. */
  37875. function mapCacheGet(key) {
  37876. return getMapData(this, key).get(key);
  37877. }
  37878. /**
  37879. * Checks if a map value for `key` exists.
  37880. *
  37881. * @private
  37882. * @name has
  37883. * @memberOf MapCache
  37884. * @param {string} key The key of the entry to check.
  37885. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  37886. */
  37887. function mapCacheHas(key) {
  37888. return getMapData(this, key).has(key);
  37889. }
  37890. /**
  37891. * Sets the map `key` to `value`.
  37892. *
  37893. * @private
  37894. * @name set
  37895. * @memberOf MapCache
  37896. * @param {string} key The key of the value to set.
  37897. * @param {*} value The value to set.
  37898. * @returns {Object} Returns the map cache instance.
  37899. */
  37900. function mapCacheSet(key, value) {
  37901. getMapData(this, key).set(key, value);
  37902. return this;
  37903. }
  37904. // Add methods to `MapCache`.
  37905. MapCache.prototype.clear = mapCacheClear;
  37906. MapCache.prototype['delete'] = mapCacheDelete;
  37907. MapCache.prototype.get = mapCacheGet;
  37908. MapCache.prototype.has = mapCacheHas;
  37909. MapCache.prototype.set = mapCacheSet;
  37910. /**
  37911. *
  37912. * Creates an array cache object to store unique values.
  37913. *
  37914. * @private
  37915. * @constructor
  37916. * @param {Array} [values] The values to cache.
  37917. */
  37918. function SetCache(values) {
  37919. var index = -1,
  37920. length = values ? values.length : 0;
  37921. this.__data__ = new MapCache();
  37922. while (++index < length) {
  37923. this.add(values[index]);
  37924. }
  37925. }
  37926. /**
  37927. * Adds `value` to the array cache.
  37928. *
  37929. * @private
  37930. * @name add
  37931. * @memberOf SetCache
  37932. * @alias push
  37933. * @param {*} value The value to cache.
  37934. * @returns {Object} Returns the cache instance.
  37935. */
  37936. function setCacheAdd(value) {
  37937. this.__data__.set(value, HASH_UNDEFINED);
  37938. return this;
  37939. }
  37940. /**
  37941. * Checks if `value` is in the array cache.
  37942. *
  37943. * @private
  37944. * @name has
  37945. * @memberOf SetCache
  37946. * @param {*} value The value to search for.
  37947. * @returns {number} Returns `true` if `value` is found, else `false`.
  37948. */
  37949. function setCacheHas(value) {
  37950. return this.__data__.has(value);
  37951. }
  37952. // Add methods to `SetCache`.
  37953. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
  37954. SetCache.prototype.has = setCacheHas;
  37955. /**
  37956. * Creates a stack cache object to store key-value pairs.
  37957. *
  37958. * @private
  37959. * @constructor
  37960. * @param {Array} [entries] The key-value pairs to cache.
  37961. */
  37962. function Stack(entries) {
  37963. this.__data__ = new ListCache(entries);
  37964. }
  37965. /**
  37966. * Removes all key-value entries from the stack.
  37967. *
  37968. * @private
  37969. * @name clear
  37970. * @memberOf Stack
  37971. */
  37972. function stackClear() {
  37973. this.__data__ = new ListCache();
  37974. }
  37975. /**
  37976. * Removes `key` and its value from the stack.
  37977. *
  37978. * @private
  37979. * @name delete
  37980. * @memberOf Stack
  37981. * @param {string} key The key of the value to remove.
  37982. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  37983. */
  37984. function stackDelete(key) {
  37985. return this.__data__['delete'](key);
  37986. }
  37987. /**
  37988. * Gets the stack value for `key`.
  37989. *
  37990. * @private
  37991. * @name get
  37992. * @memberOf Stack
  37993. * @param {string} key The key of the value to get.
  37994. * @returns {*} Returns the entry value.
  37995. */
  37996. function stackGet(key) {
  37997. return this.__data__.get(key);
  37998. }
  37999. /**
  38000. * Checks if a stack value for `key` exists.
  38001. *
  38002. * @private
  38003. * @name has
  38004. * @memberOf Stack
  38005. * @param {string} key The key of the entry to check.
  38006. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  38007. */
  38008. function stackHas(key) {
  38009. return this.__data__.has(key);
  38010. }
  38011. /**
  38012. * Sets the stack `key` to `value`.
  38013. *
  38014. * @private
  38015. * @name set
  38016. * @memberOf Stack
  38017. * @param {string} key The key of the value to set.
  38018. * @param {*} value The value to set.
  38019. * @returns {Object} Returns the stack cache instance.
  38020. */
  38021. function stackSet(key, value) {
  38022. var cache = this.__data__;
  38023. if (cache instanceof ListCache) {
  38024. var pairs = cache.__data__;
  38025. if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
  38026. pairs.push([key, value]);
  38027. return this;
  38028. }
  38029. cache = this.__data__ = new MapCache(pairs);
  38030. }
  38031. cache.set(key, value);
  38032. return this;
  38033. }
  38034. // Add methods to `Stack`.
  38035. Stack.prototype.clear = stackClear;
  38036. Stack.prototype['delete'] = stackDelete;
  38037. Stack.prototype.get = stackGet;
  38038. Stack.prototype.has = stackHas;
  38039. Stack.prototype.set = stackSet;
  38040. /**
  38041. * Creates an array of the enumerable property names of the array-like `value`.
  38042. *
  38043. * @private
  38044. * @param {*} value The value to query.
  38045. * @param {boolean} inherited Specify returning inherited property names.
  38046. * @returns {Array} Returns the array of property names.
  38047. */
  38048. function arrayLikeKeys(value, inherited) {
  38049. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  38050. // Safari 9 makes `arguments.length` enumerable in strict mode.
  38051. var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : [];
  38052. var length = result.length,
  38053. skipIndexes = !!length;
  38054. for (var key in value) {
  38055. if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
  38056. result.push(key);
  38057. }
  38058. }
  38059. return result;
  38060. }
  38061. /**
  38062. * Gets the index at which the `key` is found in `array` of key-value pairs.
  38063. *
  38064. * @private
  38065. * @param {Array} array The array to inspect.
  38066. * @param {*} key The key to search for.
  38067. * @returns {number} Returns the index of the matched value, else `-1`.
  38068. */
  38069. function assocIndexOf(array, key) {
  38070. var length = array.length;
  38071. while (length--) {
  38072. if (eq(array[length][0], key)) {
  38073. return length;
  38074. }
  38075. }
  38076. return -1;
  38077. }
  38078. /**
  38079. * Aggregates elements of `collection` on `accumulator` with keys transformed
  38080. * by `iteratee` and values set by `setter`.
  38081. *
  38082. * @private
  38083. * @param {Array|Object} collection The collection to iterate over.
  38084. * @param {Function} setter The function to set `accumulator` values.
  38085. * @param {Function} iteratee The iteratee to transform keys.
  38086. * @param {Object} accumulator The initial aggregated object.
  38087. * @returns {Function} Returns `accumulator`.
  38088. */
  38089. function baseAggregator(collection, setter, iteratee, accumulator) {
  38090. baseEach(collection, function (value, key, collection) {
  38091. setter(accumulator, value, iteratee(value), collection);
  38092. });
  38093. return accumulator;
  38094. }
  38095. /**
  38096. * The base implementation of `_.forEach` without support for iteratee shorthands.
  38097. *
  38098. * @private
  38099. * @param {Array|Object} collection The collection to iterate over.
  38100. * @param {Function} iteratee The function invoked per iteration.
  38101. * @returns {Array|Object} Returns `collection`.
  38102. */
  38103. var baseEach = createBaseEach(baseForOwn);
  38104. /**
  38105. * The base implementation of `baseForOwn` which iterates over `object`
  38106. * properties returned by `keysFunc` and invokes `iteratee` for each property.
  38107. * Iteratee functions may exit iteration early by explicitly returning `false`.
  38108. *
  38109. * @private
  38110. * @param {Object} object The object to iterate over.
  38111. * @param {Function} iteratee The function invoked per iteration.
  38112. * @param {Function} keysFunc The function to get the keys of `object`.
  38113. * @returns {Object} Returns `object`.
  38114. */
  38115. var baseFor = createBaseFor();
  38116. /**
  38117. * The base implementation of `_.forOwn` without support for iteratee shorthands.
  38118. *
  38119. * @private
  38120. * @param {Object} object The object to iterate over.
  38121. * @param {Function} iteratee The function invoked per iteration.
  38122. * @returns {Object} Returns `object`.
  38123. */
  38124. function baseForOwn(object, iteratee) {
  38125. return object && baseFor(object, iteratee, keys);
  38126. }
  38127. /**
  38128. * The base implementation of `_.get` without support for default values.
  38129. *
  38130. * @private
  38131. * @param {Object} object The object to query.
  38132. * @param {Array|string} path The path of the property to get.
  38133. * @returns {*} Returns the resolved value.
  38134. */
  38135. function baseGet(object, path) {
  38136. path = isKey(path, object) ? [path] : castPath(path);
  38137. var index = 0,
  38138. length = path.length;
  38139. while (object != null && index < length) {
  38140. object = object[toKey(path[index++])];
  38141. }
  38142. return index && index == length ? object : undefined;
  38143. }
  38144. /**
  38145. * The base implementation of `getTag`.
  38146. *
  38147. * @private
  38148. * @param {*} value The value to query.
  38149. * @returns {string} Returns the `toStringTag`.
  38150. */
  38151. function baseGetTag(value) {
  38152. return objectToString.call(value);
  38153. }
  38154. /**
  38155. * The base implementation of `_.hasIn` without support for deep paths.
  38156. *
  38157. * @private
  38158. * @param {Object} [object] The object to query.
  38159. * @param {Array|string} key The key to check.
  38160. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  38161. */
  38162. function baseHasIn(object, key) {
  38163. return object != null && key in Object(object);
  38164. }
  38165. /**
  38166. * The base implementation of `_.isEqual` which supports partial comparisons
  38167. * and tracks traversed objects.
  38168. *
  38169. * @private
  38170. * @param {*} value The value to compare.
  38171. * @param {*} other The other value to compare.
  38172. * @param {Function} [customizer] The function to customize comparisons.
  38173. * @param {boolean} [bitmask] The bitmask of comparison flags.
  38174. * The bitmask may be composed of the following flags:
  38175. * 1 - Unordered comparison
  38176. * 2 - Partial comparison
  38177. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  38178. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  38179. */
  38180. function baseIsEqual(value, other, customizer, bitmask, stack) {
  38181. if (value === other) {
  38182. return true;
  38183. }
  38184. if (value == null || other == null || !isObject(value) && !isObjectLike(other)) {
  38185. return value !== value && other !== other;
  38186. }
  38187. return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
  38188. }
  38189. /**
  38190. * A specialized version of `baseIsEqual` for arrays and objects which performs
  38191. * deep comparisons and tracks traversed objects enabling objects with circular
  38192. * references to be compared.
  38193. *
  38194. * @private
  38195. * @param {Object} object The object to compare.
  38196. * @param {Object} other The other object to compare.
  38197. * @param {Function} equalFunc The function to determine equivalents of values.
  38198. * @param {Function} [customizer] The function to customize comparisons.
  38199. * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
  38200. * for more details.
  38201. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  38202. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  38203. */
  38204. function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
  38205. var objIsArr = isArray(object),
  38206. othIsArr = isArray(other),
  38207. objTag = arrayTag,
  38208. othTag = arrayTag;
  38209. if (!objIsArr) {
  38210. objTag = getTag(object);
  38211. objTag = objTag == argsTag ? objectTag : objTag;
  38212. }
  38213. if (!othIsArr) {
  38214. othTag = getTag(other);
  38215. othTag = othTag == argsTag ? objectTag : othTag;
  38216. }
  38217. var objIsObj = objTag == objectTag && !isHostObject(object),
  38218. othIsObj = othTag == objectTag && !isHostObject(other),
  38219. isSameTag = objTag == othTag;
  38220. if (isSameTag && !objIsObj) {
  38221. stack || (stack = new Stack());
  38222. return objIsArr || isTypedArray(object) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
  38223. }
  38224. if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
  38225. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  38226. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  38227. if (objIsWrapped || othIsWrapped) {
  38228. var objUnwrapped = objIsWrapped ? object.value() : object,
  38229. othUnwrapped = othIsWrapped ? other.value() : other;
  38230. stack || (stack = new Stack());
  38231. return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
  38232. }
  38233. }
  38234. if (!isSameTag) {
  38235. return false;
  38236. }
  38237. stack || (stack = new Stack());
  38238. return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
  38239. }
  38240. /**
  38241. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  38242. *
  38243. * @private
  38244. * @param {Object} object The object to inspect.
  38245. * @param {Object} source The object of property values to match.
  38246. * @param {Array} matchData The property names, values, and compare flags to match.
  38247. * @param {Function} [customizer] The function to customize comparisons.
  38248. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  38249. */
  38250. function baseIsMatch(object, source, matchData, customizer) {
  38251. var index = matchData.length,
  38252. length = index,
  38253. noCustomizer = !customizer;
  38254. if (object == null) {
  38255. return !length;
  38256. }
  38257. object = Object(object);
  38258. while (index--) {
  38259. var data = matchData[index];
  38260. if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
  38261. return false;
  38262. }
  38263. }
  38264. while (++index < length) {
  38265. data = matchData[index];
  38266. var key = data[0],
  38267. objValue = object[key],
  38268. srcValue = data[1];
  38269. if (noCustomizer && data[2]) {
  38270. if (objValue === undefined && !(key in object)) {
  38271. return false;
  38272. }
  38273. } else {
  38274. var stack = new Stack();
  38275. if (customizer) {
  38276. var result = customizer(objValue, srcValue, key, object, source, stack);
  38277. }
  38278. if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result)) {
  38279. return false;
  38280. }
  38281. }
  38282. }
  38283. return true;
  38284. }
  38285. /**
  38286. * The base implementation of `_.isNative` without bad shim checks.
  38287. *
  38288. * @private
  38289. * @param {*} value The value to check.
  38290. * @returns {boolean} Returns `true` if `value` is a native function,
  38291. * else `false`.
  38292. */
  38293. function baseIsNative(value) {
  38294. if (!isObject(value) || isMasked(value)) {
  38295. return false;
  38296. }
  38297. var pattern = isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor;
  38298. return pattern.test(toSource(value));
  38299. }
  38300. /**
  38301. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  38302. *
  38303. * @private
  38304. * @param {*} value The value to check.
  38305. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  38306. */
  38307. function baseIsTypedArray(value) {
  38308. return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
  38309. }
  38310. /**
  38311. * The base implementation of `_.iteratee`.
  38312. *
  38313. * @private
  38314. * @param {*} [value=_.identity] The value to convert to an iteratee.
  38315. * @returns {Function} Returns the iteratee.
  38316. */
  38317. function baseIteratee(value) {
  38318. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  38319. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  38320. if (typeof value == 'function') {
  38321. return value;
  38322. }
  38323. if (value == null) {
  38324. return identity;
  38325. }
  38326. if (typeof value == 'object') {
  38327. return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
  38328. }
  38329. return property(value);
  38330. }
  38331. /**
  38332. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  38333. *
  38334. * @private
  38335. * @param {Object} object The object to query.
  38336. * @returns {Array} Returns the array of property names.
  38337. */
  38338. function baseKeys(object) {
  38339. if (!isPrototype(object)) {
  38340. return nativeKeys(object);
  38341. }
  38342. var result = [];
  38343. for (var key in Object(object)) {
  38344. if (hasOwnProperty.call(object, key) && key != 'constructor') {
  38345. result.push(key);
  38346. }
  38347. }
  38348. return result;
  38349. }
  38350. /**
  38351. * The base implementation of `_.matches` which doesn't clone `source`.
  38352. *
  38353. * @private
  38354. * @param {Object} source The object of property values to match.
  38355. * @returns {Function} Returns the new spec function.
  38356. */
  38357. function baseMatches(source) {
  38358. var matchData = getMatchData(source);
  38359. if (matchData.length == 1 && matchData[0][2]) {
  38360. return matchesStrictComparable(matchData[0][0], matchData[0][1]);
  38361. }
  38362. return function (object) {
  38363. return object === source || baseIsMatch(object, source, matchData);
  38364. };
  38365. }
  38366. /**
  38367. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  38368. *
  38369. * @private
  38370. * @param {string} path The path of the property to get.
  38371. * @param {*} srcValue The value to match.
  38372. * @returns {Function} Returns the new spec function.
  38373. */
  38374. function baseMatchesProperty(path, srcValue) {
  38375. if (isKey(path) && isStrictComparable(srcValue)) {
  38376. return matchesStrictComparable(toKey(path), srcValue);
  38377. }
  38378. return function (object) {
  38379. var objValue = get(object, path);
  38380. return objValue === undefined && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
  38381. };
  38382. }
  38383. /**
  38384. * A specialized version of `baseProperty` which supports deep paths.
  38385. *
  38386. * @private
  38387. * @param {Array|string} path The path of the property to get.
  38388. * @returns {Function} Returns the new accessor function.
  38389. */
  38390. function basePropertyDeep(path) {
  38391. return function (object) {
  38392. return baseGet(object, path);
  38393. };
  38394. }
  38395. /**
  38396. * The base implementation of `_.toString` which doesn't convert nullish
  38397. * values to empty strings.
  38398. *
  38399. * @private
  38400. * @param {*} value The value to process.
  38401. * @returns {string} Returns the string.
  38402. */
  38403. function baseToString(value) {
  38404. // Exit early for strings to avoid a performance hit in some environments.
  38405. if (typeof value == 'string') {
  38406. return value;
  38407. }
  38408. if (isSymbol(value)) {
  38409. return symbolToString ? symbolToString.call(value) : '';
  38410. }
  38411. var result = value + '';
  38412. return result == '0' && 1 / value == -INFINITY ? '-0' : result;
  38413. }
  38414. /**
  38415. * Casts `value` to a path array if it's not one.
  38416. *
  38417. * @private
  38418. * @param {*} value The value to inspect.
  38419. * @returns {Array} Returns the cast property path array.
  38420. */
  38421. function castPath(value) {
  38422. return isArray(value) ? value : stringToPath(value);
  38423. }
  38424. /**
  38425. * Creates a function like `_.groupBy`.
  38426. *
  38427. * @private
  38428. * @param {Function} setter The function to set accumulator values.
  38429. * @param {Function} [initializer] The accumulator object initializer.
  38430. * @returns {Function} Returns the new aggregator function.
  38431. */
  38432. function createAggregator(setter, initializer) {
  38433. return function (collection, iteratee) {
  38434. var func = isArray(collection) ? arrayAggregator : baseAggregator,
  38435. accumulator = initializer ? initializer() : {};
  38436. return func(collection, setter, baseIteratee(iteratee, 2), accumulator);
  38437. };
  38438. }
  38439. /**
  38440. * Creates a `baseEach` or `baseEachRight` function.
  38441. *
  38442. * @private
  38443. * @param {Function} eachFunc The function to iterate over a collection.
  38444. * @param {boolean} [fromRight] Specify iterating from right to left.
  38445. * @returns {Function} Returns the new base function.
  38446. */
  38447. function createBaseEach(eachFunc, fromRight) {
  38448. return function (collection, iteratee) {
  38449. if (collection == null) {
  38450. return collection;
  38451. }
  38452. if (!isArrayLike(collection)) {
  38453. return eachFunc(collection, iteratee);
  38454. }
  38455. var length = collection.length,
  38456. index = fromRight ? length : -1,
  38457. iterable = Object(collection);
  38458. while (fromRight ? index-- : ++index < length) {
  38459. if (iteratee(iterable[index], index, iterable) === false) {
  38460. break;
  38461. }
  38462. }
  38463. return collection;
  38464. };
  38465. }
  38466. /**
  38467. * Creates a base function for methods like `_.forIn` and `_.forOwn`.
  38468. *
  38469. * @private
  38470. * @param {boolean} [fromRight] Specify iterating from right to left.
  38471. * @returns {Function} Returns the new base function.
  38472. */
  38473. function createBaseFor(fromRight) {
  38474. return function (object, iteratee, keysFunc) {
  38475. var index = -1,
  38476. iterable = Object(object),
  38477. props = keysFunc(object),
  38478. length = props.length;
  38479. while (length--) {
  38480. var key = props[fromRight ? length : ++index];
  38481. if (iteratee(iterable[key], key, iterable) === false) {
  38482. break;
  38483. }
  38484. }
  38485. return object;
  38486. };
  38487. }
  38488. /**
  38489. * A specialized version of `baseIsEqualDeep` for arrays with support for
  38490. * partial deep comparisons.
  38491. *
  38492. * @private
  38493. * @param {Array} array The array to compare.
  38494. * @param {Array} other The other array to compare.
  38495. * @param {Function} equalFunc The function to determine equivalents of values.
  38496. * @param {Function} customizer The function to customize comparisons.
  38497. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
  38498. * for more details.
  38499. * @param {Object} stack Tracks traversed `array` and `other` objects.
  38500. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  38501. */
  38502. function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
  38503. var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
  38504. arrLength = array.length,
  38505. othLength = other.length;
  38506. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  38507. return false;
  38508. }
  38509. // Assume cyclic values are equal.
  38510. var stacked = stack.get(array);
  38511. if (stacked && stack.get(other)) {
  38512. return stacked == other;
  38513. }
  38514. var index = -1,
  38515. result = true,
  38516. seen = bitmask & UNORDERED_COMPARE_FLAG ? new SetCache() : undefined;
  38517. stack.set(array, other);
  38518. stack.set(other, array);
  38519. // Ignore non-index properties.
  38520. while (++index < arrLength) {
  38521. var arrValue = array[index],
  38522. othValue = other[index];
  38523. if (customizer) {
  38524. var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
  38525. }
  38526. if (compared !== undefined) {
  38527. if (compared) {
  38528. continue;
  38529. }
  38530. result = false;
  38531. break;
  38532. }
  38533. // Recursively compare arrays (susceptible to call stack limits).
  38534. if (seen) {
  38535. if (!arraySome(other, function (othValue, othIndex) {
  38536. if (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
  38537. return seen.add(othIndex);
  38538. }
  38539. })) {
  38540. result = false;
  38541. break;
  38542. }
  38543. } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
  38544. result = false;
  38545. break;
  38546. }
  38547. }
  38548. stack['delete'](array);
  38549. stack['delete'](other);
  38550. return result;
  38551. }
  38552. /**
  38553. * A specialized version of `baseIsEqualDeep` for comparing objects of
  38554. * the same `toStringTag`.
  38555. *
  38556. * **Note:** This function only supports comparing values with tags of
  38557. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  38558. *
  38559. * @private
  38560. * @param {Object} object The object to compare.
  38561. * @param {Object} other The other object to compare.
  38562. * @param {string} tag The `toStringTag` of the objects to compare.
  38563. * @param {Function} equalFunc The function to determine equivalents of values.
  38564. * @param {Function} customizer The function to customize comparisons.
  38565. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
  38566. * for more details.
  38567. * @param {Object} stack Tracks traversed `object` and `other` objects.
  38568. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  38569. */
  38570. function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
  38571. switch (tag) {
  38572. case dataViewTag:
  38573. if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
  38574. return false;
  38575. }
  38576. object = object.buffer;
  38577. other = other.buffer;
  38578. case arrayBufferTag:
  38579. if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
  38580. return false;
  38581. }
  38582. return true;
  38583. case boolTag:
  38584. case dateTag:
  38585. case numberTag:
  38586. // Coerce booleans to `1` or `0` and dates to milliseconds.
  38587. // Invalid dates are coerced to `NaN`.
  38588. return eq(+object, +other);
  38589. case errorTag:
  38590. return object.name == other.name && object.message == other.message;
  38591. case regexpTag:
  38592. case stringTag:
  38593. // Coerce regexes to strings and treat strings, primitives and objects,
  38594. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  38595. // for more details.
  38596. return object == other + '';
  38597. case mapTag:
  38598. var convert = mapToArray;
  38599. case setTag:
  38600. var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
  38601. convert || (convert = setToArray);
  38602. if (object.size != other.size && !isPartial) {
  38603. return false;
  38604. }
  38605. // Assume cyclic values are equal.
  38606. var stacked = stack.get(object);
  38607. if (stacked) {
  38608. return stacked == other;
  38609. }
  38610. bitmask |= UNORDERED_COMPARE_FLAG;
  38611. // Recursively compare objects (susceptible to call stack limits).
  38612. stack.set(object, other);
  38613. var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
  38614. stack['delete'](object);
  38615. return result;
  38616. case symbolTag:
  38617. if (symbolValueOf) {
  38618. return symbolValueOf.call(object) == symbolValueOf.call(other);
  38619. }
  38620. }
  38621. return false;
  38622. }
  38623. /**
  38624. * A specialized version of `baseIsEqualDeep` for objects with support for
  38625. * partial deep comparisons.
  38626. *
  38627. * @private
  38628. * @param {Object} object The object to compare.
  38629. * @param {Object} other The other object to compare.
  38630. * @param {Function} equalFunc The function to determine equivalents of values.
  38631. * @param {Function} customizer The function to customize comparisons.
  38632. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
  38633. * for more details.
  38634. * @param {Object} stack Tracks traversed `object` and `other` objects.
  38635. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  38636. */
  38637. function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
  38638. var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
  38639. objProps = keys(object),
  38640. objLength = objProps.length,
  38641. othProps = keys(other),
  38642. othLength = othProps.length;
  38643. if (objLength != othLength && !isPartial) {
  38644. return false;
  38645. }
  38646. var index = objLength;
  38647. while (index--) {
  38648. var key = objProps[index];
  38649. if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
  38650. return false;
  38651. }
  38652. }
  38653. // Assume cyclic values are equal.
  38654. var stacked = stack.get(object);
  38655. if (stacked && stack.get(other)) {
  38656. return stacked == other;
  38657. }
  38658. var result = true;
  38659. stack.set(object, other);
  38660. stack.set(other, object);
  38661. var skipCtor = isPartial;
  38662. while (++index < objLength) {
  38663. key = objProps[index];
  38664. var objValue = object[key],
  38665. othValue = other[key];
  38666. if (customizer) {
  38667. var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
  38668. }
  38669. // Recursively compare objects (susceptible to call stack limits).
  38670. if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack) : compared)) {
  38671. result = false;
  38672. break;
  38673. }
  38674. skipCtor || (skipCtor = key == 'constructor');
  38675. }
  38676. if (result && !skipCtor) {
  38677. var objCtor = object.constructor,
  38678. othCtor = other.constructor;
  38679. // Non `Object` object instances with different constructors are not equal.
  38680. if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  38681. result = false;
  38682. }
  38683. }
  38684. stack['delete'](object);
  38685. stack['delete'](other);
  38686. return result;
  38687. }
  38688. /**
  38689. * Gets the data for `map`.
  38690. *
  38691. * @private
  38692. * @param {Object} map The map to query.
  38693. * @param {string} key The reference key.
  38694. * @returns {*} Returns the map data.
  38695. */
  38696. function getMapData(map, key) {
  38697. var data = map.__data__;
  38698. return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
  38699. }
  38700. /**
  38701. * Gets the property names, values, and compare flags of `object`.
  38702. *
  38703. * @private
  38704. * @param {Object} object The object to query.
  38705. * @returns {Array} Returns the match data of `object`.
  38706. */
  38707. function getMatchData(object) {
  38708. var result = keys(object),
  38709. length = result.length;
  38710. while (length--) {
  38711. var key = result[length],
  38712. value = object[key];
  38713. result[length] = [key, value, isStrictComparable(value)];
  38714. }
  38715. return result;
  38716. }
  38717. /**
  38718. * Gets the native function at `key` of `object`.
  38719. *
  38720. * @private
  38721. * @param {Object} object The object to query.
  38722. * @param {string} key The key of the method to get.
  38723. * @returns {*} Returns the function if it's native, else `undefined`.
  38724. */
  38725. function getNative(object, key) {
  38726. var value = getValue(object, key);
  38727. return baseIsNative(value) ? value : undefined;
  38728. }
  38729. /**
  38730. * Gets the `toStringTag` of `value`.
  38731. *
  38732. * @private
  38733. * @param {*} value The value to query.
  38734. * @returns {string} Returns the `toStringTag`.
  38735. */
  38736. var getTag = baseGetTag;
  38737. // Fallback for data views, maps, sets, and weak maps in IE 11,
  38738. // for data views in Edge < 14, and promises in Node.js.
  38739. if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) {
  38740. getTag = function (value) {
  38741. var result = objectToString.call(value),
  38742. Ctor = result == objectTag ? value.constructor : undefined,
  38743. ctorString = Ctor ? toSource(Ctor) : undefined;
  38744. if (ctorString) {
  38745. switch (ctorString) {
  38746. case dataViewCtorString:
  38747. return dataViewTag;
  38748. case mapCtorString:
  38749. return mapTag;
  38750. case promiseCtorString:
  38751. return promiseTag;
  38752. case setCtorString:
  38753. return setTag;
  38754. case weakMapCtorString:
  38755. return weakMapTag;
  38756. }
  38757. }
  38758. return result;
  38759. };
  38760. }
  38761. /**
  38762. * Checks if `path` exists on `object`.
  38763. *
  38764. * @private
  38765. * @param {Object} object The object to query.
  38766. * @param {Array|string} path The path to check.
  38767. * @param {Function} hasFunc The function to check properties.
  38768. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  38769. */
  38770. function hasPath(object, path, hasFunc) {
  38771. path = isKey(path, object) ? [path] : castPath(path);
  38772. var result,
  38773. index = -1,
  38774. length = path.length;
  38775. while (++index < length) {
  38776. var key = toKey(path[index]);
  38777. if (!(result = object != null && hasFunc(object, key))) {
  38778. break;
  38779. }
  38780. object = object[key];
  38781. }
  38782. if (result) {
  38783. return result;
  38784. }
  38785. var length = object ? object.length : 0;
  38786. return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object));
  38787. }
  38788. /**
  38789. * Checks if `value` is a valid array-like index.
  38790. *
  38791. * @private
  38792. * @param {*} value The value to check.
  38793. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  38794. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  38795. */
  38796. function isIndex(value, length) {
  38797. length = length == null ? MAX_SAFE_INTEGER : length;
  38798. return !!length && (typeof value == 'number' || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
  38799. }
  38800. /**
  38801. * Checks if `value` is a property name and not a property path.
  38802. *
  38803. * @private
  38804. * @param {*} value The value to check.
  38805. * @param {Object} [object] The object to query keys on.
  38806. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  38807. */
  38808. function isKey(value, object) {
  38809. if (isArray(value)) {
  38810. return false;
  38811. }
  38812. var type = typeof value;
  38813. if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) {
  38814. return true;
  38815. }
  38816. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
  38817. }
  38818. /**
  38819. * Checks if `value` is suitable for use as unique object key.
  38820. *
  38821. * @private
  38822. * @param {*} value The value to check.
  38823. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  38824. */
  38825. function isKeyable(value) {
  38826. var type = typeof value;
  38827. return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
  38828. }
  38829. /**
  38830. * Checks if `func` has its source masked.
  38831. *
  38832. * @private
  38833. * @param {Function} func The function to check.
  38834. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  38835. */
  38836. function isMasked(func) {
  38837. return !!maskSrcKey && maskSrcKey in func;
  38838. }
  38839. /**
  38840. * Checks if `value` is likely a prototype object.
  38841. *
  38842. * @private
  38843. * @param {*} value The value to check.
  38844. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  38845. */
  38846. function isPrototype(value) {
  38847. var Ctor = value && value.constructor,
  38848. proto = typeof Ctor == 'function' && Ctor.prototype || objectProto;
  38849. return value === proto;
  38850. }
  38851. /**
  38852. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  38853. *
  38854. * @private
  38855. * @param {*} value The value to check.
  38856. * @returns {boolean} Returns `true` if `value` if suitable for strict
  38857. * equality comparisons, else `false`.
  38858. */
  38859. function isStrictComparable(value) {
  38860. return value === value && !isObject(value);
  38861. }
  38862. /**
  38863. * A specialized version of `matchesProperty` for source values suitable
  38864. * for strict equality comparisons, i.e. `===`.
  38865. *
  38866. * @private
  38867. * @param {string} key The key of the property to get.
  38868. * @param {*} srcValue The value to match.
  38869. * @returns {Function} Returns the new spec function.
  38870. */
  38871. function matchesStrictComparable(key, srcValue) {
  38872. return function (object) {
  38873. if (object == null) {
  38874. return false;
  38875. }
  38876. return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
  38877. };
  38878. }
  38879. /**
  38880. * Converts `string` to a property path array.
  38881. *
  38882. * @private
  38883. * @param {string} string The string to convert.
  38884. * @returns {Array} Returns the property path array.
  38885. */
  38886. var stringToPath = memoize(function (string) {
  38887. string = toString(string);
  38888. var result = [];
  38889. if (reLeadingDot.test(string)) {
  38890. result.push('');
  38891. }
  38892. string.replace(rePropName, function (match, number, quote, string) {
  38893. result.push(quote ? string.replace(reEscapeChar, '$1') : number || match);
  38894. });
  38895. return result;
  38896. });
  38897. /**
  38898. * Converts `value` to a string key if it's not a string or symbol.
  38899. *
  38900. * @private
  38901. * @param {*} value The value to inspect.
  38902. * @returns {string|symbol} Returns the key.
  38903. */
  38904. function toKey(value) {
  38905. if (typeof value == 'string' || isSymbol(value)) {
  38906. return value;
  38907. }
  38908. var result = value + '';
  38909. return result == '0' && 1 / value == -INFINITY ? '-0' : result;
  38910. }
  38911. /**
  38912. * Converts `func` to its source code.
  38913. *
  38914. * @private
  38915. * @param {Function} func The function to process.
  38916. * @returns {string} Returns the source code.
  38917. */
  38918. function toSource(func) {
  38919. if (func != null) {
  38920. try {
  38921. return funcToString.call(func);
  38922. } catch (e) {}
  38923. try {
  38924. return func + '';
  38925. } catch (e) {}
  38926. }
  38927. return '';
  38928. }
  38929. /**
  38930. * Creates an object composed of keys generated from the results of running
  38931. * each element of `collection` thru `iteratee`. The order of grouped values
  38932. * is determined by the order they occur in `collection`. The corresponding
  38933. * value of each key is an array of elements responsible for generating the
  38934. * key. The iteratee is invoked with one argument: (value).
  38935. *
  38936. * @static
  38937. * @memberOf _
  38938. * @since 0.1.0
  38939. * @category Collection
  38940. * @param {Array|Object} collection The collection to iterate over.
  38941. * @param {Function} [iteratee=_.identity]
  38942. * The iteratee to transform keys.
  38943. * @returns {Object} Returns the composed aggregate object.
  38944. * @example
  38945. *
  38946. * _.groupBy([6.1, 4.2, 6.3], Math.floor);
  38947. * // => { '4': [4.2], '6': [6.1, 6.3] }
  38948. *
  38949. * // The `_.property` iteratee shorthand.
  38950. * _.groupBy(['one', 'two', 'three'], 'length');
  38951. * // => { '3': ['one', 'two'], '5': ['three'] }
  38952. */
  38953. var groupBy = createAggregator(function (result, value, key) {
  38954. if (hasOwnProperty.call(result, key)) {
  38955. result[key].push(value);
  38956. } else {
  38957. result[key] = [value];
  38958. }
  38959. });
  38960. /**
  38961. * Creates a function that memoizes the result of `func`. If `resolver` is
  38962. * provided, it determines the cache key for storing the result based on the
  38963. * arguments provided to the memoized function. By default, the first argument
  38964. * provided to the memoized function is used as the map cache key. The `func`
  38965. * is invoked with the `this` binding of the memoized function.
  38966. *
  38967. * **Note:** The cache is exposed as the `cache` property on the memoized
  38968. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  38969. * constructor with one whose instances implement the
  38970. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  38971. * method interface of `delete`, `get`, `has`, and `set`.
  38972. *
  38973. * @static
  38974. * @memberOf _
  38975. * @since 0.1.0
  38976. * @category Function
  38977. * @param {Function} func The function to have its output memoized.
  38978. * @param {Function} [resolver] The function to resolve the cache key.
  38979. * @returns {Function} Returns the new memoized function.
  38980. * @example
  38981. *
  38982. * var object = { 'a': 1, 'b': 2 };
  38983. * var other = { 'c': 3, 'd': 4 };
  38984. *
  38985. * var values = _.memoize(_.values);
  38986. * values(object);
  38987. * // => [1, 2]
  38988. *
  38989. * values(other);
  38990. * // => [3, 4]
  38991. *
  38992. * object.a = 2;
  38993. * values(object);
  38994. * // => [1, 2]
  38995. *
  38996. * // Modify the result cache.
  38997. * values.cache.set(object, ['a', 'b']);
  38998. * values(object);
  38999. * // => ['a', 'b']
  39000. *
  39001. * // Replace `_.memoize.Cache`.
  39002. * _.memoize.Cache = WeakMap;
  39003. */
  39004. function memoize(func, resolver) {
  39005. if (typeof func != 'function' || resolver && typeof resolver != 'function') {
  39006. throw new TypeError(FUNC_ERROR_TEXT);
  39007. }
  39008. var memoized = function () {
  39009. var args = arguments,
  39010. key = resolver ? resolver.apply(this, args) : args[0],
  39011. cache = memoized.cache;
  39012. if (cache.has(key)) {
  39013. return cache.get(key);
  39014. }
  39015. var result = func.apply(this, args);
  39016. memoized.cache = cache.set(key, result);
  39017. return result;
  39018. };
  39019. memoized.cache = new (memoize.Cache || MapCache)();
  39020. return memoized;
  39021. }
  39022. // Assign cache to `_.memoize`.
  39023. memoize.Cache = MapCache;
  39024. /**
  39025. * Performs a
  39026. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  39027. * comparison between two values to determine if they are equivalent.
  39028. *
  39029. * @static
  39030. * @memberOf _
  39031. * @since 4.0.0
  39032. * @category Lang
  39033. * @param {*} value The value to compare.
  39034. * @param {*} other The other value to compare.
  39035. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  39036. * @example
  39037. *
  39038. * var object = { 'a': 1 };
  39039. * var other = { 'a': 1 };
  39040. *
  39041. * _.eq(object, object);
  39042. * // => true
  39043. *
  39044. * _.eq(object, other);
  39045. * // => false
  39046. *
  39047. * _.eq('a', 'a');
  39048. * // => true
  39049. *
  39050. * _.eq('a', Object('a'));
  39051. * // => false
  39052. *
  39053. * _.eq(NaN, NaN);
  39054. * // => true
  39055. */
  39056. function eq(value, other) {
  39057. return value === other || value !== value && other !== other;
  39058. }
  39059. /**
  39060. * Checks if `value` is likely an `arguments` object.
  39061. *
  39062. * @static
  39063. * @memberOf _
  39064. * @since 0.1.0
  39065. * @category Lang
  39066. * @param {*} value The value to check.
  39067. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  39068. * else `false`.
  39069. * @example
  39070. *
  39071. * _.isArguments(function() { return arguments; }());
  39072. * // => true
  39073. *
  39074. * _.isArguments([1, 2, 3]);
  39075. * // => false
  39076. */
  39077. function isArguments(value) {
  39078. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  39079. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
  39080. }
  39081. /**
  39082. * Checks if `value` is classified as an `Array` object.
  39083. *
  39084. * @static
  39085. * @memberOf _
  39086. * @since 0.1.0
  39087. * @category Lang
  39088. * @param {*} value The value to check.
  39089. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  39090. * @example
  39091. *
  39092. * _.isArray([1, 2, 3]);
  39093. * // => true
  39094. *
  39095. * _.isArray(document.body.children);
  39096. * // => false
  39097. *
  39098. * _.isArray('abc');
  39099. * // => false
  39100. *
  39101. * _.isArray(_.noop);
  39102. * // => false
  39103. */
  39104. var isArray = Array.isArray;
  39105. /**
  39106. * Checks if `value` is array-like. A value is considered array-like if it's
  39107. * not a function and has a `value.length` that's an integer greater than or
  39108. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  39109. *
  39110. * @static
  39111. * @memberOf _
  39112. * @since 4.0.0
  39113. * @category Lang
  39114. * @param {*} value The value to check.
  39115. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  39116. * @example
  39117. *
  39118. * _.isArrayLike([1, 2, 3]);
  39119. * // => true
  39120. *
  39121. * _.isArrayLike(document.body.children);
  39122. * // => true
  39123. *
  39124. * _.isArrayLike('abc');
  39125. * // => true
  39126. *
  39127. * _.isArrayLike(_.noop);
  39128. * // => false
  39129. */
  39130. function isArrayLike(value) {
  39131. return value != null && isLength(value.length) && !isFunction(value);
  39132. }
  39133. /**
  39134. * This method is like `_.isArrayLike` except that it also checks if `value`
  39135. * is an object.
  39136. *
  39137. * @static
  39138. * @memberOf _
  39139. * @since 4.0.0
  39140. * @category Lang
  39141. * @param {*} value The value to check.
  39142. * @returns {boolean} Returns `true` if `value` is an array-like object,
  39143. * else `false`.
  39144. * @example
  39145. *
  39146. * _.isArrayLikeObject([1, 2, 3]);
  39147. * // => true
  39148. *
  39149. * _.isArrayLikeObject(document.body.children);
  39150. * // => true
  39151. *
  39152. * _.isArrayLikeObject('abc');
  39153. * // => false
  39154. *
  39155. * _.isArrayLikeObject(_.noop);
  39156. * // => false
  39157. */
  39158. function isArrayLikeObject(value) {
  39159. return isObjectLike(value) && isArrayLike(value);
  39160. }
  39161. /**
  39162. * Checks if `value` is classified as a `Function` object.
  39163. *
  39164. * @static
  39165. * @memberOf _
  39166. * @since 0.1.0
  39167. * @category Lang
  39168. * @param {*} value The value to check.
  39169. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  39170. * @example
  39171. *
  39172. * _.isFunction(_);
  39173. * // => true
  39174. *
  39175. * _.isFunction(/abc/);
  39176. * // => false
  39177. */
  39178. function isFunction(value) {
  39179. // The use of `Object#toString` avoids issues with the `typeof` operator
  39180. // in Safari 8-9 which returns 'object' for typed array and other constructors.
  39181. var tag = isObject(value) ? objectToString.call(value) : '';
  39182. return tag == funcTag || tag == genTag;
  39183. }
  39184. /**
  39185. * Checks if `value` is a valid array-like length.
  39186. *
  39187. * **Note:** This method is loosely based on
  39188. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  39189. *
  39190. * @static
  39191. * @memberOf _
  39192. * @since 4.0.0
  39193. * @category Lang
  39194. * @param {*} value The value to check.
  39195. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  39196. * @example
  39197. *
  39198. * _.isLength(3);
  39199. * // => true
  39200. *
  39201. * _.isLength(Number.MIN_VALUE);
  39202. * // => false
  39203. *
  39204. * _.isLength(Infinity);
  39205. * // => false
  39206. *
  39207. * _.isLength('3');
  39208. * // => false
  39209. */
  39210. function isLength(value) {
  39211. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  39212. }
  39213. /**
  39214. * Checks if `value` is the
  39215. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  39216. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  39217. *
  39218. * @static
  39219. * @memberOf _
  39220. * @since 0.1.0
  39221. * @category Lang
  39222. * @param {*} value The value to check.
  39223. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  39224. * @example
  39225. *
  39226. * _.isObject({});
  39227. * // => true
  39228. *
  39229. * _.isObject([1, 2, 3]);
  39230. * // => true
  39231. *
  39232. * _.isObject(_.noop);
  39233. * // => true
  39234. *
  39235. * _.isObject(null);
  39236. * // => false
  39237. */
  39238. function isObject(value) {
  39239. var type = typeof value;
  39240. return !!value && (type == 'object' || type == 'function');
  39241. }
  39242. /**
  39243. * Checks if `value` is object-like. A value is object-like if it's not `null`
  39244. * and has a `typeof` result of "object".
  39245. *
  39246. * @static
  39247. * @memberOf _
  39248. * @since 4.0.0
  39249. * @category Lang
  39250. * @param {*} value The value to check.
  39251. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  39252. * @example
  39253. *
  39254. * _.isObjectLike({});
  39255. * // => true
  39256. *
  39257. * _.isObjectLike([1, 2, 3]);
  39258. * // => true
  39259. *
  39260. * _.isObjectLike(_.noop);
  39261. * // => false
  39262. *
  39263. * _.isObjectLike(null);
  39264. * // => false
  39265. */
  39266. function isObjectLike(value) {
  39267. return !!value && typeof value == 'object';
  39268. }
  39269. /**
  39270. * Checks if `value` is classified as a `Symbol` primitive or object.
  39271. *
  39272. * @static
  39273. * @memberOf _
  39274. * @since 4.0.0
  39275. * @category Lang
  39276. * @param {*} value The value to check.
  39277. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  39278. * @example
  39279. *
  39280. * _.isSymbol(Symbol.iterator);
  39281. * // => true
  39282. *
  39283. * _.isSymbol('abc');
  39284. * // => false
  39285. */
  39286. function isSymbol(value) {
  39287. return typeof value == 'symbol' || isObjectLike(value) && objectToString.call(value) == symbolTag;
  39288. }
  39289. /**
  39290. * Checks if `value` is classified as a typed array.
  39291. *
  39292. * @static
  39293. * @memberOf _
  39294. * @since 3.0.0
  39295. * @category Lang
  39296. * @param {*} value The value to check.
  39297. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  39298. * @example
  39299. *
  39300. * _.isTypedArray(new Uint8Array);
  39301. * // => true
  39302. *
  39303. * _.isTypedArray([]);
  39304. * // => false
  39305. */
  39306. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  39307. /**
  39308. * Converts `value` to a string. An empty string is returned for `null`
  39309. * and `undefined` values. The sign of `-0` is preserved.
  39310. *
  39311. * @static
  39312. * @memberOf _
  39313. * @since 4.0.0
  39314. * @category Lang
  39315. * @param {*} value The value to process.
  39316. * @returns {string} Returns the string.
  39317. * @example
  39318. *
  39319. * _.toString(null);
  39320. * // => ''
  39321. *
  39322. * _.toString(-0);
  39323. * // => '-0'
  39324. *
  39325. * _.toString([1, 2, 3]);
  39326. * // => '1,2,3'
  39327. */
  39328. function toString(value) {
  39329. return value == null ? '' : baseToString(value);
  39330. }
  39331. /**
  39332. * Gets the value at `path` of `object`. If the resolved value is
  39333. * `undefined`, the `defaultValue` is returned in its place.
  39334. *
  39335. * @static
  39336. * @memberOf _
  39337. * @since 3.7.0
  39338. * @category Object
  39339. * @param {Object} object The object to query.
  39340. * @param {Array|string} path The path of the property to get.
  39341. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  39342. * @returns {*} Returns the resolved value.
  39343. * @example
  39344. *
  39345. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  39346. *
  39347. * _.get(object, 'a[0].b.c');
  39348. * // => 3
  39349. *
  39350. * _.get(object, ['a', '0', 'b', 'c']);
  39351. * // => 3
  39352. *
  39353. * _.get(object, 'a.b.c', 'default');
  39354. * // => 'default'
  39355. */
  39356. function get(object, path, defaultValue) {
  39357. var result = object == null ? undefined : baseGet(object, path);
  39358. return result === undefined ? defaultValue : result;
  39359. }
  39360. /**
  39361. * Checks if `path` is a direct or inherited property of `object`.
  39362. *
  39363. * @static
  39364. * @memberOf _
  39365. * @since 4.0.0
  39366. * @category Object
  39367. * @param {Object} object The object to query.
  39368. * @param {Array|string} path The path to check.
  39369. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  39370. * @example
  39371. *
  39372. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  39373. *
  39374. * _.hasIn(object, 'a');
  39375. * // => true
  39376. *
  39377. * _.hasIn(object, 'a.b');
  39378. * // => true
  39379. *
  39380. * _.hasIn(object, ['a', 'b']);
  39381. * // => true
  39382. *
  39383. * _.hasIn(object, 'b');
  39384. * // => false
  39385. */
  39386. function hasIn(object, path) {
  39387. return object != null && hasPath(object, path, baseHasIn);
  39388. }
  39389. /**
  39390. * Creates an array of the own enumerable property names of `object`.
  39391. *
  39392. * **Note:** Non-object values are coerced to objects. See the
  39393. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  39394. * for more details.
  39395. *
  39396. * @static
  39397. * @since 0.1.0
  39398. * @memberOf _
  39399. * @category Object
  39400. * @param {Object} object The object to query.
  39401. * @returns {Array} Returns the array of property names.
  39402. * @example
  39403. *
  39404. * function Foo() {
  39405. * this.a = 1;
  39406. * this.b = 2;
  39407. * }
  39408. *
  39409. * Foo.prototype.c = 3;
  39410. *
  39411. * _.keys(new Foo);
  39412. * // => ['a', 'b'] (iteration order is not guaranteed)
  39413. *
  39414. * _.keys('hi');
  39415. * // => ['0', '1']
  39416. */
  39417. function keys(object) {
  39418. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  39419. }
  39420. /**
  39421. * This method returns the first argument it receives.
  39422. *
  39423. * @static
  39424. * @since 0.1.0
  39425. * @memberOf _
  39426. * @category Util
  39427. * @param {*} value Any value.
  39428. * @returns {*} Returns `value`.
  39429. * @example
  39430. *
  39431. * var object = { 'a': 1 };
  39432. *
  39433. * console.log(_.identity(object) === object);
  39434. * // => true
  39435. */
  39436. function identity(value) {
  39437. return value;
  39438. }
  39439. /**
  39440. * Creates a function that returns the value at `path` of a given object.
  39441. *
  39442. * @static
  39443. * @memberOf _
  39444. * @since 2.4.0
  39445. * @category Util
  39446. * @param {Array|string} path The path of the property to get.
  39447. * @returns {Function} Returns the new accessor function.
  39448. * @example
  39449. *
  39450. * var objects = [
  39451. * { 'a': { 'b': 2 } },
  39452. * { 'a': { 'b': 1 } }
  39453. * ];
  39454. *
  39455. * _.map(objects, _.property('a.b'));
  39456. * // => [2, 1]
  39457. *
  39458. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  39459. * // => [1, 2]
  39460. */
  39461. function property(path) {
  39462. return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
  39463. }
  39464. module.exports = groupBy;
  39465. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  39466. },{}],283:[function(require,module,exports){
  39467. "use strict";
  39468. /**
  39469. * lodash 3.0.3 (Custom Build) <https://lodash.com/>
  39470. * Build: `lodash modularize exports="npm" -o ./`
  39471. * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
  39472. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  39473. * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  39474. * Available under MIT license <https://lodash.com/license>
  39475. */
  39476. /** `Object#toString` result references. */
  39477. var boolTag = '[object Boolean]';
  39478. /** Used for built-in method references. */
  39479. var objectProto = Object.prototype;
  39480. /**
  39481. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  39482. * of values.
  39483. */
  39484. var objectToString = objectProto.toString;
  39485. /**
  39486. * Checks if `value` is classified as a boolean primitive or object.
  39487. *
  39488. * @static
  39489. * @memberOf _
  39490. * @category Lang
  39491. * @param {*} value The value to check.
  39492. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  39493. * @example
  39494. *
  39495. * _.isBoolean(false);
  39496. * // => true
  39497. *
  39498. * _.isBoolean(null);
  39499. * // => false
  39500. */
  39501. function isBoolean(value) {
  39502. return value === true || value === false || isObjectLike(value) && objectToString.call(value) == boolTag;
  39503. }
  39504. /**
  39505. * Checks if `value` is object-like. A value is object-like if it's not `null`
  39506. * and has a `typeof` result of "object".
  39507. *
  39508. * @static
  39509. * @memberOf _
  39510. * @category Lang
  39511. * @param {*} value The value to check.
  39512. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  39513. * @example
  39514. *
  39515. * _.isObjectLike({});
  39516. * // => true
  39517. *
  39518. * _.isObjectLike([1, 2, 3]);
  39519. * // => true
  39520. *
  39521. * _.isObjectLike(_.noop);
  39522. * // => false
  39523. *
  39524. * _.isObjectLike(null);
  39525. * // => false
  39526. */
  39527. function isObjectLike(value) {
  39528. return !!value && typeof value == 'object';
  39529. }
  39530. module.exports = isBoolean;
  39531. },{}],284:[function(require,module,exports){
  39532. (function (global){(function (){
  39533. "use strict";
  39534. /**
  39535. * Lodash (Custom Build) <https://lodash.com/>
  39536. * Build: `lodash modularize exports="npm" -o ./`
  39537. * Copyright JS Foundation and other contributors <https://js.foundation/>
  39538. * Released under MIT license <https://lodash.com/license>
  39539. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  39540. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  39541. */
  39542. /** Used as the size to enable large array optimizations. */
  39543. var LARGE_ARRAY_SIZE = 200;
  39544. /** Used to stand-in for `undefined` hash values. */
  39545. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  39546. /** Used to compose bitmasks for value comparisons. */
  39547. var COMPARE_PARTIAL_FLAG = 1,
  39548. COMPARE_UNORDERED_FLAG = 2;
  39549. /** Used as references for various `Number` constants. */
  39550. var MAX_SAFE_INTEGER = 9007199254740991;
  39551. /** `Object#toString` result references. */
  39552. var argsTag = '[object Arguments]',
  39553. arrayTag = '[object Array]',
  39554. asyncTag = '[object AsyncFunction]',
  39555. boolTag = '[object Boolean]',
  39556. dateTag = '[object Date]',
  39557. errorTag = '[object Error]',
  39558. funcTag = '[object Function]',
  39559. genTag = '[object GeneratorFunction]',
  39560. mapTag = '[object Map]',
  39561. numberTag = '[object Number]',
  39562. nullTag = '[object Null]',
  39563. objectTag = '[object Object]',
  39564. promiseTag = '[object Promise]',
  39565. proxyTag = '[object Proxy]',
  39566. regexpTag = '[object RegExp]',
  39567. setTag = '[object Set]',
  39568. stringTag = '[object String]',
  39569. symbolTag = '[object Symbol]',
  39570. undefinedTag = '[object Undefined]',
  39571. weakMapTag = '[object WeakMap]';
  39572. var arrayBufferTag = '[object ArrayBuffer]',
  39573. dataViewTag = '[object DataView]',
  39574. float32Tag = '[object Float32Array]',
  39575. float64Tag = '[object Float64Array]',
  39576. int8Tag = '[object Int8Array]',
  39577. int16Tag = '[object Int16Array]',
  39578. int32Tag = '[object Int32Array]',
  39579. uint8Tag = '[object Uint8Array]',
  39580. uint8ClampedTag = '[object Uint8ClampedArray]',
  39581. uint16Tag = '[object Uint16Array]',
  39582. uint32Tag = '[object Uint32Array]';
  39583. /**
  39584. * Used to match `RegExp`
  39585. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  39586. */
  39587. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  39588. /** Used to detect host constructors (Safari). */
  39589. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  39590. /** Used to detect unsigned integer values. */
  39591. var reIsUint = /^(?:0|[1-9]\d*)$/;
  39592. /** Used to identify `toStringTag` values of typed arrays. */
  39593. var typedArrayTags = {};
  39594. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
  39595. typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
  39596. /** Detect free variable `global` from Node.js. */
  39597. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  39598. /** Detect free variable `self`. */
  39599. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  39600. /** Used as a reference to the global object. */
  39601. var root = freeGlobal || freeSelf || Function('return this')();
  39602. /** Detect free variable `exports`. */
  39603. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  39604. /** Detect free variable `module`. */
  39605. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  39606. /** Detect the popular CommonJS extension `module.exports`. */
  39607. var moduleExports = freeModule && freeModule.exports === freeExports;
  39608. /** Detect free variable `process` from Node.js. */
  39609. var freeProcess = moduleExports && freeGlobal.process;
  39610. /** Used to access faster Node.js helpers. */
  39611. var nodeUtil = function () {
  39612. try {
  39613. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  39614. } catch (e) {}
  39615. }();
  39616. /* Node.js helper references. */
  39617. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  39618. /**
  39619. * A specialized version of `_.filter` for arrays without support for
  39620. * iteratee shorthands.
  39621. *
  39622. * @private
  39623. * @param {Array} [array] The array to iterate over.
  39624. * @param {Function} predicate The function invoked per iteration.
  39625. * @returns {Array} Returns the new filtered array.
  39626. */
  39627. function arrayFilter(array, predicate) {
  39628. var index = -1,
  39629. length = array == null ? 0 : array.length,
  39630. resIndex = 0,
  39631. result = [];
  39632. while (++index < length) {
  39633. var value = array[index];
  39634. if (predicate(value, index, array)) {
  39635. result[resIndex++] = value;
  39636. }
  39637. }
  39638. return result;
  39639. }
  39640. /**
  39641. * Appends the elements of `values` to `array`.
  39642. *
  39643. * @private
  39644. * @param {Array} array The array to modify.
  39645. * @param {Array} values The values to append.
  39646. * @returns {Array} Returns `array`.
  39647. */
  39648. function arrayPush(array, values) {
  39649. var index = -1,
  39650. length = values.length,
  39651. offset = array.length;
  39652. while (++index < length) {
  39653. array[offset + index] = values[index];
  39654. }
  39655. return array;
  39656. }
  39657. /**
  39658. * A specialized version of `_.some` for arrays without support for iteratee
  39659. * shorthands.
  39660. *
  39661. * @private
  39662. * @param {Array} [array] The array to iterate over.
  39663. * @param {Function} predicate The function invoked per iteration.
  39664. * @returns {boolean} Returns `true` if any element passes the predicate check,
  39665. * else `false`.
  39666. */
  39667. function arraySome(array, predicate) {
  39668. var index = -1,
  39669. length = array == null ? 0 : array.length;
  39670. while (++index < length) {
  39671. if (predicate(array[index], index, array)) {
  39672. return true;
  39673. }
  39674. }
  39675. return false;
  39676. }
  39677. /**
  39678. * The base implementation of `_.times` without support for iteratee shorthands
  39679. * or max array length checks.
  39680. *
  39681. * @private
  39682. * @param {number} n The number of times to invoke `iteratee`.
  39683. * @param {Function} iteratee The function invoked per iteration.
  39684. * @returns {Array} Returns the array of results.
  39685. */
  39686. function baseTimes(n, iteratee) {
  39687. var index = -1,
  39688. result = Array(n);
  39689. while (++index < n) {
  39690. result[index] = iteratee(index);
  39691. }
  39692. return result;
  39693. }
  39694. /**
  39695. * The base implementation of `_.unary` without support for storing metadata.
  39696. *
  39697. * @private
  39698. * @param {Function} func The function to cap arguments for.
  39699. * @returns {Function} Returns the new capped function.
  39700. */
  39701. function baseUnary(func) {
  39702. return function (value) {
  39703. return func(value);
  39704. };
  39705. }
  39706. /**
  39707. * Checks if a `cache` value for `key` exists.
  39708. *
  39709. * @private
  39710. * @param {Object} cache The cache to query.
  39711. * @param {string} key The key of the entry to check.
  39712. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  39713. */
  39714. function cacheHas(cache, key) {
  39715. return cache.has(key);
  39716. }
  39717. /**
  39718. * Gets the value at `key` of `object`.
  39719. *
  39720. * @private
  39721. * @param {Object} [object] The object to query.
  39722. * @param {string} key The key of the property to get.
  39723. * @returns {*} Returns the property value.
  39724. */
  39725. function getValue(object, key) {
  39726. return object == null ? undefined : object[key];
  39727. }
  39728. /**
  39729. * Converts `map` to its key-value pairs.
  39730. *
  39731. * @private
  39732. * @param {Object} map The map to convert.
  39733. * @returns {Array} Returns the key-value pairs.
  39734. */
  39735. function mapToArray(map) {
  39736. var index = -1,
  39737. result = Array(map.size);
  39738. map.forEach(function (value, key) {
  39739. result[++index] = [key, value];
  39740. });
  39741. return result;
  39742. }
  39743. /**
  39744. * Creates a unary function that invokes `func` with its argument transformed.
  39745. *
  39746. * @private
  39747. * @param {Function} func The function to wrap.
  39748. * @param {Function} transform The argument transform.
  39749. * @returns {Function} Returns the new function.
  39750. */
  39751. function overArg(func, transform) {
  39752. return function (arg) {
  39753. return func(transform(arg));
  39754. };
  39755. }
  39756. /**
  39757. * Converts `set` to an array of its values.
  39758. *
  39759. * @private
  39760. * @param {Object} set The set to convert.
  39761. * @returns {Array} Returns the values.
  39762. */
  39763. function setToArray(set) {
  39764. var index = -1,
  39765. result = Array(set.size);
  39766. set.forEach(function (value) {
  39767. result[++index] = value;
  39768. });
  39769. return result;
  39770. }
  39771. /** Used for built-in method references. */
  39772. var arrayProto = Array.prototype,
  39773. funcProto = Function.prototype,
  39774. objectProto = Object.prototype;
  39775. /** Used to detect overreaching core-js shims. */
  39776. var coreJsData = root['__core-js_shared__'];
  39777. /** Used to resolve the decompiled source of functions. */
  39778. var funcToString = funcProto.toString;
  39779. /** Used to check objects for own properties. */
  39780. var hasOwnProperty = objectProto.hasOwnProperty;
  39781. /** Used to detect methods masquerading as native. */
  39782. var maskSrcKey = function () {
  39783. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  39784. return uid ? 'Symbol(src)_1.' + uid : '';
  39785. }();
  39786. /**
  39787. * Used to resolve the
  39788. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  39789. * of values.
  39790. */
  39791. var nativeObjectToString = objectProto.toString;
  39792. /** Used to detect if a method is native. */
  39793. var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
  39794. /** Built-in value references. */
  39795. var Buffer = moduleExports ? root.Buffer : undefined,
  39796. Symbol = root.Symbol,
  39797. Uint8Array = root.Uint8Array,
  39798. propertyIsEnumerable = objectProto.propertyIsEnumerable,
  39799. splice = arrayProto.splice,
  39800. symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  39801. /* Built-in method references for those with the same name as other `lodash` methods. */
  39802. var nativeGetSymbols = Object.getOwnPropertySymbols,
  39803. nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
  39804. nativeKeys = overArg(Object.keys, Object);
  39805. /* Built-in method references that are verified to be native. */
  39806. var DataView = getNative(root, 'DataView'),
  39807. Map = getNative(root, 'Map'),
  39808. Promise = getNative(root, 'Promise'),
  39809. Set = getNative(root, 'Set'),
  39810. WeakMap = getNative(root, 'WeakMap'),
  39811. nativeCreate = getNative(Object, 'create');
  39812. /** Used to detect maps, sets, and weakmaps. */
  39813. var dataViewCtorString = toSource(DataView),
  39814. mapCtorString = toSource(Map),
  39815. promiseCtorString = toSource(Promise),
  39816. setCtorString = toSource(Set),
  39817. weakMapCtorString = toSource(WeakMap);
  39818. /** Used to convert symbols to primitives and strings. */
  39819. var symbolProto = Symbol ? Symbol.prototype : undefined,
  39820. symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
  39821. /**
  39822. * Creates a hash object.
  39823. *
  39824. * @private
  39825. * @constructor
  39826. * @param {Array} [entries] The key-value pairs to cache.
  39827. */
  39828. function Hash(entries) {
  39829. var index = -1,
  39830. length = entries == null ? 0 : entries.length;
  39831. this.clear();
  39832. while (++index < length) {
  39833. var entry = entries[index];
  39834. this.set(entry[0], entry[1]);
  39835. }
  39836. }
  39837. /**
  39838. * Removes all key-value entries from the hash.
  39839. *
  39840. * @private
  39841. * @name clear
  39842. * @memberOf Hash
  39843. */
  39844. function hashClear() {
  39845. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  39846. this.size = 0;
  39847. }
  39848. /**
  39849. * Removes `key` and its value from the hash.
  39850. *
  39851. * @private
  39852. * @name delete
  39853. * @memberOf Hash
  39854. * @param {Object} hash The hash to modify.
  39855. * @param {string} key The key of the value to remove.
  39856. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  39857. */
  39858. function hashDelete(key) {
  39859. var result = this.has(key) && delete this.__data__[key];
  39860. this.size -= result ? 1 : 0;
  39861. return result;
  39862. }
  39863. /**
  39864. * Gets the hash value for `key`.
  39865. *
  39866. * @private
  39867. * @name get
  39868. * @memberOf Hash
  39869. * @param {string} key The key of the value to get.
  39870. * @returns {*} Returns the entry value.
  39871. */
  39872. function hashGet(key) {
  39873. var data = this.__data__;
  39874. if (nativeCreate) {
  39875. var result = data[key];
  39876. return result === HASH_UNDEFINED ? undefined : result;
  39877. }
  39878. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  39879. }
  39880. /**
  39881. * Checks if a hash value for `key` exists.
  39882. *
  39883. * @private
  39884. * @name has
  39885. * @memberOf Hash
  39886. * @param {string} key The key of the entry to check.
  39887. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  39888. */
  39889. function hashHas(key) {
  39890. var data = this.__data__;
  39891. return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
  39892. }
  39893. /**
  39894. * Sets the hash `key` to `value`.
  39895. *
  39896. * @private
  39897. * @name set
  39898. * @memberOf Hash
  39899. * @param {string} key The key of the value to set.
  39900. * @param {*} value The value to set.
  39901. * @returns {Object} Returns the hash instance.
  39902. */
  39903. function hashSet(key, value) {
  39904. var data = this.__data__;
  39905. this.size += this.has(key) ? 0 : 1;
  39906. data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value;
  39907. return this;
  39908. }
  39909. // Add methods to `Hash`.
  39910. Hash.prototype.clear = hashClear;
  39911. Hash.prototype['delete'] = hashDelete;
  39912. Hash.prototype.get = hashGet;
  39913. Hash.prototype.has = hashHas;
  39914. Hash.prototype.set = hashSet;
  39915. /**
  39916. * Creates an list cache object.
  39917. *
  39918. * @private
  39919. * @constructor
  39920. * @param {Array} [entries] The key-value pairs to cache.
  39921. */
  39922. function ListCache(entries) {
  39923. var index = -1,
  39924. length = entries == null ? 0 : entries.length;
  39925. this.clear();
  39926. while (++index < length) {
  39927. var entry = entries[index];
  39928. this.set(entry[0], entry[1]);
  39929. }
  39930. }
  39931. /**
  39932. * Removes all key-value entries from the list cache.
  39933. *
  39934. * @private
  39935. * @name clear
  39936. * @memberOf ListCache
  39937. */
  39938. function listCacheClear() {
  39939. this.__data__ = [];
  39940. this.size = 0;
  39941. }
  39942. /**
  39943. * Removes `key` and its value from the list cache.
  39944. *
  39945. * @private
  39946. * @name delete
  39947. * @memberOf ListCache
  39948. * @param {string} key The key of the value to remove.
  39949. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  39950. */
  39951. function listCacheDelete(key) {
  39952. var data = this.__data__,
  39953. index = assocIndexOf(data, key);
  39954. if (index < 0) {
  39955. return false;
  39956. }
  39957. var lastIndex = data.length - 1;
  39958. if (index == lastIndex) {
  39959. data.pop();
  39960. } else {
  39961. splice.call(data, index, 1);
  39962. }
  39963. --this.size;
  39964. return true;
  39965. }
  39966. /**
  39967. * Gets the list cache value for `key`.
  39968. *
  39969. * @private
  39970. * @name get
  39971. * @memberOf ListCache
  39972. * @param {string} key The key of the value to get.
  39973. * @returns {*} Returns the entry value.
  39974. */
  39975. function listCacheGet(key) {
  39976. var data = this.__data__,
  39977. index = assocIndexOf(data, key);
  39978. return index < 0 ? undefined : data[index][1];
  39979. }
  39980. /**
  39981. * Checks if a list cache value for `key` exists.
  39982. *
  39983. * @private
  39984. * @name has
  39985. * @memberOf ListCache
  39986. * @param {string} key The key of the entry to check.
  39987. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  39988. */
  39989. function listCacheHas(key) {
  39990. return assocIndexOf(this.__data__, key) > -1;
  39991. }
  39992. /**
  39993. * Sets the list cache `key` to `value`.
  39994. *
  39995. * @private
  39996. * @name set
  39997. * @memberOf ListCache
  39998. * @param {string} key The key of the value to set.
  39999. * @param {*} value The value to set.
  40000. * @returns {Object} Returns the list cache instance.
  40001. */
  40002. function listCacheSet(key, value) {
  40003. var data = this.__data__,
  40004. index = assocIndexOf(data, key);
  40005. if (index < 0) {
  40006. ++this.size;
  40007. data.push([key, value]);
  40008. } else {
  40009. data[index][1] = value;
  40010. }
  40011. return this;
  40012. }
  40013. // Add methods to `ListCache`.
  40014. ListCache.prototype.clear = listCacheClear;
  40015. ListCache.prototype['delete'] = listCacheDelete;
  40016. ListCache.prototype.get = listCacheGet;
  40017. ListCache.prototype.has = listCacheHas;
  40018. ListCache.prototype.set = listCacheSet;
  40019. /**
  40020. * Creates a map cache object to store key-value pairs.
  40021. *
  40022. * @private
  40023. * @constructor
  40024. * @param {Array} [entries] The key-value pairs to cache.
  40025. */
  40026. function MapCache(entries) {
  40027. var index = -1,
  40028. length = entries == null ? 0 : entries.length;
  40029. this.clear();
  40030. while (++index < length) {
  40031. var entry = entries[index];
  40032. this.set(entry[0], entry[1]);
  40033. }
  40034. }
  40035. /**
  40036. * Removes all key-value entries from the map.
  40037. *
  40038. * @private
  40039. * @name clear
  40040. * @memberOf MapCache
  40041. */
  40042. function mapCacheClear() {
  40043. this.size = 0;
  40044. this.__data__ = {
  40045. 'hash': new Hash(),
  40046. 'map': new (Map || ListCache)(),
  40047. 'string': new Hash()
  40048. };
  40049. }
  40050. /**
  40051. * Removes `key` and its value from the map.
  40052. *
  40053. * @private
  40054. * @name delete
  40055. * @memberOf MapCache
  40056. * @param {string} key The key of the value to remove.
  40057. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  40058. */
  40059. function mapCacheDelete(key) {
  40060. var result = getMapData(this, key)['delete'](key);
  40061. this.size -= result ? 1 : 0;
  40062. return result;
  40063. }
  40064. /**
  40065. * Gets the map value for `key`.
  40066. *
  40067. * @private
  40068. * @name get
  40069. * @memberOf MapCache
  40070. * @param {string} key The key of the value to get.
  40071. * @returns {*} Returns the entry value.
  40072. */
  40073. function mapCacheGet(key) {
  40074. return getMapData(this, key).get(key);
  40075. }
  40076. /**
  40077. * Checks if a map value for `key` exists.
  40078. *
  40079. * @private
  40080. * @name has
  40081. * @memberOf MapCache
  40082. * @param {string} key The key of the entry to check.
  40083. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  40084. */
  40085. function mapCacheHas(key) {
  40086. return getMapData(this, key).has(key);
  40087. }
  40088. /**
  40089. * Sets the map `key` to `value`.
  40090. *
  40091. * @private
  40092. * @name set
  40093. * @memberOf MapCache
  40094. * @param {string} key The key of the value to set.
  40095. * @param {*} value The value to set.
  40096. * @returns {Object} Returns the map cache instance.
  40097. */
  40098. function mapCacheSet(key, value) {
  40099. var data = getMapData(this, key),
  40100. size = data.size;
  40101. data.set(key, value);
  40102. this.size += data.size == size ? 0 : 1;
  40103. return this;
  40104. }
  40105. // Add methods to `MapCache`.
  40106. MapCache.prototype.clear = mapCacheClear;
  40107. MapCache.prototype['delete'] = mapCacheDelete;
  40108. MapCache.prototype.get = mapCacheGet;
  40109. MapCache.prototype.has = mapCacheHas;
  40110. MapCache.prototype.set = mapCacheSet;
  40111. /**
  40112. *
  40113. * Creates an array cache object to store unique values.
  40114. *
  40115. * @private
  40116. * @constructor
  40117. * @param {Array} [values] The values to cache.
  40118. */
  40119. function SetCache(values) {
  40120. var index = -1,
  40121. length = values == null ? 0 : values.length;
  40122. this.__data__ = new MapCache();
  40123. while (++index < length) {
  40124. this.add(values[index]);
  40125. }
  40126. }
  40127. /**
  40128. * Adds `value` to the array cache.
  40129. *
  40130. * @private
  40131. * @name add
  40132. * @memberOf SetCache
  40133. * @alias push
  40134. * @param {*} value The value to cache.
  40135. * @returns {Object} Returns the cache instance.
  40136. */
  40137. function setCacheAdd(value) {
  40138. this.__data__.set(value, HASH_UNDEFINED);
  40139. return this;
  40140. }
  40141. /**
  40142. * Checks if `value` is in the array cache.
  40143. *
  40144. * @private
  40145. * @name has
  40146. * @memberOf SetCache
  40147. * @param {*} value The value to search for.
  40148. * @returns {number} Returns `true` if `value` is found, else `false`.
  40149. */
  40150. function setCacheHas(value) {
  40151. return this.__data__.has(value);
  40152. }
  40153. // Add methods to `SetCache`.
  40154. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
  40155. SetCache.prototype.has = setCacheHas;
  40156. /**
  40157. * Creates a stack cache object to store key-value pairs.
  40158. *
  40159. * @private
  40160. * @constructor
  40161. * @param {Array} [entries] The key-value pairs to cache.
  40162. */
  40163. function Stack(entries) {
  40164. var data = this.__data__ = new ListCache(entries);
  40165. this.size = data.size;
  40166. }
  40167. /**
  40168. * Removes all key-value entries from the stack.
  40169. *
  40170. * @private
  40171. * @name clear
  40172. * @memberOf Stack
  40173. */
  40174. function stackClear() {
  40175. this.__data__ = new ListCache();
  40176. this.size = 0;
  40177. }
  40178. /**
  40179. * Removes `key` and its value from the stack.
  40180. *
  40181. * @private
  40182. * @name delete
  40183. * @memberOf Stack
  40184. * @param {string} key The key of the value to remove.
  40185. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  40186. */
  40187. function stackDelete(key) {
  40188. var data = this.__data__,
  40189. result = data['delete'](key);
  40190. this.size = data.size;
  40191. return result;
  40192. }
  40193. /**
  40194. * Gets the stack value for `key`.
  40195. *
  40196. * @private
  40197. * @name get
  40198. * @memberOf Stack
  40199. * @param {string} key The key of the value to get.
  40200. * @returns {*} Returns the entry value.
  40201. */
  40202. function stackGet(key) {
  40203. return this.__data__.get(key);
  40204. }
  40205. /**
  40206. * Checks if a stack value for `key` exists.
  40207. *
  40208. * @private
  40209. * @name has
  40210. * @memberOf Stack
  40211. * @param {string} key The key of the entry to check.
  40212. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  40213. */
  40214. function stackHas(key) {
  40215. return this.__data__.has(key);
  40216. }
  40217. /**
  40218. * Sets the stack `key` to `value`.
  40219. *
  40220. * @private
  40221. * @name set
  40222. * @memberOf Stack
  40223. * @param {string} key The key of the value to set.
  40224. * @param {*} value The value to set.
  40225. * @returns {Object} Returns the stack cache instance.
  40226. */
  40227. function stackSet(key, value) {
  40228. var data = this.__data__;
  40229. if (data instanceof ListCache) {
  40230. var pairs = data.__data__;
  40231. if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
  40232. pairs.push([key, value]);
  40233. this.size = ++data.size;
  40234. return this;
  40235. }
  40236. data = this.__data__ = new MapCache(pairs);
  40237. }
  40238. data.set(key, value);
  40239. this.size = data.size;
  40240. return this;
  40241. }
  40242. // Add methods to `Stack`.
  40243. Stack.prototype.clear = stackClear;
  40244. Stack.prototype['delete'] = stackDelete;
  40245. Stack.prototype.get = stackGet;
  40246. Stack.prototype.has = stackHas;
  40247. Stack.prototype.set = stackSet;
  40248. /**
  40249. * Creates an array of the enumerable property names of the array-like `value`.
  40250. *
  40251. * @private
  40252. * @param {*} value The value to query.
  40253. * @param {boolean} inherited Specify returning inherited property names.
  40254. * @returns {Array} Returns the array of property names.
  40255. */
  40256. function arrayLikeKeys(value, inherited) {
  40257. var isArr = isArray(value),
  40258. isArg = !isArr && isArguments(value),
  40259. isBuff = !isArr && !isArg && isBuffer(value),
  40260. isType = !isArr && !isArg && !isBuff && isTypedArray(value),
  40261. skipIndexes = isArr || isArg || isBuff || isType,
  40262. result = skipIndexes ? baseTimes(value.length, String) : [],
  40263. length = result.length;
  40264. for (var key in value) {
  40265. if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (
  40266. // Safari 9 has enumerable `arguments.length` in strict mode.
  40267. key == 'length' ||
  40268. // Node.js 0.10 has enumerable non-index properties on buffers.
  40269. isBuff && (key == 'offset' || key == 'parent') ||
  40270. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  40271. isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') ||
  40272. // Skip index properties.
  40273. isIndex(key, length)))) {
  40274. result.push(key);
  40275. }
  40276. }
  40277. return result;
  40278. }
  40279. /**
  40280. * Gets the index at which the `key` is found in `array` of key-value pairs.
  40281. *
  40282. * @private
  40283. * @param {Array} array The array to inspect.
  40284. * @param {*} key The key to search for.
  40285. * @returns {number} Returns the index of the matched value, else `-1`.
  40286. */
  40287. function assocIndexOf(array, key) {
  40288. var length = array.length;
  40289. while (length--) {
  40290. if (eq(array[length][0], key)) {
  40291. return length;
  40292. }
  40293. }
  40294. return -1;
  40295. }
  40296. /**
  40297. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  40298. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  40299. * symbols of `object`.
  40300. *
  40301. * @private
  40302. * @param {Object} object The object to query.
  40303. * @param {Function} keysFunc The function to get the keys of `object`.
  40304. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  40305. * @returns {Array} Returns the array of property names and symbols.
  40306. */
  40307. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  40308. var result = keysFunc(object);
  40309. return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
  40310. }
  40311. /**
  40312. * The base implementation of `getTag` without fallbacks for buggy environments.
  40313. *
  40314. * @private
  40315. * @param {*} value The value to query.
  40316. * @returns {string} Returns the `toStringTag`.
  40317. */
  40318. function baseGetTag(value) {
  40319. if (value == null) {
  40320. return value === undefined ? undefinedTag : nullTag;
  40321. }
  40322. return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
  40323. }
  40324. /**
  40325. * The base implementation of `_.isArguments`.
  40326. *
  40327. * @private
  40328. * @param {*} value The value to check.
  40329. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  40330. */
  40331. function baseIsArguments(value) {
  40332. return isObjectLike(value) && baseGetTag(value) == argsTag;
  40333. }
  40334. /**
  40335. * The base implementation of `_.isEqual` which supports partial comparisons
  40336. * and tracks traversed objects.
  40337. *
  40338. * @private
  40339. * @param {*} value The value to compare.
  40340. * @param {*} other The other value to compare.
  40341. * @param {boolean} bitmask The bitmask flags.
  40342. * 1 - Unordered comparison
  40343. * 2 - Partial comparison
  40344. * @param {Function} [customizer] The function to customize comparisons.
  40345. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  40346. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  40347. */
  40348. function baseIsEqual(value, other, bitmask, customizer, stack) {
  40349. if (value === other) {
  40350. return true;
  40351. }
  40352. if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
  40353. return value !== value && other !== other;
  40354. }
  40355. return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  40356. }
  40357. /**
  40358. * A specialized version of `baseIsEqual` for arrays and objects which performs
  40359. * deep comparisons and tracks traversed objects enabling objects with circular
  40360. * references to be compared.
  40361. *
  40362. * @private
  40363. * @param {Object} object The object to compare.
  40364. * @param {Object} other The other object to compare.
  40365. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  40366. * @param {Function} customizer The function to customize comparisons.
  40367. * @param {Function} equalFunc The function to determine equivalents of values.
  40368. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  40369. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  40370. */
  40371. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  40372. var objIsArr = isArray(object),
  40373. othIsArr = isArray(other),
  40374. objTag = objIsArr ? arrayTag : getTag(object),
  40375. othTag = othIsArr ? arrayTag : getTag(other);
  40376. objTag = objTag == argsTag ? objectTag : objTag;
  40377. othTag = othTag == argsTag ? objectTag : othTag;
  40378. var objIsObj = objTag == objectTag,
  40379. othIsObj = othTag == objectTag,
  40380. isSameTag = objTag == othTag;
  40381. if (isSameTag && isBuffer(object)) {
  40382. if (!isBuffer(other)) {
  40383. return false;
  40384. }
  40385. objIsArr = true;
  40386. objIsObj = false;
  40387. }
  40388. if (isSameTag && !objIsObj) {
  40389. stack || (stack = new Stack());
  40390. return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  40391. }
  40392. if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
  40393. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  40394. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  40395. if (objIsWrapped || othIsWrapped) {
  40396. var objUnwrapped = objIsWrapped ? object.value() : object,
  40397. othUnwrapped = othIsWrapped ? other.value() : other;
  40398. stack || (stack = new Stack());
  40399. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  40400. }
  40401. }
  40402. if (!isSameTag) {
  40403. return false;
  40404. }
  40405. stack || (stack = new Stack());
  40406. return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  40407. }
  40408. /**
  40409. * The base implementation of `_.isNative` without bad shim checks.
  40410. *
  40411. * @private
  40412. * @param {*} value The value to check.
  40413. * @returns {boolean} Returns `true` if `value` is a native function,
  40414. * else `false`.
  40415. */
  40416. function baseIsNative(value) {
  40417. if (!isObject(value) || isMasked(value)) {
  40418. return false;
  40419. }
  40420. var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  40421. return pattern.test(toSource(value));
  40422. }
  40423. /**
  40424. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  40425. *
  40426. * @private
  40427. * @param {*} value The value to check.
  40428. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  40429. */
  40430. function baseIsTypedArray(value) {
  40431. return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
  40432. }
  40433. /**
  40434. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  40435. *
  40436. * @private
  40437. * @param {Object} object The object to query.
  40438. * @returns {Array} Returns the array of property names.
  40439. */
  40440. function baseKeys(object) {
  40441. if (!isPrototype(object)) {
  40442. return nativeKeys(object);
  40443. }
  40444. var result = [];
  40445. for (var key in Object(object)) {
  40446. if (hasOwnProperty.call(object, key) && key != 'constructor') {
  40447. result.push(key);
  40448. }
  40449. }
  40450. return result;
  40451. }
  40452. /**
  40453. * A specialized version of `baseIsEqualDeep` for arrays with support for
  40454. * partial deep comparisons.
  40455. *
  40456. * @private
  40457. * @param {Array} array The array to compare.
  40458. * @param {Array} other The other array to compare.
  40459. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  40460. * @param {Function} customizer The function to customize comparisons.
  40461. * @param {Function} equalFunc The function to determine equivalents of values.
  40462. * @param {Object} stack Tracks traversed `array` and `other` objects.
  40463. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  40464. */
  40465. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  40466. var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
  40467. arrLength = array.length,
  40468. othLength = other.length;
  40469. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  40470. return false;
  40471. }
  40472. // Assume cyclic values are equal.
  40473. var stacked = stack.get(array);
  40474. if (stacked && stack.get(other)) {
  40475. return stacked == other;
  40476. }
  40477. var index = -1,
  40478. result = true,
  40479. seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined;
  40480. stack.set(array, other);
  40481. stack.set(other, array);
  40482. // Ignore non-index properties.
  40483. while (++index < arrLength) {
  40484. var arrValue = array[index],
  40485. othValue = other[index];
  40486. if (customizer) {
  40487. var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
  40488. }
  40489. if (compared !== undefined) {
  40490. if (compared) {
  40491. continue;
  40492. }
  40493. result = false;
  40494. break;
  40495. }
  40496. // Recursively compare arrays (susceptible to call stack limits).
  40497. if (seen) {
  40498. if (!arraySome(other, function (othValue, othIndex) {
  40499. if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  40500. return seen.push(othIndex);
  40501. }
  40502. })) {
  40503. result = false;
  40504. break;
  40505. }
  40506. } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  40507. result = false;
  40508. break;
  40509. }
  40510. }
  40511. stack['delete'](array);
  40512. stack['delete'](other);
  40513. return result;
  40514. }
  40515. /**
  40516. * A specialized version of `baseIsEqualDeep` for comparing objects of
  40517. * the same `toStringTag`.
  40518. *
  40519. * **Note:** This function only supports comparing values with tags of
  40520. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  40521. *
  40522. * @private
  40523. * @param {Object} object The object to compare.
  40524. * @param {Object} other The other object to compare.
  40525. * @param {string} tag The `toStringTag` of the objects to compare.
  40526. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  40527. * @param {Function} customizer The function to customize comparisons.
  40528. * @param {Function} equalFunc The function to determine equivalents of values.
  40529. * @param {Object} stack Tracks traversed `object` and `other` objects.
  40530. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  40531. */
  40532. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  40533. switch (tag) {
  40534. case dataViewTag:
  40535. if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
  40536. return false;
  40537. }
  40538. object = object.buffer;
  40539. other = other.buffer;
  40540. case arrayBufferTag:
  40541. if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
  40542. return false;
  40543. }
  40544. return true;
  40545. case boolTag:
  40546. case dateTag:
  40547. case numberTag:
  40548. // Coerce booleans to `1` or `0` and dates to milliseconds.
  40549. // Invalid dates are coerced to `NaN`.
  40550. return eq(+object, +other);
  40551. case errorTag:
  40552. return object.name == other.name && object.message == other.message;
  40553. case regexpTag:
  40554. case stringTag:
  40555. // Coerce regexes to strings and treat strings, primitives and objects,
  40556. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  40557. // for more details.
  40558. return object == other + '';
  40559. case mapTag:
  40560. var convert = mapToArray;
  40561. case setTag:
  40562. var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
  40563. convert || (convert = setToArray);
  40564. if (object.size != other.size && !isPartial) {
  40565. return false;
  40566. }
  40567. // Assume cyclic values are equal.
  40568. var stacked = stack.get(object);
  40569. if (stacked) {
  40570. return stacked == other;
  40571. }
  40572. bitmask |= COMPARE_UNORDERED_FLAG;
  40573. // Recursively compare objects (susceptible to call stack limits).
  40574. stack.set(object, other);
  40575. var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  40576. stack['delete'](object);
  40577. return result;
  40578. case symbolTag:
  40579. if (symbolValueOf) {
  40580. return symbolValueOf.call(object) == symbolValueOf.call(other);
  40581. }
  40582. }
  40583. return false;
  40584. }
  40585. /**
  40586. * A specialized version of `baseIsEqualDeep` for objects with support for
  40587. * partial deep comparisons.
  40588. *
  40589. * @private
  40590. * @param {Object} object The object to compare.
  40591. * @param {Object} other The other object to compare.
  40592. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  40593. * @param {Function} customizer The function to customize comparisons.
  40594. * @param {Function} equalFunc The function to determine equivalents of values.
  40595. * @param {Object} stack Tracks traversed `object` and `other` objects.
  40596. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  40597. */
  40598. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  40599. var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
  40600. objProps = getAllKeys(object),
  40601. objLength = objProps.length,
  40602. othProps = getAllKeys(other),
  40603. othLength = othProps.length;
  40604. if (objLength != othLength && !isPartial) {
  40605. return false;
  40606. }
  40607. var index = objLength;
  40608. while (index--) {
  40609. var key = objProps[index];
  40610. if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
  40611. return false;
  40612. }
  40613. }
  40614. // Assume cyclic values are equal.
  40615. var stacked = stack.get(object);
  40616. if (stacked && stack.get(other)) {
  40617. return stacked == other;
  40618. }
  40619. var result = true;
  40620. stack.set(object, other);
  40621. stack.set(other, object);
  40622. var skipCtor = isPartial;
  40623. while (++index < objLength) {
  40624. key = objProps[index];
  40625. var objValue = object[key],
  40626. othValue = other[key];
  40627. if (customizer) {
  40628. var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
  40629. }
  40630. // Recursively compare objects (susceptible to call stack limits).
  40631. if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
  40632. result = false;
  40633. break;
  40634. }
  40635. skipCtor || (skipCtor = key == 'constructor');
  40636. }
  40637. if (result && !skipCtor) {
  40638. var objCtor = object.constructor,
  40639. othCtor = other.constructor;
  40640. // Non `Object` object instances with different constructors are not equal.
  40641. if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  40642. result = false;
  40643. }
  40644. }
  40645. stack['delete'](object);
  40646. stack['delete'](other);
  40647. return result;
  40648. }
  40649. /**
  40650. * Creates an array of own enumerable property names and symbols of `object`.
  40651. *
  40652. * @private
  40653. * @param {Object} object The object to query.
  40654. * @returns {Array} Returns the array of property names and symbols.
  40655. */
  40656. function getAllKeys(object) {
  40657. return baseGetAllKeys(object, keys, getSymbols);
  40658. }
  40659. /**
  40660. * Gets the data for `map`.
  40661. *
  40662. * @private
  40663. * @param {Object} map The map to query.
  40664. * @param {string} key The reference key.
  40665. * @returns {*} Returns the map data.
  40666. */
  40667. function getMapData(map, key) {
  40668. var data = map.__data__;
  40669. return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
  40670. }
  40671. /**
  40672. * Gets the native function at `key` of `object`.
  40673. *
  40674. * @private
  40675. * @param {Object} object The object to query.
  40676. * @param {string} key The key of the method to get.
  40677. * @returns {*} Returns the function if it's native, else `undefined`.
  40678. */
  40679. function getNative(object, key) {
  40680. var value = getValue(object, key);
  40681. return baseIsNative(value) ? value : undefined;
  40682. }
  40683. /**
  40684. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  40685. *
  40686. * @private
  40687. * @param {*} value The value to query.
  40688. * @returns {string} Returns the raw `toStringTag`.
  40689. */
  40690. function getRawTag(value) {
  40691. var isOwn = hasOwnProperty.call(value, symToStringTag),
  40692. tag = value[symToStringTag];
  40693. try {
  40694. value[symToStringTag] = undefined;
  40695. var unmasked = true;
  40696. } catch (e) {}
  40697. var result = nativeObjectToString.call(value);
  40698. if (unmasked) {
  40699. if (isOwn) {
  40700. value[symToStringTag] = tag;
  40701. } else {
  40702. delete value[symToStringTag];
  40703. }
  40704. }
  40705. return result;
  40706. }
  40707. /**
  40708. * Creates an array of the own enumerable symbols of `object`.
  40709. *
  40710. * @private
  40711. * @param {Object} object The object to query.
  40712. * @returns {Array} Returns the array of symbols.
  40713. */
  40714. var getSymbols = !nativeGetSymbols ? stubArray : function (object) {
  40715. if (object == null) {
  40716. return [];
  40717. }
  40718. object = Object(object);
  40719. return arrayFilter(nativeGetSymbols(object), function (symbol) {
  40720. return propertyIsEnumerable.call(object, symbol);
  40721. });
  40722. };
  40723. /**
  40724. * Gets the `toStringTag` of `value`.
  40725. *
  40726. * @private
  40727. * @param {*} value The value to query.
  40728. * @returns {string} Returns the `toStringTag`.
  40729. */
  40730. var getTag = baseGetTag;
  40731. // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  40732. if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) {
  40733. getTag = function (value) {
  40734. var result = baseGetTag(value),
  40735. Ctor = result == objectTag ? value.constructor : undefined,
  40736. ctorString = Ctor ? toSource(Ctor) : '';
  40737. if (ctorString) {
  40738. switch (ctorString) {
  40739. case dataViewCtorString:
  40740. return dataViewTag;
  40741. case mapCtorString:
  40742. return mapTag;
  40743. case promiseCtorString:
  40744. return promiseTag;
  40745. case setCtorString:
  40746. return setTag;
  40747. case weakMapCtorString:
  40748. return weakMapTag;
  40749. }
  40750. }
  40751. return result;
  40752. };
  40753. }
  40754. /**
  40755. * Checks if `value` is a valid array-like index.
  40756. *
  40757. * @private
  40758. * @param {*} value The value to check.
  40759. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  40760. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  40761. */
  40762. function isIndex(value, length) {
  40763. length = length == null ? MAX_SAFE_INTEGER : length;
  40764. return !!length && (typeof value == 'number' || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
  40765. }
  40766. /**
  40767. * Checks if `value` is suitable for use as unique object key.
  40768. *
  40769. * @private
  40770. * @param {*} value The value to check.
  40771. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  40772. */
  40773. function isKeyable(value) {
  40774. var type = typeof value;
  40775. return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
  40776. }
  40777. /**
  40778. * Checks if `func` has its source masked.
  40779. *
  40780. * @private
  40781. * @param {Function} func The function to check.
  40782. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  40783. */
  40784. function isMasked(func) {
  40785. return !!maskSrcKey && maskSrcKey in func;
  40786. }
  40787. /**
  40788. * Checks if `value` is likely a prototype object.
  40789. *
  40790. * @private
  40791. * @param {*} value The value to check.
  40792. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  40793. */
  40794. function isPrototype(value) {
  40795. var Ctor = value && value.constructor,
  40796. proto = typeof Ctor == 'function' && Ctor.prototype || objectProto;
  40797. return value === proto;
  40798. }
  40799. /**
  40800. * Converts `value` to a string using `Object.prototype.toString`.
  40801. *
  40802. * @private
  40803. * @param {*} value The value to convert.
  40804. * @returns {string} Returns the converted string.
  40805. */
  40806. function objectToString(value) {
  40807. return nativeObjectToString.call(value);
  40808. }
  40809. /**
  40810. * Converts `func` to its source code.
  40811. *
  40812. * @private
  40813. * @param {Function} func The function to convert.
  40814. * @returns {string} Returns the source code.
  40815. */
  40816. function toSource(func) {
  40817. if (func != null) {
  40818. try {
  40819. return funcToString.call(func);
  40820. } catch (e) {}
  40821. try {
  40822. return func + '';
  40823. } catch (e) {}
  40824. }
  40825. return '';
  40826. }
  40827. /**
  40828. * Performs a
  40829. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  40830. * comparison between two values to determine if they are equivalent.
  40831. *
  40832. * @static
  40833. * @memberOf _
  40834. * @since 4.0.0
  40835. * @category Lang
  40836. * @param {*} value The value to compare.
  40837. * @param {*} other The other value to compare.
  40838. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  40839. * @example
  40840. *
  40841. * var object = { 'a': 1 };
  40842. * var other = { 'a': 1 };
  40843. *
  40844. * _.eq(object, object);
  40845. * // => true
  40846. *
  40847. * _.eq(object, other);
  40848. * // => false
  40849. *
  40850. * _.eq('a', 'a');
  40851. * // => true
  40852. *
  40853. * _.eq('a', Object('a'));
  40854. * // => false
  40855. *
  40856. * _.eq(NaN, NaN);
  40857. * // => true
  40858. */
  40859. function eq(value, other) {
  40860. return value === other || value !== value && other !== other;
  40861. }
  40862. /**
  40863. * Checks if `value` is likely an `arguments` object.
  40864. *
  40865. * @static
  40866. * @memberOf _
  40867. * @since 0.1.0
  40868. * @category Lang
  40869. * @param {*} value The value to check.
  40870. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  40871. * else `false`.
  40872. * @example
  40873. *
  40874. * _.isArguments(function() { return arguments; }());
  40875. * // => true
  40876. *
  40877. * _.isArguments([1, 2, 3]);
  40878. * // => false
  40879. */
  40880. var isArguments = baseIsArguments(function () {
  40881. return arguments;
  40882. }()) ? baseIsArguments : function (value) {
  40883. return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
  40884. };
  40885. /**
  40886. * Checks if `value` is classified as an `Array` object.
  40887. *
  40888. * @static
  40889. * @memberOf _
  40890. * @since 0.1.0
  40891. * @category Lang
  40892. * @param {*} value The value to check.
  40893. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  40894. * @example
  40895. *
  40896. * _.isArray([1, 2, 3]);
  40897. * // => true
  40898. *
  40899. * _.isArray(document.body.children);
  40900. * // => false
  40901. *
  40902. * _.isArray('abc');
  40903. * // => false
  40904. *
  40905. * _.isArray(_.noop);
  40906. * // => false
  40907. */
  40908. var isArray = Array.isArray;
  40909. /**
  40910. * Checks if `value` is array-like. A value is considered array-like if it's
  40911. * not a function and has a `value.length` that's an integer greater than or
  40912. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  40913. *
  40914. * @static
  40915. * @memberOf _
  40916. * @since 4.0.0
  40917. * @category Lang
  40918. * @param {*} value The value to check.
  40919. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  40920. * @example
  40921. *
  40922. * _.isArrayLike([1, 2, 3]);
  40923. * // => true
  40924. *
  40925. * _.isArrayLike(document.body.children);
  40926. * // => true
  40927. *
  40928. * _.isArrayLike('abc');
  40929. * // => true
  40930. *
  40931. * _.isArrayLike(_.noop);
  40932. * // => false
  40933. */
  40934. function isArrayLike(value) {
  40935. return value != null && isLength(value.length) && !isFunction(value);
  40936. }
  40937. /**
  40938. * Checks if `value` is a buffer.
  40939. *
  40940. * @static
  40941. * @memberOf _
  40942. * @since 4.3.0
  40943. * @category Lang
  40944. * @param {*} value The value to check.
  40945. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  40946. * @example
  40947. *
  40948. * _.isBuffer(new Buffer(2));
  40949. * // => true
  40950. *
  40951. * _.isBuffer(new Uint8Array(2));
  40952. * // => false
  40953. */
  40954. var isBuffer = nativeIsBuffer || stubFalse;
  40955. /**
  40956. * Performs a deep comparison between two values to determine if they are
  40957. * equivalent.
  40958. *
  40959. * **Note:** This method supports comparing arrays, array buffers, booleans,
  40960. * date objects, error objects, maps, numbers, `Object` objects, regexes,
  40961. * sets, strings, symbols, and typed arrays. `Object` objects are compared
  40962. * by their own, not inherited, enumerable properties. Functions and DOM
  40963. * nodes are compared by strict equality, i.e. `===`.
  40964. *
  40965. * @static
  40966. * @memberOf _
  40967. * @since 0.1.0
  40968. * @category Lang
  40969. * @param {*} value The value to compare.
  40970. * @param {*} other The other value to compare.
  40971. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  40972. * @example
  40973. *
  40974. * var object = { 'a': 1 };
  40975. * var other = { 'a': 1 };
  40976. *
  40977. * _.isEqual(object, other);
  40978. * // => true
  40979. *
  40980. * object === other;
  40981. * // => false
  40982. */
  40983. function isEqual(value, other) {
  40984. return baseIsEqual(value, other);
  40985. }
  40986. /**
  40987. * Checks if `value` is classified as a `Function` object.
  40988. *
  40989. * @static
  40990. * @memberOf _
  40991. * @since 0.1.0
  40992. * @category Lang
  40993. * @param {*} value The value to check.
  40994. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  40995. * @example
  40996. *
  40997. * _.isFunction(_);
  40998. * // => true
  40999. *
  41000. * _.isFunction(/abc/);
  41001. * // => false
  41002. */
  41003. function isFunction(value) {
  41004. if (!isObject(value)) {
  41005. return false;
  41006. }
  41007. // The use of `Object#toString` avoids issues with the `typeof` operator
  41008. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  41009. var tag = baseGetTag(value);
  41010. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  41011. }
  41012. /**
  41013. * Checks if `value` is a valid array-like length.
  41014. *
  41015. * **Note:** This method is loosely based on
  41016. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  41017. *
  41018. * @static
  41019. * @memberOf _
  41020. * @since 4.0.0
  41021. * @category Lang
  41022. * @param {*} value The value to check.
  41023. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  41024. * @example
  41025. *
  41026. * _.isLength(3);
  41027. * // => true
  41028. *
  41029. * _.isLength(Number.MIN_VALUE);
  41030. * // => false
  41031. *
  41032. * _.isLength(Infinity);
  41033. * // => false
  41034. *
  41035. * _.isLength('3');
  41036. * // => false
  41037. */
  41038. function isLength(value) {
  41039. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  41040. }
  41041. /**
  41042. * Checks if `value` is the
  41043. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  41044. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  41045. *
  41046. * @static
  41047. * @memberOf _
  41048. * @since 0.1.0
  41049. * @category Lang
  41050. * @param {*} value The value to check.
  41051. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  41052. * @example
  41053. *
  41054. * _.isObject({});
  41055. * // => true
  41056. *
  41057. * _.isObject([1, 2, 3]);
  41058. * // => true
  41059. *
  41060. * _.isObject(_.noop);
  41061. * // => true
  41062. *
  41063. * _.isObject(null);
  41064. * // => false
  41065. */
  41066. function isObject(value) {
  41067. var type = typeof value;
  41068. return value != null && (type == 'object' || type == 'function');
  41069. }
  41070. /**
  41071. * Checks if `value` is object-like. A value is object-like if it's not `null`
  41072. * and has a `typeof` result of "object".
  41073. *
  41074. * @static
  41075. * @memberOf _
  41076. * @since 4.0.0
  41077. * @category Lang
  41078. * @param {*} value The value to check.
  41079. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  41080. * @example
  41081. *
  41082. * _.isObjectLike({});
  41083. * // => true
  41084. *
  41085. * _.isObjectLike([1, 2, 3]);
  41086. * // => true
  41087. *
  41088. * _.isObjectLike(_.noop);
  41089. * // => false
  41090. *
  41091. * _.isObjectLike(null);
  41092. * // => false
  41093. */
  41094. function isObjectLike(value) {
  41095. return value != null && typeof value == 'object';
  41096. }
  41097. /**
  41098. * Checks if `value` is classified as a typed array.
  41099. *
  41100. * @static
  41101. * @memberOf _
  41102. * @since 3.0.0
  41103. * @category Lang
  41104. * @param {*} value The value to check.
  41105. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  41106. * @example
  41107. *
  41108. * _.isTypedArray(new Uint8Array);
  41109. * // => true
  41110. *
  41111. * _.isTypedArray([]);
  41112. * // => false
  41113. */
  41114. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  41115. /**
  41116. * Creates an array of the own enumerable property names of `object`.
  41117. *
  41118. * **Note:** Non-object values are coerced to objects. See the
  41119. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  41120. * for more details.
  41121. *
  41122. * @static
  41123. * @since 0.1.0
  41124. * @memberOf _
  41125. * @category Object
  41126. * @param {Object} object The object to query.
  41127. * @returns {Array} Returns the array of property names.
  41128. * @example
  41129. *
  41130. * function Foo() {
  41131. * this.a = 1;
  41132. * this.b = 2;
  41133. * }
  41134. *
  41135. * Foo.prototype.c = 3;
  41136. *
  41137. * _.keys(new Foo);
  41138. * // => ['a', 'b'] (iteration order is not guaranteed)
  41139. *
  41140. * _.keys('hi');
  41141. * // => ['0', '1']
  41142. */
  41143. function keys(object) {
  41144. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  41145. }
  41146. /**
  41147. * This method returns a new empty array.
  41148. *
  41149. * @static
  41150. * @memberOf _
  41151. * @since 4.13.0
  41152. * @category Util
  41153. * @returns {Array} Returns the new empty array.
  41154. * @example
  41155. *
  41156. * var arrays = _.times(2, _.stubArray);
  41157. *
  41158. * console.log(arrays);
  41159. * // => [[], []]
  41160. *
  41161. * console.log(arrays[0] === arrays[1]);
  41162. * // => false
  41163. */
  41164. function stubArray() {
  41165. return [];
  41166. }
  41167. /**
  41168. * This method returns `false`.
  41169. *
  41170. * @static
  41171. * @memberOf _
  41172. * @since 4.13.0
  41173. * @category Util
  41174. * @returns {boolean} Returns `false`.
  41175. * @example
  41176. *
  41177. * _.times(2, _.stubFalse);
  41178. * // => [false, false]
  41179. */
  41180. function stubFalse() {
  41181. return false;
  41182. }
  41183. module.exports = isEqual;
  41184. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  41185. },{}],285:[function(require,module,exports){
  41186. (function (global){(function (){
  41187. "use strict";
  41188. /**
  41189. * Lodash (Custom Build) <https://lodash.com/>
  41190. * Build: `lodash modularize exports="npm" -o ./`
  41191. * Copyright JS Foundation and other contributors <https://js.foundation/>
  41192. * Released under MIT license <https://lodash.com/license>
  41193. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  41194. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  41195. */
  41196. /** `Object#toString` result references. */
  41197. var asyncTag = '[object AsyncFunction]',
  41198. funcTag = '[object Function]',
  41199. genTag = '[object GeneratorFunction]',
  41200. nullTag = '[object Null]',
  41201. proxyTag = '[object Proxy]',
  41202. undefinedTag = '[object Undefined]';
  41203. /** Detect free variable `global` from Node.js. */
  41204. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  41205. /** Detect free variable `self`. */
  41206. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  41207. /** Used as a reference to the global object. */
  41208. var root = freeGlobal || freeSelf || Function('return this')();
  41209. /** Used for built-in method references. */
  41210. var objectProto = Object.prototype;
  41211. /** Used to check objects for own properties. */
  41212. var hasOwnProperty = objectProto.hasOwnProperty;
  41213. /**
  41214. * Used to resolve the
  41215. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  41216. * of values.
  41217. */
  41218. var nativeObjectToString = objectProto.toString;
  41219. /** Built-in value references. */
  41220. var Symbol = root.Symbol,
  41221. symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  41222. /**
  41223. * The base implementation of `getTag` without fallbacks for buggy environments.
  41224. *
  41225. * @private
  41226. * @param {*} value The value to query.
  41227. * @returns {string} Returns the `toStringTag`.
  41228. */
  41229. function baseGetTag(value) {
  41230. if (value == null) {
  41231. return value === undefined ? undefinedTag : nullTag;
  41232. }
  41233. return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
  41234. }
  41235. /**
  41236. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  41237. *
  41238. * @private
  41239. * @param {*} value The value to query.
  41240. * @returns {string} Returns the raw `toStringTag`.
  41241. */
  41242. function getRawTag(value) {
  41243. var isOwn = hasOwnProperty.call(value, symToStringTag),
  41244. tag = value[symToStringTag];
  41245. try {
  41246. value[symToStringTag] = undefined;
  41247. var unmasked = true;
  41248. } catch (e) {}
  41249. var result = nativeObjectToString.call(value);
  41250. if (unmasked) {
  41251. if (isOwn) {
  41252. value[symToStringTag] = tag;
  41253. } else {
  41254. delete value[symToStringTag];
  41255. }
  41256. }
  41257. return result;
  41258. }
  41259. /**
  41260. * Converts `value` to a string using `Object.prototype.toString`.
  41261. *
  41262. * @private
  41263. * @param {*} value The value to convert.
  41264. * @returns {string} Returns the converted string.
  41265. */
  41266. function objectToString(value) {
  41267. return nativeObjectToString.call(value);
  41268. }
  41269. /**
  41270. * Checks if `value` is classified as a `Function` object.
  41271. *
  41272. * @static
  41273. * @memberOf _
  41274. * @since 0.1.0
  41275. * @category Lang
  41276. * @param {*} value The value to check.
  41277. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  41278. * @example
  41279. *
  41280. * _.isFunction(_);
  41281. * // => true
  41282. *
  41283. * _.isFunction(/abc/);
  41284. * // => false
  41285. */
  41286. function isFunction(value) {
  41287. if (!isObject(value)) {
  41288. return false;
  41289. }
  41290. // The use of `Object#toString` avoids issues with the `typeof` operator
  41291. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  41292. var tag = baseGetTag(value);
  41293. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  41294. }
  41295. /**
  41296. * Checks if `value` is the
  41297. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  41298. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  41299. *
  41300. * @static
  41301. * @memberOf _
  41302. * @since 0.1.0
  41303. * @category Lang
  41304. * @param {*} value The value to check.
  41305. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  41306. * @example
  41307. *
  41308. * _.isObject({});
  41309. * // => true
  41310. *
  41311. * _.isObject([1, 2, 3]);
  41312. * // => true
  41313. *
  41314. * _.isObject(_.noop);
  41315. * // => true
  41316. *
  41317. * _.isObject(null);
  41318. * // => false
  41319. */
  41320. function isObject(value) {
  41321. var type = typeof value;
  41322. return value != null && (type == 'object' || type == 'function');
  41323. }
  41324. module.exports = isFunction;
  41325. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  41326. },{}],286:[function(require,module,exports){
  41327. "use strict";
  41328. /**
  41329. * lodash 4.0.0 (Custom Build) <https://lodash.com/>
  41330. * Build: `lodash modularize exports="npm" -o ./`
  41331. * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
  41332. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  41333. * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  41334. * Available under MIT license <https://lodash.com/license>
  41335. */
  41336. /**
  41337. * Checks if `value` is `null` or `undefined`.
  41338. *
  41339. * @static
  41340. * @memberOf _
  41341. * @category Lang
  41342. * @param {*} value The value to check.
  41343. * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
  41344. * @example
  41345. *
  41346. * _.isNil(null);
  41347. * // => true
  41348. *
  41349. * _.isNil(void 0);
  41350. * // => true
  41351. *
  41352. * _.isNil(NaN);
  41353. * // => false
  41354. */
  41355. function isNil(value) {
  41356. return value == null;
  41357. }
  41358. module.exports = isNil;
  41359. },{}],287:[function(require,module,exports){
  41360. "use strict";
  41361. /**
  41362. * lodash 3.0.1 (Custom Build) <https://lodash.com/>
  41363. * Build: `lodash modern modularize exports="npm" -o ./`
  41364. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  41365. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  41366. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  41367. * Available under MIT license <https://lodash.com/license>
  41368. */
  41369. /**
  41370. * Checks if `value` is `undefined`.
  41371. *
  41372. * @static
  41373. * @memberOf _
  41374. * @category Lang
  41375. * @param {*} value The value to check.
  41376. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
  41377. * @example
  41378. *
  41379. * _.isUndefined(void 0);
  41380. * // => true
  41381. *
  41382. * _.isUndefined(null);
  41383. * // => false
  41384. */
  41385. function isUndefined(value) {
  41386. return value === undefined;
  41387. }
  41388. module.exports = isUndefined;
  41389. },{}],288:[function(require,module,exports){
  41390. (function (global){(function (){
  41391. "use strict";
  41392. /**
  41393. * lodash (Custom Build) <https://lodash.com/>
  41394. * Build: `lodash modularize exports="npm" -o ./`
  41395. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  41396. * Released under MIT license <https://lodash.com/license>
  41397. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  41398. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  41399. */
  41400. /** Used as the size to enable large array optimizations. */
  41401. var LARGE_ARRAY_SIZE = 200;
  41402. /** Used to stand-in for `undefined` hash values. */
  41403. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  41404. /** Used as references for various `Number` constants. */
  41405. var INFINITY = 1 / 0;
  41406. /** `Object#toString` result references. */
  41407. var funcTag = '[object Function]',
  41408. genTag = '[object GeneratorFunction]';
  41409. /**
  41410. * Used to match `RegExp`
  41411. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  41412. */
  41413. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  41414. /** Used to detect host constructors (Safari). */
  41415. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  41416. /** Detect free variable `global` from Node.js. */
  41417. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  41418. /** Detect free variable `self`. */
  41419. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  41420. /** Used as a reference to the global object. */
  41421. var root = freeGlobal || freeSelf || Function('return this')();
  41422. /**
  41423. * A specialized version of `_.includes` for arrays without support for
  41424. * specifying an index to search from.
  41425. *
  41426. * @private
  41427. * @param {Array} [array] The array to inspect.
  41428. * @param {*} target The value to search for.
  41429. * @returns {boolean} Returns `true` if `target` is found, else `false`.
  41430. */
  41431. function arrayIncludes(array, value) {
  41432. var length = array ? array.length : 0;
  41433. return !!length && baseIndexOf(array, value, 0) > -1;
  41434. }
  41435. /**
  41436. * This function is like `arrayIncludes` except that it accepts a comparator.
  41437. *
  41438. * @private
  41439. * @param {Array} [array] The array to inspect.
  41440. * @param {*} target The value to search for.
  41441. * @param {Function} comparator The comparator invoked per element.
  41442. * @returns {boolean} Returns `true` if `target` is found, else `false`.
  41443. */
  41444. function arrayIncludesWith(array, value, comparator) {
  41445. var index = -1,
  41446. length = array ? array.length : 0;
  41447. while (++index < length) {
  41448. if (comparator(value, array[index])) {
  41449. return true;
  41450. }
  41451. }
  41452. return false;
  41453. }
  41454. /**
  41455. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  41456. * support for iteratee shorthands.
  41457. *
  41458. * @private
  41459. * @param {Array} array The array to inspect.
  41460. * @param {Function} predicate The function invoked per iteration.
  41461. * @param {number} fromIndex The index to search from.
  41462. * @param {boolean} [fromRight] Specify iterating from right to left.
  41463. * @returns {number} Returns the index of the matched value, else `-1`.
  41464. */
  41465. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  41466. var length = array.length,
  41467. index = fromIndex + (fromRight ? 1 : -1);
  41468. while (fromRight ? index-- : ++index < length) {
  41469. if (predicate(array[index], index, array)) {
  41470. return index;
  41471. }
  41472. }
  41473. return -1;
  41474. }
  41475. /**
  41476. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  41477. *
  41478. * @private
  41479. * @param {Array} array The array to inspect.
  41480. * @param {*} value The value to search for.
  41481. * @param {number} fromIndex The index to search from.
  41482. * @returns {number} Returns the index of the matched value, else `-1`.
  41483. */
  41484. function baseIndexOf(array, value, fromIndex) {
  41485. if (value !== value) {
  41486. return baseFindIndex(array, baseIsNaN, fromIndex);
  41487. }
  41488. var index = fromIndex - 1,
  41489. length = array.length;
  41490. while (++index < length) {
  41491. if (array[index] === value) {
  41492. return index;
  41493. }
  41494. }
  41495. return -1;
  41496. }
  41497. /**
  41498. * The base implementation of `_.isNaN` without support for number objects.
  41499. *
  41500. * @private
  41501. * @param {*} value The value to check.
  41502. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  41503. */
  41504. function baseIsNaN(value) {
  41505. return value !== value;
  41506. }
  41507. /**
  41508. * Checks if a cache value for `key` exists.
  41509. *
  41510. * @private
  41511. * @param {Object} cache The cache to query.
  41512. * @param {string} key The key of the entry to check.
  41513. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  41514. */
  41515. function cacheHas(cache, key) {
  41516. return cache.has(key);
  41517. }
  41518. /**
  41519. * Gets the value at `key` of `object`.
  41520. *
  41521. * @private
  41522. * @param {Object} [object] The object to query.
  41523. * @param {string} key The key of the property to get.
  41524. * @returns {*} Returns the property value.
  41525. */
  41526. function getValue(object, key) {
  41527. return object == null ? undefined : object[key];
  41528. }
  41529. /**
  41530. * Checks if `value` is a host object in IE < 9.
  41531. *
  41532. * @private
  41533. * @param {*} value The value to check.
  41534. * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
  41535. */
  41536. function isHostObject(value) {
  41537. // Many host objects are `Object` objects that can coerce to strings
  41538. // despite having improperly defined `toString` methods.
  41539. var result = false;
  41540. if (value != null && typeof value.toString != 'function') {
  41541. try {
  41542. result = !!(value + '');
  41543. } catch (e) {}
  41544. }
  41545. return result;
  41546. }
  41547. /**
  41548. * Converts `set` to an array of its values.
  41549. *
  41550. * @private
  41551. * @param {Object} set The set to convert.
  41552. * @returns {Array} Returns the values.
  41553. */
  41554. function setToArray(set) {
  41555. var index = -1,
  41556. result = Array(set.size);
  41557. set.forEach(function (value) {
  41558. result[++index] = value;
  41559. });
  41560. return result;
  41561. }
  41562. /** Used for built-in method references. */
  41563. var arrayProto = Array.prototype,
  41564. funcProto = Function.prototype,
  41565. objectProto = Object.prototype;
  41566. /** Used to detect overreaching core-js shims. */
  41567. var coreJsData = root['__core-js_shared__'];
  41568. /** Used to detect methods masquerading as native. */
  41569. var maskSrcKey = function () {
  41570. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  41571. return uid ? 'Symbol(src)_1.' + uid : '';
  41572. }();
  41573. /** Used to resolve the decompiled source of functions. */
  41574. var funcToString = funcProto.toString;
  41575. /** Used to check objects for own properties. */
  41576. var hasOwnProperty = objectProto.hasOwnProperty;
  41577. /**
  41578. * Used to resolve the
  41579. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  41580. * of values.
  41581. */
  41582. var objectToString = objectProto.toString;
  41583. /** Used to detect if a method is native. */
  41584. var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
  41585. /** Built-in value references. */
  41586. var splice = arrayProto.splice;
  41587. /* Built-in method references that are verified to be native. */
  41588. var Map = getNative(root, 'Map'),
  41589. Set = getNative(root, 'Set'),
  41590. nativeCreate = getNative(Object, 'create');
  41591. /**
  41592. * Creates a hash object.
  41593. *
  41594. * @private
  41595. * @constructor
  41596. * @param {Array} [entries] The key-value pairs to cache.
  41597. */
  41598. function Hash(entries) {
  41599. var index = -1,
  41600. length = entries ? entries.length : 0;
  41601. this.clear();
  41602. while (++index < length) {
  41603. var entry = entries[index];
  41604. this.set(entry[0], entry[1]);
  41605. }
  41606. }
  41607. /**
  41608. * Removes all key-value entries from the hash.
  41609. *
  41610. * @private
  41611. * @name clear
  41612. * @memberOf Hash
  41613. */
  41614. function hashClear() {
  41615. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  41616. }
  41617. /**
  41618. * Removes `key` and its value from the hash.
  41619. *
  41620. * @private
  41621. * @name delete
  41622. * @memberOf Hash
  41623. * @param {Object} hash The hash to modify.
  41624. * @param {string} key The key of the value to remove.
  41625. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  41626. */
  41627. function hashDelete(key) {
  41628. return this.has(key) && delete this.__data__[key];
  41629. }
  41630. /**
  41631. * Gets the hash value for `key`.
  41632. *
  41633. * @private
  41634. * @name get
  41635. * @memberOf Hash
  41636. * @param {string} key The key of the value to get.
  41637. * @returns {*} Returns the entry value.
  41638. */
  41639. function hashGet(key) {
  41640. var data = this.__data__;
  41641. if (nativeCreate) {
  41642. var result = data[key];
  41643. return result === HASH_UNDEFINED ? undefined : result;
  41644. }
  41645. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  41646. }
  41647. /**
  41648. * Checks if a hash value for `key` exists.
  41649. *
  41650. * @private
  41651. * @name has
  41652. * @memberOf Hash
  41653. * @param {string} key The key of the entry to check.
  41654. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  41655. */
  41656. function hashHas(key) {
  41657. var data = this.__data__;
  41658. return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
  41659. }
  41660. /**
  41661. * Sets the hash `key` to `value`.
  41662. *
  41663. * @private
  41664. * @name set
  41665. * @memberOf Hash
  41666. * @param {string} key The key of the value to set.
  41667. * @param {*} value The value to set.
  41668. * @returns {Object} Returns the hash instance.
  41669. */
  41670. function hashSet(key, value) {
  41671. var data = this.__data__;
  41672. data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value;
  41673. return this;
  41674. }
  41675. // Add methods to `Hash`.
  41676. Hash.prototype.clear = hashClear;
  41677. Hash.prototype['delete'] = hashDelete;
  41678. Hash.prototype.get = hashGet;
  41679. Hash.prototype.has = hashHas;
  41680. Hash.prototype.set = hashSet;
  41681. /**
  41682. * Creates an list cache object.
  41683. *
  41684. * @private
  41685. * @constructor
  41686. * @param {Array} [entries] The key-value pairs to cache.
  41687. */
  41688. function ListCache(entries) {
  41689. var index = -1,
  41690. length = entries ? entries.length : 0;
  41691. this.clear();
  41692. while (++index < length) {
  41693. var entry = entries[index];
  41694. this.set(entry[0], entry[1]);
  41695. }
  41696. }
  41697. /**
  41698. * Removes all key-value entries from the list cache.
  41699. *
  41700. * @private
  41701. * @name clear
  41702. * @memberOf ListCache
  41703. */
  41704. function listCacheClear() {
  41705. this.__data__ = [];
  41706. }
  41707. /**
  41708. * Removes `key` and its value from the list cache.
  41709. *
  41710. * @private
  41711. * @name delete
  41712. * @memberOf ListCache
  41713. * @param {string} key The key of the value to remove.
  41714. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  41715. */
  41716. function listCacheDelete(key) {
  41717. var data = this.__data__,
  41718. index = assocIndexOf(data, key);
  41719. if (index < 0) {
  41720. return false;
  41721. }
  41722. var lastIndex = data.length - 1;
  41723. if (index == lastIndex) {
  41724. data.pop();
  41725. } else {
  41726. splice.call(data, index, 1);
  41727. }
  41728. return true;
  41729. }
  41730. /**
  41731. * Gets the list cache value for `key`.
  41732. *
  41733. * @private
  41734. * @name get
  41735. * @memberOf ListCache
  41736. * @param {string} key The key of the value to get.
  41737. * @returns {*} Returns the entry value.
  41738. */
  41739. function listCacheGet(key) {
  41740. var data = this.__data__,
  41741. index = assocIndexOf(data, key);
  41742. return index < 0 ? undefined : data[index][1];
  41743. }
  41744. /**
  41745. * Checks if a list cache value for `key` exists.
  41746. *
  41747. * @private
  41748. * @name has
  41749. * @memberOf ListCache
  41750. * @param {string} key The key of the entry to check.
  41751. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  41752. */
  41753. function listCacheHas(key) {
  41754. return assocIndexOf(this.__data__, key) > -1;
  41755. }
  41756. /**
  41757. * Sets the list cache `key` to `value`.
  41758. *
  41759. * @private
  41760. * @name set
  41761. * @memberOf ListCache
  41762. * @param {string} key The key of the value to set.
  41763. * @param {*} value The value to set.
  41764. * @returns {Object} Returns the list cache instance.
  41765. */
  41766. function listCacheSet(key, value) {
  41767. var data = this.__data__,
  41768. index = assocIndexOf(data, key);
  41769. if (index < 0) {
  41770. data.push([key, value]);
  41771. } else {
  41772. data[index][1] = value;
  41773. }
  41774. return this;
  41775. }
  41776. // Add methods to `ListCache`.
  41777. ListCache.prototype.clear = listCacheClear;
  41778. ListCache.prototype['delete'] = listCacheDelete;
  41779. ListCache.prototype.get = listCacheGet;
  41780. ListCache.prototype.has = listCacheHas;
  41781. ListCache.prototype.set = listCacheSet;
  41782. /**
  41783. * Creates a map cache object to store key-value pairs.
  41784. *
  41785. * @private
  41786. * @constructor
  41787. * @param {Array} [entries] The key-value pairs to cache.
  41788. */
  41789. function MapCache(entries) {
  41790. var index = -1,
  41791. length = entries ? entries.length : 0;
  41792. this.clear();
  41793. while (++index < length) {
  41794. var entry = entries[index];
  41795. this.set(entry[0], entry[1]);
  41796. }
  41797. }
  41798. /**
  41799. * Removes all key-value entries from the map.
  41800. *
  41801. * @private
  41802. * @name clear
  41803. * @memberOf MapCache
  41804. */
  41805. function mapCacheClear() {
  41806. this.__data__ = {
  41807. 'hash': new Hash(),
  41808. 'map': new (Map || ListCache)(),
  41809. 'string': new Hash()
  41810. };
  41811. }
  41812. /**
  41813. * Removes `key` and its value from the map.
  41814. *
  41815. * @private
  41816. * @name delete
  41817. * @memberOf MapCache
  41818. * @param {string} key The key of the value to remove.
  41819. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  41820. */
  41821. function mapCacheDelete(key) {
  41822. return getMapData(this, key)['delete'](key);
  41823. }
  41824. /**
  41825. * Gets the map value for `key`.
  41826. *
  41827. * @private
  41828. * @name get
  41829. * @memberOf MapCache
  41830. * @param {string} key The key of the value to get.
  41831. * @returns {*} Returns the entry value.
  41832. */
  41833. function mapCacheGet(key) {
  41834. return getMapData(this, key).get(key);
  41835. }
  41836. /**
  41837. * Checks if a map value for `key` exists.
  41838. *
  41839. * @private
  41840. * @name has
  41841. * @memberOf MapCache
  41842. * @param {string} key The key of the entry to check.
  41843. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  41844. */
  41845. function mapCacheHas(key) {
  41846. return getMapData(this, key).has(key);
  41847. }
  41848. /**
  41849. * Sets the map `key` to `value`.
  41850. *
  41851. * @private
  41852. * @name set
  41853. * @memberOf MapCache
  41854. * @param {string} key The key of the value to set.
  41855. * @param {*} value The value to set.
  41856. * @returns {Object} Returns the map cache instance.
  41857. */
  41858. function mapCacheSet(key, value) {
  41859. getMapData(this, key).set(key, value);
  41860. return this;
  41861. }
  41862. // Add methods to `MapCache`.
  41863. MapCache.prototype.clear = mapCacheClear;
  41864. MapCache.prototype['delete'] = mapCacheDelete;
  41865. MapCache.prototype.get = mapCacheGet;
  41866. MapCache.prototype.has = mapCacheHas;
  41867. MapCache.prototype.set = mapCacheSet;
  41868. /**
  41869. *
  41870. * Creates an array cache object to store unique values.
  41871. *
  41872. * @private
  41873. * @constructor
  41874. * @param {Array} [values] The values to cache.
  41875. */
  41876. function SetCache(values) {
  41877. var index = -1,
  41878. length = values ? values.length : 0;
  41879. this.__data__ = new MapCache();
  41880. while (++index < length) {
  41881. this.add(values[index]);
  41882. }
  41883. }
  41884. /**
  41885. * Adds `value` to the array cache.
  41886. *
  41887. * @private
  41888. * @name add
  41889. * @memberOf SetCache
  41890. * @alias push
  41891. * @param {*} value The value to cache.
  41892. * @returns {Object} Returns the cache instance.
  41893. */
  41894. function setCacheAdd(value) {
  41895. this.__data__.set(value, HASH_UNDEFINED);
  41896. return this;
  41897. }
  41898. /**
  41899. * Checks if `value` is in the array cache.
  41900. *
  41901. * @private
  41902. * @name has
  41903. * @memberOf SetCache
  41904. * @param {*} value The value to search for.
  41905. * @returns {number} Returns `true` if `value` is found, else `false`.
  41906. */
  41907. function setCacheHas(value) {
  41908. return this.__data__.has(value);
  41909. }
  41910. // Add methods to `SetCache`.
  41911. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
  41912. SetCache.prototype.has = setCacheHas;
  41913. /**
  41914. * Gets the index at which the `key` is found in `array` of key-value pairs.
  41915. *
  41916. * @private
  41917. * @param {Array} array The array to inspect.
  41918. * @param {*} key The key to search for.
  41919. * @returns {number} Returns the index of the matched value, else `-1`.
  41920. */
  41921. function assocIndexOf(array, key) {
  41922. var length = array.length;
  41923. while (length--) {
  41924. if (eq(array[length][0], key)) {
  41925. return length;
  41926. }
  41927. }
  41928. return -1;
  41929. }
  41930. /**
  41931. * The base implementation of `_.isNative` without bad shim checks.
  41932. *
  41933. * @private
  41934. * @param {*} value The value to check.
  41935. * @returns {boolean} Returns `true` if `value` is a native function,
  41936. * else `false`.
  41937. */
  41938. function baseIsNative(value) {
  41939. if (!isObject(value) || isMasked(value)) {
  41940. return false;
  41941. }
  41942. var pattern = isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor;
  41943. return pattern.test(toSource(value));
  41944. }
  41945. /**
  41946. * The base implementation of `_.uniqBy` without support for iteratee shorthands.
  41947. *
  41948. * @private
  41949. * @param {Array} array The array to inspect.
  41950. * @param {Function} [iteratee] The iteratee invoked per element.
  41951. * @param {Function} [comparator] The comparator invoked per element.
  41952. * @returns {Array} Returns the new duplicate free array.
  41953. */
  41954. function baseUniq(array, iteratee, comparator) {
  41955. var index = -1,
  41956. includes = arrayIncludes,
  41957. length = array.length,
  41958. isCommon = true,
  41959. result = [],
  41960. seen = result;
  41961. if (comparator) {
  41962. isCommon = false;
  41963. includes = arrayIncludesWith;
  41964. } else if (length >= LARGE_ARRAY_SIZE) {
  41965. var set = iteratee ? null : createSet(array);
  41966. if (set) {
  41967. return setToArray(set);
  41968. }
  41969. isCommon = false;
  41970. includes = cacheHas;
  41971. seen = new SetCache();
  41972. } else {
  41973. seen = iteratee ? [] : result;
  41974. }
  41975. outer: while (++index < length) {
  41976. var value = array[index],
  41977. computed = iteratee ? iteratee(value) : value;
  41978. value = comparator || value !== 0 ? value : 0;
  41979. if (isCommon && computed === computed) {
  41980. var seenIndex = seen.length;
  41981. while (seenIndex--) {
  41982. if (seen[seenIndex] === computed) {
  41983. continue outer;
  41984. }
  41985. }
  41986. if (iteratee) {
  41987. seen.push(computed);
  41988. }
  41989. result.push(value);
  41990. } else if (!includes(seen, computed, comparator)) {
  41991. if (seen !== result) {
  41992. seen.push(computed);
  41993. }
  41994. result.push(value);
  41995. }
  41996. }
  41997. return result;
  41998. }
  41999. /**
  42000. * Creates a set object of `values`.
  42001. *
  42002. * @private
  42003. * @param {Array} values The values to add to the set.
  42004. * @returns {Object} Returns the new set.
  42005. */
  42006. var createSet = !(Set && 1 / setToArray(new Set([, -0]))[1] == INFINITY) ? noop : function (values) {
  42007. return new Set(values);
  42008. };
  42009. /**
  42010. * Gets the data for `map`.
  42011. *
  42012. * @private
  42013. * @param {Object} map The map to query.
  42014. * @param {string} key The reference key.
  42015. * @returns {*} Returns the map data.
  42016. */
  42017. function getMapData(map, key) {
  42018. var data = map.__data__;
  42019. return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
  42020. }
  42021. /**
  42022. * Gets the native function at `key` of `object`.
  42023. *
  42024. * @private
  42025. * @param {Object} object The object to query.
  42026. * @param {string} key The key of the method to get.
  42027. * @returns {*} Returns the function if it's native, else `undefined`.
  42028. */
  42029. function getNative(object, key) {
  42030. var value = getValue(object, key);
  42031. return baseIsNative(value) ? value : undefined;
  42032. }
  42033. /**
  42034. * Checks if `value` is suitable for use as unique object key.
  42035. *
  42036. * @private
  42037. * @param {*} value The value to check.
  42038. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  42039. */
  42040. function isKeyable(value) {
  42041. var type = typeof value;
  42042. return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
  42043. }
  42044. /**
  42045. * Checks if `func` has its source masked.
  42046. *
  42047. * @private
  42048. * @param {Function} func The function to check.
  42049. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  42050. */
  42051. function isMasked(func) {
  42052. return !!maskSrcKey && maskSrcKey in func;
  42053. }
  42054. /**
  42055. * Converts `func` to its source code.
  42056. *
  42057. * @private
  42058. * @param {Function} func The function to process.
  42059. * @returns {string} Returns the source code.
  42060. */
  42061. function toSource(func) {
  42062. if (func != null) {
  42063. try {
  42064. return funcToString.call(func);
  42065. } catch (e) {}
  42066. try {
  42067. return func + '';
  42068. } catch (e) {}
  42069. }
  42070. return '';
  42071. }
  42072. /**
  42073. * Creates a duplicate-free version of an array, using
  42074. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  42075. * for equality comparisons, in which only the first occurrence of each
  42076. * element is kept.
  42077. *
  42078. * @static
  42079. * @memberOf _
  42080. * @since 0.1.0
  42081. * @category Array
  42082. * @param {Array} array The array to inspect.
  42083. * @returns {Array} Returns the new duplicate free array.
  42084. * @example
  42085. *
  42086. * _.uniq([2, 1, 2]);
  42087. * // => [2, 1]
  42088. */
  42089. function uniq(array) {
  42090. return array && array.length ? baseUniq(array) : [];
  42091. }
  42092. /**
  42093. * Performs a
  42094. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  42095. * comparison between two values to determine if they are equivalent.
  42096. *
  42097. * @static
  42098. * @memberOf _
  42099. * @since 4.0.0
  42100. * @category Lang
  42101. * @param {*} value The value to compare.
  42102. * @param {*} other The other value to compare.
  42103. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  42104. * @example
  42105. *
  42106. * var object = { 'a': 1 };
  42107. * var other = { 'a': 1 };
  42108. *
  42109. * _.eq(object, object);
  42110. * // => true
  42111. *
  42112. * _.eq(object, other);
  42113. * // => false
  42114. *
  42115. * _.eq('a', 'a');
  42116. * // => true
  42117. *
  42118. * _.eq('a', Object('a'));
  42119. * // => false
  42120. *
  42121. * _.eq(NaN, NaN);
  42122. * // => true
  42123. */
  42124. function eq(value, other) {
  42125. return value === other || value !== value && other !== other;
  42126. }
  42127. /**
  42128. * Checks if `value` is classified as a `Function` object.
  42129. *
  42130. * @static
  42131. * @memberOf _
  42132. * @since 0.1.0
  42133. * @category Lang
  42134. * @param {*} value The value to check.
  42135. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  42136. * @example
  42137. *
  42138. * _.isFunction(_);
  42139. * // => true
  42140. *
  42141. * _.isFunction(/abc/);
  42142. * // => false
  42143. */
  42144. function isFunction(value) {
  42145. // The use of `Object#toString` avoids issues with the `typeof` operator
  42146. // in Safari 8-9 which returns 'object' for typed array and other constructors.
  42147. var tag = isObject(value) ? objectToString.call(value) : '';
  42148. return tag == funcTag || tag == genTag;
  42149. }
  42150. /**
  42151. * Checks if `value` is the
  42152. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  42153. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  42154. *
  42155. * @static
  42156. * @memberOf _
  42157. * @since 0.1.0
  42158. * @category Lang
  42159. * @param {*} value The value to check.
  42160. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  42161. * @example
  42162. *
  42163. * _.isObject({});
  42164. * // => true
  42165. *
  42166. * _.isObject([1, 2, 3]);
  42167. * // => true
  42168. *
  42169. * _.isObject(_.noop);
  42170. * // => true
  42171. *
  42172. * _.isObject(null);
  42173. * // => false
  42174. */
  42175. function isObject(value) {
  42176. var type = typeof value;
  42177. return !!value && (type == 'object' || type == 'function');
  42178. }
  42179. /**
  42180. * This method returns `undefined`.
  42181. *
  42182. * @static
  42183. * @memberOf _
  42184. * @since 2.3.0
  42185. * @category Util
  42186. * @example
  42187. *
  42188. * _.times(2, _.noop);
  42189. * // => [undefined, undefined]
  42190. */
  42191. function noop() {
  42192. // No operation performed.
  42193. }
  42194. module.exports = uniq;
  42195. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  42196. },{}],289:[function(require,module,exports){
  42197. 'use strict';
  42198. var inherits = require('inherits');
  42199. var HashBase = require('hash-base');
  42200. var Buffer = require('safe-buffer').Buffer;
  42201. var ARRAY16 = new Array(16);
  42202. function MD5() {
  42203. HashBase.call(this, 64);
  42204. // state
  42205. this._a = 0x67452301;
  42206. this._b = 0xefcdab89;
  42207. this._c = 0x98badcfe;
  42208. this._d = 0x10325476;
  42209. }
  42210. inherits(MD5, HashBase);
  42211. MD5.prototype._update = function () {
  42212. var M = ARRAY16;
  42213. for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4);
  42214. var a = this._a;
  42215. var b = this._b;
  42216. var c = this._c;
  42217. var d = this._d;
  42218. a = fnF(a, b, c, d, M[0], 0xd76aa478, 7);
  42219. d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12);
  42220. c = fnF(c, d, a, b, M[2], 0x242070db, 17);
  42221. b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22);
  42222. a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7);
  42223. d = fnF(d, a, b, c, M[5], 0x4787c62a, 12);
  42224. c = fnF(c, d, a, b, M[6], 0xa8304613, 17);
  42225. b = fnF(b, c, d, a, M[7], 0xfd469501, 22);
  42226. a = fnF(a, b, c, d, M[8], 0x698098d8, 7);
  42227. d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12);
  42228. c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17);
  42229. b = fnF(b, c, d, a, M[11], 0x895cd7be, 22);
  42230. a = fnF(a, b, c, d, M[12], 0x6b901122, 7);
  42231. d = fnF(d, a, b, c, M[13], 0xfd987193, 12);
  42232. c = fnF(c, d, a, b, M[14], 0xa679438e, 17);
  42233. b = fnF(b, c, d, a, M[15], 0x49b40821, 22);
  42234. a = fnG(a, b, c, d, M[1], 0xf61e2562, 5);
  42235. d = fnG(d, a, b, c, M[6], 0xc040b340, 9);
  42236. c = fnG(c, d, a, b, M[11], 0x265e5a51, 14);
  42237. b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20);
  42238. a = fnG(a, b, c, d, M[5], 0xd62f105d, 5);
  42239. d = fnG(d, a, b, c, M[10], 0x02441453, 9);
  42240. c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14);
  42241. b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20);
  42242. a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5);
  42243. d = fnG(d, a, b, c, M[14], 0xc33707d6, 9);
  42244. c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14);
  42245. b = fnG(b, c, d, a, M[8], 0x455a14ed, 20);
  42246. a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5);
  42247. d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9);
  42248. c = fnG(c, d, a, b, M[7], 0x676f02d9, 14);
  42249. b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20);
  42250. a = fnH(a, b, c, d, M[5], 0xfffa3942, 4);
  42251. d = fnH(d, a, b, c, M[8], 0x8771f681, 11);
  42252. c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16);
  42253. b = fnH(b, c, d, a, M[14], 0xfde5380c, 23);
  42254. a = fnH(a, b, c, d, M[1], 0xa4beea44, 4);
  42255. d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11);
  42256. c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16);
  42257. b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23);
  42258. a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4);
  42259. d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11);
  42260. c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16);
  42261. b = fnH(b, c, d, a, M[6], 0x04881d05, 23);
  42262. a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4);
  42263. d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11);
  42264. c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16);
  42265. b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23);
  42266. a = fnI(a, b, c, d, M[0], 0xf4292244, 6);
  42267. d = fnI(d, a, b, c, M[7], 0x432aff97, 10);
  42268. c = fnI(c, d, a, b, M[14], 0xab9423a7, 15);
  42269. b = fnI(b, c, d, a, M[5], 0xfc93a039, 21);
  42270. a = fnI(a, b, c, d, M[12], 0x655b59c3, 6);
  42271. d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10);
  42272. c = fnI(c, d, a, b, M[10], 0xffeff47d, 15);
  42273. b = fnI(b, c, d, a, M[1], 0x85845dd1, 21);
  42274. a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6);
  42275. d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10);
  42276. c = fnI(c, d, a, b, M[6], 0xa3014314, 15);
  42277. b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21);
  42278. a = fnI(a, b, c, d, M[4], 0xf7537e82, 6);
  42279. d = fnI(d, a, b, c, M[11], 0xbd3af235, 10);
  42280. c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15);
  42281. b = fnI(b, c, d, a, M[9], 0xeb86d391, 21);
  42282. this._a = this._a + a | 0;
  42283. this._b = this._b + b | 0;
  42284. this._c = this._c + c | 0;
  42285. this._d = this._d + d | 0;
  42286. };
  42287. MD5.prototype._digest = function () {
  42288. // create padding and handle blocks
  42289. this._block[this._blockOffset++] = 0x80;
  42290. if (this._blockOffset > 56) {
  42291. this._block.fill(0, this._blockOffset, 64);
  42292. this._update();
  42293. this._blockOffset = 0;
  42294. }
  42295. this._block.fill(0, this._blockOffset, 56);
  42296. this._block.writeUInt32LE(this._length[0], 56);
  42297. this._block.writeUInt32LE(this._length[1], 60);
  42298. this._update();
  42299. // produce result
  42300. var buffer = Buffer.allocUnsafe(16);
  42301. buffer.writeInt32LE(this._a, 0);
  42302. buffer.writeInt32LE(this._b, 4);
  42303. buffer.writeInt32LE(this._c, 8);
  42304. buffer.writeInt32LE(this._d, 12);
  42305. return buffer;
  42306. };
  42307. function rotl(x, n) {
  42308. return x << n | x >>> 32 - n;
  42309. }
  42310. function fnF(a, b, c, d, m, k, s) {
  42311. return rotl(a + (b & c | ~b & d) + m + k | 0, s) + b | 0;
  42312. }
  42313. function fnG(a, b, c, d, m, k, s) {
  42314. return rotl(a + (b & d | c & ~d) + m + k | 0, s) + b | 0;
  42315. }
  42316. function fnH(a, b, c, d, m, k, s) {
  42317. return rotl(a + (b ^ c ^ d) + m + k | 0, s) + b | 0;
  42318. }
  42319. function fnI(a, b, c, d, m, k, s) {
  42320. return rotl(a + (c ^ (b | ~d)) + m + k | 0, s) + b | 0;
  42321. }
  42322. module.exports = MD5;
  42323. },{"hash-base":264,"inherits":279,"safe-buffer":332}],290:[function(require,module,exports){
  42324. "use strict";
  42325. var bn = require('bn.js');
  42326. var brorand = require('brorand');
  42327. function MillerRabin(rand) {
  42328. this.rand = rand || new brorand.Rand();
  42329. }
  42330. module.exports = MillerRabin;
  42331. MillerRabin.create = function create(rand) {
  42332. return new MillerRabin(rand);
  42333. };
  42334. MillerRabin.prototype._randbelow = function _randbelow(n) {
  42335. var len = n.bitLength();
  42336. var min_bytes = Math.ceil(len / 8);
  42337. // Generage random bytes until a number less than n is found.
  42338. // This ensures that 0..n-1 have an equal probability of being selected.
  42339. do var a = new bn(this.rand.generate(min_bytes)); while (a.cmp(n) >= 0);
  42340. return a;
  42341. };
  42342. MillerRabin.prototype._randrange = function _randrange(start, stop) {
  42343. // Generate a random number greater than or equal to start and less than stop.
  42344. var size = stop.sub(start);
  42345. return start.add(this._randbelow(size));
  42346. };
  42347. MillerRabin.prototype.test = function test(n, k, cb) {
  42348. var len = n.bitLength();
  42349. var red = bn.mont(n);
  42350. var rone = new bn(1).toRed(red);
  42351. if (!k) k = Math.max(1, len / 48 | 0);
  42352. // Find d and s, (n - 1) = (2 ^ s) * d;
  42353. var n1 = n.subn(1);
  42354. for (var s = 0; !n1.testn(s); s++) {}
  42355. var d = n.shrn(s);
  42356. var rn1 = n1.toRed(red);
  42357. var prime = true;
  42358. for (; k > 0; k--) {
  42359. var a = this._randrange(new bn(2), n1);
  42360. if (cb) cb(a);
  42361. var x = a.toRed(red).redPow(d);
  42362. if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue;
  42363. for (var i = 1; i < s; i++) {
  42364. x = x.redSqr();
  42365. if (x.cmp(rone) === 0) return false;
  42366. if (x.cmp(rn1) === 0) break;
  42367. }
  42368. if (i === s) return false;
  42369. }
  42370. return prime;
  42371. };
  42372. MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
  42373. var len = n.bitLength();
  42374. var red = bn.mont(n);
  42375. var rone = new bn(1).toRed(red);
  42376. if (!k) k = Math.max(1, len / 48 | 0);
  42377. // Find d and s, (n - 1) = (2 ^ s) * d;
  42378. var n1 = n.subn(1);
  42379. for (var s = 0; !n1.testn(s); s++) {}
  42380. var d = n.shrn(s);
  42381. var rn1 = n1.toRed(red);
  42382. for (; k > 0; k--) {
  42383. var a = this._randrange(new bn(2), n1);
  42384. var g = n.gcd(a);
  42385. if (g.cmpn(1) !== 0) return g;
  42386. var x = a.toRed(red).redPow(d);
  42387. if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue;
  42388. for (var i = 1; i < s; i++) {
  42389. x = x.redSqr();
  42390. if (x.cmp(rone) === 0) return x.fromRed().subn(1).gcd(n);
  42391. if (x.cmp(rn1) === 0) break;
  42392. }
  42393. if (i === s) {
  42394. x = x.redSqr();
  42395. return x.fromRed().subn(1).gcd(n);
  42396. }
  42397. }
  42398. return false;
  42399. };
  42400. },{"bn.js":291,"brorand":187}],291:[function(require,module,exports){
  42401. arguments[4][184][0].apply(exports,arguments)
  42402. },{"buffer":188,"dup":184}],292:[function(require,module,exports){
  42403. "use strict";
  42404. module.exports = assert;
  42405. function assert(val, msg) {
  42406. if (!val) throw new Error(msg || 'Assertion failed');
  42407. }
  42408. assert.equal = function assertEqual(l, r, msg) {
  42409. if (l != r) throw new Error(msg || 'Assertion failed: ' + l + ' != ' + r);
  42410. };
  42411. },{}],293:[function(require,module,exports){
  42412. 'use strict';
  42413. var utils = exports;
  42414. function toArray(msg, enc) {
  42415. if (Array.isArray(msg)) return msg.slice();
  42416. if (!msg) return [];
  42417. var res = [];
  42418. if (typeof msg !== 'string') {
  42419. for (var i = 0; i < msg.length; i++) res[i] = msg[i] | 0;
  42420. return res;
  42421. }
  42422. if (enc === 'hex') {
  42423. msg = msg.replace(/[^a-z0-9]+/ig, '');
  42424. if (msg.length % 2 !== 0) msg = '0' + msg;
  42425. for (var i = 0; i < msg.length; i += 2) res.push(parseInt(msg[i] + msg[i + 1], 16));
  42426. } else {
  42427. for (var i = 0; i < msg.length; i++) {
  42428. var c = msg.charCodeAt(i);
  42429. var hi = c >> 8;
  42430. var lo = c & 0xff;
  42431. if (hi) res.push(hi, lo);else res.push(lo);
  42432. }
  42433. }
  42434. return res;
  42435. }
  42436. utils.toArray = toArray;
  42437. function zero2(word) {
  42438. if (word.length === 1) return '0' + word;else return word;
  42439. }
  42440. utils.zero2 = zero2;
  42441. function toHex(msg) {
  42442. var res = '';
  42443. for (var i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16));
  42444. return res;
  42445. }
  42446. utils.toHex = toHex;
  42447. utils.encode = function encode(arr, enc) {
  42448. if (enc === 'hex') return toHex(arr);else return arr;
  42449. };
  42450. },{}],294:[function(require,module,exports){
  42451. module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
  42452. "2.16.840.1.101.3.4.1.2": "aes-128-cbc",
  42453. "2.16.840.1.101.3.4.1.3": "aes-128-ofb",
  42454. "2.16.840.1.101.3.4.1.4": "aes-128-cfb",
  42455. "2.16.840.1.101.3.4.1.21": "aes-192-ecb",
  42456. "2.16.840.1.101.3.4.1.22": "aes-192-cbc",
  42457. "2.16.840.1.101.3.4.1.23": "aes-192-ofb",
  42458. "2.16.840.1.101.3.4.1.24": "aes-192-cfb",
  42459. "2.16.840.1.101.3.4.1.41": "aes-256-ecb",
  42460. "2.16.840.1.101.3.4.1.42": "aes-256-cbc",
  42461. "2.16.840.1.101.3.4.1.43": "aes-256-ofb",
  42462. "2.16.840.1.101.3.4.1.44": "aes-256-cfb"
  42463. }
  42464. },{}],295:[function(require,module,exports){
  42465. // from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
  42466. // Fedor, you are amazing.
  42467. 'use strict';
  42468. var asn1 = require('asn1.js');
  42469. exports.certificate = require('./certificate');
  42470. var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
  42471. this.seq().obj(this.key('version').int(), this.key('modulus').int(), this.key('publicExponent').int(), this.key('privateExponent').int(), this.key('prime1').int(), this.key('prime2').int(), this.key('exponent1').int(), this.key('exponent2').int(), this.key('coefficient').int());
  42472. });
  42473. exports.RSAPrivateKey = RSAPrivateKey;
  42474. var RSAPublicKey = asn1.define('RSAPublicKey', function () {
  42475. this.seq().obj(this.key('modulus').int(), this.key('publicExponent').int());
  42476. });
  42477. exports.RSAPublicKey = RSAPublicKey;
  42478. var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
  42479. this.seq().obj(this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr());
  42480. });
  42481. exports.PublicKey = PublicKey;
  42482. var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
  42483. this.seq().obj(this.key('algorithm').objid(), this.key('none').null_().optional(), this.key('curve').objid().optional(), this.key('params').seq().obj(this.key('p').int(), this.key('q').int(), this.key('g').int()).optional());
  42484. });
  42485. var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
  42486. this.seq().obj(this.key('version').int(), this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPrivateKey').octstr());
  42487. });
  42488. exports.PrivateKey = PrivateKeyInfo;
  42489. var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
  42490. this.seq().obj(this.key('algorithm').seq().obj(this.key('id').objid(), this.key('decrypt').seq().obj(this.key('kde').seq().obj(this.key('id').objid(), this.key('kdeparams').seq().obj(this.key('salt').octstr(), this.key('iters').int())), this.key('cipher').seq().obj(this.key('algo').objid(), this.key('iv').octstr()))), this.key('subjectPrivateKey').octstr());
  42491. });
  42492. exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo;
  42493. var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
  42494. this.seq().obj(this.key('version').int(), this.key('p').int(), this.key('q').int(), this.key('g').int(), this.key('pub_key').int(), this.key('priv_key').int());
  42495. });
  42496. exports.DSAPrivateKey = DSAPrivateKey;
  42497. exports.DSAparam = asn1.define('DSAparam', function () {
  42498. this.int();
  42499. });
  42500. var ECPrivateKey = asn1.define('ECPrivateKey', function () {
  42501. this.seq().obj(this.key('version').int(), this.key('privateKey').octstr(), this.key('parameters').optional().explicit(0).use(ECParameters), this.key('publicKey').optional().explicit(1).bitstr());
  42502. });
  42503. exports.ECPrivateKey = ECPrivateKey;
  42504. var ECParameters = asn1.define('ECParameters', function () {
  42505. this.choice({
  42506. namedCurve: this.objid()
  42507. });
  42508. });
  42509. exports.signature = asn1.define('signature', function () {
  42510. this.seq().obj(this.key('r').int(), this.key('s').int());
  42511. });
  42512. },{"./certificate":296,"asn1.js":170}],296:[function(require,module,exports){
  42513. // from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
  42514. // thanks to @Rantanen
  42515. 'use strict';
  42516. var asn = require('asn1.js');
  42517. var Time = asn.define('Time', function () {
  42518. this.choice({
  42519. utcTime: this.utctime(),
  42520. generalTime: this.gentime()
  42521. });
  42522. });
  42523. var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
  42524. this.seq().obj(this.key('type').objid(), this.key('value').any());
  42525. });
  42526. var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
  42527. this.seq().obj(this.key('algorithm').objid(), this.key('parameters').optional(), this.key('curve').objid().optional());
  42528. });
  42529. var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
  42530. this.seq().obj(this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr());
  42531. });
  42532. var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
  42533. this.setof(AttributeTypeValue);
  42534. });
  42535. var RDNSequence = asn.define('RDNSequence', function () {
  42536. this.seqof(RelativeDistinguishedName);
  42537. });
  42538. var Name = asn.define('Name', function () {
  42539. this.choice({
  42540. rdnSequence: this.use(RDNSequence)
  42541. });
  42542. });
  42543. var Validity = asn.define('Validity', function () {
  42544. this.seq().obj(this.key('notBefore').use(Time), this.key('notAfter').use(Time));
  42545. });
  42546. var Extension = asn.define('Extension', function () {
  42547. this.seq().obj(this.key('extnID').objid(), this.key('critical').bool().def(false), this.key('extnValue').octstr());
  42548. });
  42549. var TBSCertificate = asn.define('TBSCertificate', function () {
  42550. this.seq().obj(this.key('version').explicit(0).int().optional(), this.key('serialNumber').int(), this.key('signature').use(AlgorithmIdentifier), this.key('issuer').use(Name), this.key('validity').use(Validity), this.key('subject').use(Name), this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), this.key('issuerUniqueID').implicit(1).bitstr().optional(), this.key('subjectUniqueID').implicit(2).bitstr().optional(), this.key('extensions').explicit(3).seqof(Extension).optional());
  42551. });
  42552. var X509Certificate = asn.define('X509Certificate', function () {
  42553. this.seq().obj(this.key('tbsCertificate').use(TBSCertificate), this.key('signatureAlgorithm').use(AlgorithmIdentifier), this.key('signatureValue').bitstr());
  42554. });
  42555. module.exports = X509Certificate;
  42556. },{"asn1.js":170}],297:[function(require,module,exports){
  42557. "use strict";
  42558. // adapted from https://github.com/apatil/pemstrip
  42559. var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m;
  42560. var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m;
  42561. var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m;
  42562. var evp = require('evp_bytestokey');
  42563. var ciphers = require('browserify-aes');
  42564. var Buffer = require('safe-buffer').Buffer;
  42565. module.exports = function (okey, password) {
  42566. var key = okey.toString();
  42567. var match = key.match(findProc);
  42568. var decrypted;
  42569. if (!match) {
  42570. var match2 = key.match(fullRegex);
  42571. decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ''), 'base64');
  42572. } else {
  42573. var suite = 'aes' + match[1];
  42574. var iv = Buffer.from(match[2], 'hex');
  42575. var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64');
  42576. var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key;
  42577. var out = [];
  42578. var cipher = ciphers.createDecipheriv(suite, cipherKey, iv);
  42579. out.push(cipher.update(cipherText));
  42580. out.push(cipher.final());
  42581. decrypted = Buffer.concat(out);
  42582. }
  42583. var tag = key.match(startRegex)[1];
  42584. return {
  42585. tag: tag,
  42586. data: decrypted
  42587. };
  42588. };
  42589. },{"browserify-aes":191,"evp_bytestokey":262,"safe-buffer":332}],298:[function(require,module,exports){
  42590. "use strict";
  42591. var asn1 = require('./asn1');
  42592. var aesid = require('./aesid.json');
  42593. var fixProc = require('./fixProc');
  42594. var ciphers = require('browserify-aes');
  42595. var compat = require('pbkdf2');
  42596. var Buffer = require('safe-buffer').Buffer;
  42597. module.exports = parseKeys;
  42598. function parseKeys(buffer) {
  42599. var password;
  42600. if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
  42601. password = buffer.passphrase;
  42602. buffer = buffer.key;
  42603. }
  42604. if (typeof buffer === 'string') {
  42605. buffer = Buffer.from(buffer);
  42606. }
  42607. var stripped = fixProc(buffer, password);
  42608. var type = stripped.tag;
  42609. var data = stripped.data;
  42610. var subtype, ndata;
  42611. switch (type) {
  42612. case 'CERTIFICATE':
  42613. ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo;
  42614. // falls through
  42615. case 'PUBLIC KEY':
  42616. if (!ndata) {
  42617. ndata = asn1.PublicKey.decode(data, 'der');
  42618. }
  42619. subtype = ndata.algorithm.algorithm.join('.');
  42620. switch (subtype) {
  42621. case '1.2.840.113549.1.1.1':
  42622. return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der');
  42623. case '1.2.840.10045.2.1':
  42624. ndata.subjectPrivateKey = ndata.subjectPublicKey;
  42625. return {
  42626. type: 'ec',
  42627. data: ndata
  42628. };
  42629. case '1.2.840.10040.4.1':
  42630. ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der');
  42631. return {
  42632. type: 'dsa',
  42633. data: ndata.algorithm.params
  42634. };
  42635. default:
  42636. throw new Error('unknown key id ' + subtype);
  42637. }
  42638. // throw new Error('unknown key type ' + type)
  42639. case 'ENCRYPTED PRIVATE KEY':
  42640. data = asn1.EncryptedPrivateKey.decode(data, 'der');
  42641. data = decrypt(data, password);
  42642. // falls through
  42643. case 'PRIVATE KEY':
  42644. ndata = asn1.PrivateKey.decode(data, 'der');
  42645. subtype = ndata.algorithm.algorithm.join('.');
  42646. switch (subtype) {
  42647. case '1.2.840.113549.1.1.1':
  42648. return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der');
  42649. case '1.2.840.10045.2.1':
  42650. return {
  42651. curve: ndata.algorithm.curve,
  42652. privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
  42653. };
  42654. case '1.2.840.10040.4.1':
  42655. ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der');
  42656. return {
  42657. type: 'dsa',
  42658. params: ndata.algorithm.params
  42659. };
  42660. default:
  42661. throw new Error('unknown key id ' + subtype);
  42662. }
  42663. // throw new Error('unknown key type ' + type)
  42664. case 'RSA PUBLIC KEY':
  42665. return asn1.RSAPublicKey.decode(data, 'der');
  42666. case 'RSA PRIVATE KEY':
  42667. return asn1.RSAPrivateKey.decode(data, 'der');
  42668. case 'DSA PRIVATE KEY':
  42669. return {
  42670. type: 'dsa',
  42671. params: asn1.DSAPrivateKey.decode(data, 'der')
  42672. };
  42673. case 'EC PRIVATE KEY':
  42674. data = asn1.ECPrivateKey.decode(data, 'der');
  42675. return {
  42676. curve: data.parameters.value,
  42677. privateKey: data.privateKey
  42678. };
  42679. default:
  42680. throw new Error('unknown key type ' + type);
  42681. }
  42682. }
  42683. parseKeys.signature = asn1.signature;
  42684. function decrypt(data, password) {
  42685. var salt = data.algorithm.decrypt.kde.kdeparams.salt;
  42686. var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10);
  42687. var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')];
  42688. var iv = data.algorithm.decrypt.cipher.iv;
  42689. var cipherText = data.subjectPrivateKey;
  42690. var keylen = parseInt(algo.split('-')[1], 10) / 8;
  42691. var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1');
  42692. var cipher = ciphers.createDecipheriv(algo, key, iv);
  42693. var out = [];
  42694. out.push(cipher.update(cipherText));
  42695. out.push(cipher.final());
  42696. return Buffer.concat(out);
  42697. }
  42698. },{"./aesid.json":294,"./asn1":295,"./fixProc":297,"browserify-aes":191,"pbkdf2":299,"safe-buffer":332}],299:[function(require,module,exports){
  42699. "use strict";
  42700. exports.pbkdf2 = require('./lib/async');
  42701. exports.pbkdf2Sync = require('./lib/sync');
  42702. },{"./lib/async":300,"./lib/sync":303}],300:[function(require,module,exports){
  42703. (function (global){(function (){
  42704. "use strict";
  42705. var Buffer = require('safe-buffer').Buffer;
  42706. var checkParameters = require('./precondition');
  42707. var defaultEncoding = require('./default-encoding');
  42708. var sync = require('./sync');
  42709. var toBuffer = require('./to-buffer');
  42710. var ZERO_BUF;
  42711. var subtle = global.crypto && global.crypto.subtle;
  42712. var toBrowser = {
  42713. sha: 'SHA-1',
  42714. 'sha-1': 'SHA-1',
  42715. sha1: 'SHA-1',
  42716. sha256: 'SHA-256',
  42717. 'sha-256': 'SHA-256',
  42718. sha384: 'SHA-384',
  42719. 'sha-384': 'SHA-384',
  42720. 'sha-512': 'SHA-512',
  42721. sha512: 'SHA-512'
  42722. };
  42723. var checks = [];
  42724. function checkNative(algo) {
  42725. if (global.process && !global.process.browser) {
  42726. return Promise.resolve(false);
  42727. }
  42728. if (!subtle || !subtle.importKey || !subtle.deriveBits) {
  42729. return Promise.resolve(false);
  42730. }
  42731. if (checks[algo] !== undefined) {
  42732. return checks[algo];
  42733. }
  42734. ZERO_BUF = ZERO_BUF || Buffer.alloc(8);
  42735. var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo).then(function () {
  42736. return true;
  42737. }).catch(function () {
  42738. return false;
  42739. });
  42740. checks[algo] = prom;
  42741. return prom;
  42742. }
  42743. var nextTick;
  42744. function getNextTick() {
  42745. if (nextTick) {
  42746. return nextTick;
  42747. }
  42748. if (global.process && global.process.nextTick) {
  42749. nextTick = global.process.nextTick;
  42750. } else if (global.queueMicrotask) {
  42751. nextTick = global.queueMicrotask;
  42752. } else if (global.setImmediate) {
  42753. nextTick = global.setImmediate;
  42754. } else {
  42755. nextTick = global.setTimeout;
  42756. }
  42757. return nextTick;
  42758. }
  42759. function browserPbkdf2(password, salt, iterations, length, algo) {
  42760. return subtle.importKey('raw', password, {
  42761. name: 'PBKDF2'
  42762. }, false, ['deriveBits']).then(function (key) {
  42763. return subtle.deriveBits({
  42764. name: 'PBKDF2',
  42765. salt: salt,
  42766. iterations: iterations,
  42767. hash: {
  42768. name: algo
  42769. }
  42770. }, key, length << 3);
  42771. }).then(function (res) {
  42772. return Buffer.from(res);
  42773. });
  42774. }
  42775. function resolvePromise(promise, callback) {
  42776. promise.then(function (out) {
  42777. getNextTick()(function () {
  42778. callback(null, out);
  42779. });
  42780. }, function (e) {
  42781. getNextTick()(function () {
  42782. callback(e);
  42783. });
  42784. });
  42785. }
  42786. module.exports = function (password, salt, iterations, keylen, digest, callback) {
  42787. if (typeof digest === 'function') {
  42788. callback = digest;
  42789. digest = undefined;
  42790. }
  42791. digest = digest || 'sha1';
  42792. var algo = toBrowser[digest.toLowerCase()];
  42793. if (!algo || typeof global.Promise !== 'function') {
  42794. getNextTick()(function () {
  42795. var out;
  42796. try {
  42797. out = sync(password, salt, iterations, keylen, digest);
  42798. } catch (e) {
  42799. return callback(e);
  42800. }
  42801. callback(null, out);
  42802. });
  42803. return;
  42804. }
  42805. checkParameters(iterations, keylen);
  42806. password = toBuffer(password, defaultEncoding, 'Password');
  42807. salt = toBuffer(salt, defaultEncoding, 'Salt');
  42808. if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2');
  42809. resolvePromise(checkNative(algo).then(function (resp) {
  42810. if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo);
  42811. return sync(password, salt, iterations, keylen, digest);
  42812. }), callback);
  42813. };
  42814. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  42815. },{"./default-encoding":301,"./precondition":302,"./sync":303,"./to-buffer":304,"safe-buffer":332}],301:[function(require,module,exports){
  42816. (function (process,global){(function (){
  42817. "use strict";
  42818. var defaultEncoding;
  42819. /* istanbul ignore next */
  42820. if (global.process && global.process.browser) {
  42821. defaultEncoding = 'utf-8';
  42822. } else if (global.process && global.process.version) {
  42823. var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10);
  42824. defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary';
  42825. } else {
  42826. defaultEncoding = 'utf-8';
  42827. }
  42828. module.exports = defaultEncoding;
  42829. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  42830. },{"_process":306}],302:[function(require,module,exports){
  42831. "use strict";
  42832. var MAX_ALLOC = Math.pow(2, 30) - 1; // default in iojs
  42833. module.exports = function (iterations, keylen) {
  42834. if (typeof iterations !== 'number') {
  42835. throw new TypeError('Iterations not a number');
  42836. }
  42837. if (iterations < 0) {
  42838. throw new TypeError('Bad iterations');
  42839. }
  42840. if (typeof keylen !== 'number') {
  42841. throw new TypeError('Key length not a number');
  42842. }
  42843. if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) {
  42844. /* eslint no-self-compare: 0 */
  42845. throw new TypeError('Bad key length');
  42846. }
  42847. };
  42848. },{}],303:[function(require,module,exports){
  42849. "use strict";
  42850. var md5 = require('create-hash/md5');
  42851. var RIPEMD160 = require('ripemd160');
  42852. var sha = require('sha.js');
  42853. var Buffer = require('safe-buffer').Buffer;
  42854. var checkParameters = require('./precondition');
  42855. var defaultEncoding = require('./default-encoding');
  42856. var toBuffer = require('./to-buffer');
  42857. var ZEROS = Buffer.alloc(128);
  42858. var sizes = {
  42859. md5: 16,
  42860. sha1: 20,
  42861. sha224: 28,
  42862. sha256: 32,
  42863. sha384: 48,
  42864. sha512: 64,
  42865. rmd160: 20,
  42866. ripemd160: 20
  42867. };
  42868. function Hmac(alg, key, saltLen) {
  42869. var hash = getDigest(alg);
  42870. var blocksize = alg === 'sha512' || alg === 'sha384' ? 128 : 64;
  42871. if (key.length > blocksize) {
  42872. key = hash(key);
  42873. } else if (key.length < blocksize) {
  42874. key = Buffer.concat([key, ZEROS], blocksize);
  42875. }
  42876. var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]);
  42877. var opad = Buffer.allocUnsafe(blocksize + sizes[alg]);
  42878. for (var i = 0; i < blocksize; i++) {
  42879. ipad[i] = key[i] ^ 0x36;
  42880. opad[i] = key[i] ^ 0x5C;
  42881. }
  42882. var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4);
  42883. ipad.copy(ipad1, 0, 0, blocksize);
  42884. this.ipad1 = ipad1;
  42885. this.ipad2 = ipad;
  42886. this.opad = opad;
  42887. this.alg = alg;
  42888. this.blocksize = blocksize;
  42889. this.hash = hash;
  42890. this.size = sizes[alg];
  42891. }
  42892. Hmac.prototype.run = function (data, ipad) {
  42893. data.copy(ipad, this.blocksize);
  42894. var h = this.hash(ipad);
  42895. h.copy(this.opad, this.blocksize);
  42896. return this.hash(this.opad);
  42897. };
  42898. function getDigest(alg) {
  42899. function shaFunc(data) {
  42900. return sha(alg).update(data).digest();
  42901. }
  42902. function rmd160Func(data) {
  42903. return new RIPEMD160().update(data).digest();
  42904. }
  42905. if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func;
  42906. if (alg === 'md5') return md5;
  42907. return shaFunc;
  42908. }
  42909. function pbkdf2(password, salt, iterations, keylen, digest) {
  42910. checkParameters(iterations, keylen);
  42911. password = toBuffer(password, defaultEncoding, 'Password');
  42912. salt = toBuffer(salt, defaultEncoding, 'Salt');
  42913. digest = digest || 'sha1';
  42914. var hmac = new Hmac(digest, password, salt.length);
  42915. var DK = Buffer.allocUnsafe(keylen);
  42916. var block1 = Buffer.allocUnsafe(salt.length + 4);
  42917. salt.copy(block1, 0, 0, salt.length);
  42918. var destPos = 0;
  42919. var hLen = sizes[digest];
  42920. var l = Math.ceil(keylen / hLen);
  42921. for (var i = 1; i <= l; i++) {
  42922. block1.writeUInt32BE(i, salt.length);
  42923. var T = hmac.run(block1, hmac.ipad1);
  42924. var U = T;
  42925. for (var j = 1; j < iterations; j++) {
  42926. U = hmac.run(U, hmac.ipad2);
  42927. for (var k = 0; k < hLen; k++) T[k] ^= U[k];
  42928. }
  42929. T.copy(DK, destPos);
  42930. destPos += hLen;
  42931. }
  42932. return DK;
  42933. }
  42934. module.exports = pbkdf2;
  42935. },{"./default-encoding":301,"./precondition":302,"./to-buffer":304,"create-hash/md5":226,"ripemd160":331,"safe-buffer":332,"sha.js":336}],304:[function(require,module,exports){
  42936. "use strict";
  42937. var Buffer = require('safe-buffer').Buffer;
  42938. module.exports = function (thing, encoding, name) {
  42939. if (Buffer.isBuffer(thing)) {
  42940. return thing;
  42941. } else if (typeof thing === 'string') {
  42942. return Buffer.from(thing, encoding);
  42943. } else if (ArrayBuffer.isView(thing)) {
  42944. return Buffer.from(thing.buffer);
  42945. } else {
  42946. throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView');
  42947. }
  42948. };
  42949. },{"safe-buffer":332}],305:[function(require,module,exports){
  42950. (function (process){(function (){
  42951. 'use strict';
  42952. if (typeof process === 'undefined' || !process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  42953. module.exports = {
  42954. nextTick: nextTick
  42955. };
  42956. } else {
  42957. module.exports = process;
  42958. }
  42959. function nextTick(fn, arg1, arg2, arg3) {
  42960. if (typeof fn !== 'function') {
  42961. throw new TypeError('"callback" argument must be a function');
  42962. }
  42963. var len = arguments.length;
  42964. var args, i;
  42965. switch (len) {
  42966. case 0:
  42967. case 1:
  42968. return process.nextTick(fn);
  42969. case 2:
  42970. return process.nextTick(function afterTickOne() {
  42971. fn.call(null, arg1);
  42972. });
  42973. case 3:
  42974. return process.nextTick(function afterTickTwo() {
  42975. fn.call(null, arg1, arg2);
  42976. });
  42977. case 4:
  42978. return process.nextTick(function afterTickThree() {
  42979. fn.call(null, arg1, arg2, arg3);
  42980. });
  42981. default:
  42982. args = new Array(len - 1);
  42983. i = 0;
  42984. while (i < args.length) {
  42985. args[i++] = arguments[i];
  42986. }
  42987. return process.nextTick(function afterTick() {
  42988. fn.apply(null, args);
  42989. });
  42990. }
  42991. }
  42992. }).call(this)}).call(this,require('_process'))
  42993. },{"_process":306}],306:[function(require,module,exports){
  42994. "use strict";
  42995. // shim for using process in browser
  42996. var process = module.exports = {};
  42997. // cached from whatever global is present so that test runners that stub it
  42998. // don't break things. But we need to wrap it in a try catch in case it is
  42999. // wrapped in strict mode code which doesn't define any globals. It's inside a
  43000. // function because try/catches deoptimize in certain engines.
  43001. var cachedSetTimeout;
  43002. var cachedClearTimeout;
  43003. function defaultSetTimout() {
  43004. throw new Error('setTimeout has not been defined');
  43005. }
  43006. function defaultClearTimeout() {
  43007. throw new Error('clearTimeout has not been defined');
  43008. }
  43009. (function () {
  43010. try {
  43011. if (typeof setTimeout === 'function') {
  43012. cachedSetTimeout = setTimeout;
  43013. } else {
  43014. cachedSetTimeout = defaultSetTimout;
  43015. }
  43016. } catch (e) {
  43017. cachedSetTimeout = defaultSetTimout;
  43018. }
  43019. try {
  43020. if (typeof clearTimeout === 'function') {
  43021. cachedClearTimeout = clearTimeout;
  43022. } else {
  43023. cachedClearTimeout = defaultClearTimeout;
  43024. }
  43025. } catch (e) {
  43026. cachedClearTimeout = defaultClearTimeout;
  43027. }
  43028. })();
  43029. function runTimeout(fun) {
  43030. if (cachedSetTimeout === setTimeout) {
  43031. //normal enviroments in sane situations
  43032. return setTimeout(fun, 0);
  43033. }
  43034. // if setTimeout wasn't available but was latter defined
  43035. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  43036. cachedSetTimeout = setTimeout;
  43037. return setTimeout(fun, 0);
  43038. }
  43039. try {
  43040. // when when somebody has screwed with setTimeout but no I.E. maddness
  43041. return cachedSetTimeout(fun, 0);
  43042. } catch (e) {
  43043. try {
  43044. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  43045. return cachedSetTimeout.call(null, fun, 0);
  43046. } catch (e) {
  43047. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  43048. return cachedSetTimeout.call(this, fun, 0);
  43049. }
  43050. }
  43051. }
  43052. function runClearTimeout(marker) {
  43053. if (cachedClearTimeout === clearTimeout) {
  43054. //normal enviroments in sane situations
  43055. return clearTimeout(marker);
  43056. }
  43057. // if clearTimeout wasn't available but was latter defined
  43058. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  43059. cachedClearTimeout = clearTimeout;
  43060. return clearTimeout(marker);
  43061. }
  43062. try {
  43063. // when when somebody has screwed with setTimeout but no I.E. maddness
  43064. return cachedClearTimeout(marker);
  43065. } catch (e) {
  43066. try {
  43067. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  43068. return cachedClearTimeout.call(null, marker);
  43069. } catch (e) {
  43070. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  43071. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  43072. return cachedClearTimeout.call(this, marker);
  43073. }
  43074. }
  43075. }
  43076. var queue = [];
  43077. var draining = false;
  43078. var currentQueue;
  43079. var queueIndex = -1;
  43080. function cleanUpNextTick() {
  43081. if (!draining || !currentQueue) {
  43082. return;
  43083. }
  43084. draining = false;
  43085. if (currentQueue.length) {
  43086. queue = currentQueue.concat(queue);
  43087. } else {
  43088. queueIndex = -1;
  43089. }
  43090. if (queue.length) {
  43091. drainQueue();
  43092. }
  43093. }
  43094. function drainQueue() {
  43095. if (draining) {
  43096. return;
  43097. }
  43098. var timeout = runTimeout(cleanUpNextTick);
  43099. draining = true;
  43100. var len = queue.length;
  43101. while (len) {
  43102. currentQueue = queue;
  43103. queue = [];
  43104. while (++queueIndex < len) {
  43105. if (currentQueue) {
  43106. currentQueue[queueIndex].run();
  43107. }
  43108. }
  43109. queueIndex = -1;
  43110. len = queue.length;
  43111. }
  43112. currentQueue = null;
  43113. draining = false;
  43114. runClearTimeout(timeout);
  43115. }
  43116. process.nextTick = function (fun) {
  43117. var args = new Array(arguments.length - 1);
  43118. if (arguments.length > 1) {
  43119. for (var i = 1; i < arguments.length; i++) {
  43120. args[i - 1] = arguments[i];
  43121. }
  43122. }
  43123. queue.push(new Item(fun, args));
  43124. if (queue.length === 1 && !draining) {
  43125. runTimeout(drainQueue);
  43126. }
  43127. };
  43128. // v8 likes predictible objects
  43129. function Item(fun, array) {
  43130. this.fun = fun;
  43131. this.array = array;
  43132. }
  43133. Item.prototype.run = function () {
  43134. this.fun.apply(null, this.array);
  43135. };
  43136. process.title = 'browser';
  43137. process.browser = true;
  43138. process.env = {};
  43139. process.argv = [];
  43140. process.version = ''; // empty string to avoid regexp issues
  43141. process.versions = {};
  43142. function noop() {}
  43143. process.on = noop;
  43144. process.addListener = noop;
  43145. process.once = noop;
  43146. process.off = noop;
  43147. process.removeListener = noop;
  43148. process.removeAllListeners = noop;
  43149. process.emit = noop;
  43150. process.prependListener = noop;
  43151. process.prependOnceListener = noop;
  43152. process.listeners = function (name) {
  43153. return [];
  43154. };
  43155. process.binding = function (name) {
  43156. throw new Error('process.binding is not supported');
  43157. };
  43158. process.cwd = function () {
  43159. return '/';
  43160. };
  43161. process.chdir = function (dir) {
  43162. throw new Error('process.chdir is not supported');
  43163. };
  43164. process.umask = function () {
  43165. return 0;
  43166. };
  43167. },{}],307:[function(require,module,exports){
  43168. "use strict";
  43169. exports.publicEncrypt = require('./publicEncrypt');
  43170. exports.privateDecrypt = require('./privateDecrypt');
  43171. exports.privateEncrypt = function privateEncrypt(key, buf) {
  43172. return exports.publicEncrypt(key, buf, true);
  43173. };
  43174. exports.publicDecrypt = function publicDecrypt(key, buf) {
  43175. return exports.privateDecrypt(key, buf, true);
  43176. };
  43177. },{"./privateDecrypt":310,"./publicEncrypt":311}],308:[function(require,module,exports){
  43178. "use strict";
  43179. var createHash = require('create-hash');
  43180. var Buffer = require('safe-buffer').Buffer;
  43181. module.exports = function (seed, len) {
  43182. var t = Buffer.alloc(0);
  43183. var i = 0;
  43184. var c;
  43185. while (t.length < len) {
  43186. c = i2ops(i++);
  43187. t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]);
  43188. }
  43189. return t.slice(0, len);
  43190. };
  43191. function i2ops(c) {
  43192. var out = Buffer.allocUnsafe(4);
  43193. out.writeUInt32BE(c, 0);
  43194. return out;
  43195. }
  43196. },{"create-hash":225,"safe-buffer":332}],309:[function(require,module,exports){
  43197. arguments[4][184][0].apply(exports,arguments)
  43198. },{"buffer":188,"dup":184}],310:[function(require,module,exports){
  43199. "use strict";
  43200. var parseKeys = require('parse-asn1');
  43201. var mgf = require('./mgf');
  43202. var xor = require('./xor');
  43203. var BN = require('bn.js');
  43204. var crt = require('browserify-rsa');
  43205. var createHash = require('create-hash');
  43206. var withPublic = require('./withPublic');
  43207. var Buffer = require('safe-buffer').Buffer;
  43208. module.exports = function privateDecrypt(privateKey, enc, reverse) {
  43209. var padding;
  43210. if (privateKey.padding) {
  43211. padding = privateKey.padding;
  43212. } else if (reverse) {
  43213. padding = 1;
  43214. } else {
  43215. padding = 4;
  43216. }
  43217. var key = parseKeys(privateKey);
  43218. var k = key.modulus.byteLength();
  43219. if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
  43220. throw new Error('decryption error');
  43221. }
  43222. var msg;
  43223. if (reverse) {
  43224. msg = withPublic(new BN(enc), key);
  43225. } else {
  43226. msg = crt(enc, key);
  43227. }
  43228. var zBuffer = Buffer.alloc(k - msg.length);
  43229. msg = Buffer.concat([zBuffer, msg], k);
  43230. if (padding === 4) {
  43231. return oaep(key, msg);
  43232. } else if (padding === 1) {
  43233. return pkcs1(key, msg, reverse);
  43234. } else if (padding === 3) {
  43235. return msg;
  43236. } else {
  43237. throw new Error('unknown padding');
  43238. }
  43239. };
  43240. function oaep(key, msg) {
  43241. var k = key.modulus.byteLength();
  43242. var iHash = createHash('sha1').update(Buffer.alloc(0)).digest();
  43243. var hLen = iHash.length;
  43244. if (msg[0] !== 0) {
  43245. throw new Error('decryption error');
  43246. }
  43247. var maskedSeed = msg.slice(1, hLen + 1);
  43248. var maskedDb = msg.slice(hLen + 1);
  43249. var seed = xor(maskedSeed, mgf(maskedDb, hLen));
  43250. var db = xor(maskedDb, mgf(seed, k - hLen - 1));
  43251. if (compare(iHash, db.slice(0, hLen))) {
  43252. throw new Error('decryption error');
  43253. }
  43254. var i = hLen;
  43255. while (db[i] === 0) {
  43256. i++;
  43257. }
  43258. if (db[i++] !== 1) {
  43259. throw new Error('decryption error');
  43260. }
  43261. return db.slice(i);
  43262. }
  43263. function pkcs1(key, msg, reverse) {
  43264. var p1 = msg.slice(0, 2);
  43265. var i = 2;
  43266. var status = 0;
  43267. while (msg[i++] !== 0) {
  43268. if (i >= msg.length) {
  43269. status++;
  43270. break;
  43271. }
  43272. }
  43273. var ps = msg.slice(2, i - 1);
  43274. if (p1.toString('hex') !== '0002' && !reverse || p1.toString('hex') !== '0001' && reverse) {
  43275. status++;
  43276. }
  43277. if (ps.length < 8) {
  43278. status++;
  43279. }
  43280. if (status) {
  43281. throw new Error('decryption error');
  43282. }
  43283. return msg.slice(i);
  43284. }
  43285. function compare(a, b) {
  43286. a = Buffer.from(a);
  43287. b = Buffer.from(b);
  43288. var dif = 0;
  43289. var len = a.length;
  43290. if (a.length !== b.length) {
  43291. dif++;
  43292. len = Math.min(a.length, b.length);
  43293. }
  43294. var i = -1;
  43295. while (++i < len) {
  43296. dif += a[i] ^ b[i];
  43297. }
  43298. return dif;
  43299. }
  43300. },{"./mgf":308,"./withPublic":312,"./xor":313,"bn.js":309,"browserify-rsa":209,"create-hash":225,"parse-asn1":298,"safe-buffer":332}],311:[function(require,module,exports){
  43301. "use strict";
  43302. var parseKeys = require('parse-asn1');
  43303. var randomBytes = require('randombytes');
  43304. var createHash = require('create-hash');
  43305. var mgf = require('./mgf');
  43306. var xor = require('./xor');
  43307. var BN = require('bn.js');
  43308. var withPublic = require('./withPublic');
  43309. var crt = require('browserify-rsa');
  43310. var Buffer = require('safe-buffer').Buffer;
  43311. module.exports = function publicEncrypt(publicKey, msg, reverse) {
  43312. var padding;
  43313. if (publicKey.padding) {
  43314. padding = publicKey.padding;
  43315. } else if (reverse) {
  43316. padding = 1;
  43317. } else {
  43318. padding = 4;
  43319. }
  43320. var key = parseKeys(publicKey);
  43321. var paddedMsg;
  43322. if (padding === 4) {
  43323. paddedMsg = oaep(key, msg);
  43324. } else if (padding === 1) {
  43325. paddedMsg = pkcs1(key, msg, reverse);
  43326. } else if (padding === 3) {
  43327. paddedMsg = new BN(msg);
  43328. if (paddedMsg.cmp(key.modulus) >= 0) {
  43329. throw new Error('data too long for modulus');
  43330. }
  43331. } else {
  43332. throw new Error('unknown padding');
  43333. }
  43334. if (reverse) {
  43335. return crt(paddedMsg, key);
  43336. } else {
  43337. return withPublic(paddedMsg, key);
  43338. }
  43339. };
  43340. function oaep(key, msg) {
  43341. var k = key.modulus.byteLength();
  43342. var mLen = msg.length;
  43343. var iHash = createHash('sha1').update(Buffer.alloc(0)).digest();
  43344. var hLen = iHash.length;
  43345. var hLen2 = 2 * hLen;
  43346. if (mLen > k - hLen2 - 2) {
  43347. throw new Error('message too long');
  43348. }
  43349. var ps = Buffer.alloc(k - mLen - hLen2 - 2);
  43350. var dblen = k - hLen - 1;
  43351. var seed = randomBytes(hLen);
  43352. var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen));
  43353. var maskedSeed = xor(seed, mgf(maskedDb, hLen));
  43354. return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k));
  43355. }
  43356. function pkcs1(key, msg, reverse) {
  43357. var mLen = msg.length;
  43358. var k = key.modulus.byteLength();
  43359. if (mLen > k - 11) {
  43360. throw new Error('message too long');
  43361. }
  43362. var ps;
  43363. if (reverse) {
  43364. ps = Buffer.alloc(k - mLen - 3, 0xff);
  43365. } else {
  43366. ps = nonZero(k - mLen - 3);
  43367. }
  43368. return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k));
  43369. }
  43370. function nonZero(len) {
  43371. var out = Buffer.allocUnsafe(len);
  43372. var i = 0;
  43373. var cache = randomBytes(len * 2);
  43374. var cur = 0;
  43375. var num;
  43376. while (i < len) {
  43377. if (cur === cache.length) {
  43378. cache = randomBytes(len * 2);
  43379. cur = 0;
  43380. }
  43381. num = cache[cur++];
  43382. if (num) {
  43383. out[i++] = num;
  43384. }
  43385. }
  43386. return out;
  43387. }
  43388. },{"./mgf":308,"./withPublic":312,"./xor":313,"bn.js":309,"browserify-rsa":209,"create-hash":225,"parse-asn1":298,"randombytes":314,"safe-buffer":332}],312:[function(require,module,exports){
  43389. "use strict";
  43390. var BN = require('bn.js');
  43391. var Buffer = require('safe-buffer').Buffer;
  43392. function withPublic(paddedMsg, key) {
  43393. return Buffer.from(paddedMsg.toRed(BN.mont(key.modulus)).redPow(new BN(key.publicExponent)).fromRed().toArray());
  43394. }
  43395. module.exports = withPublic;
  43396. },{"bn.js":309,"safe-buffer":332}],313:[function(require,module,exports){
  43397. "use strict";
  43398. module.exports = function xor(a, b) {
  43399. var len = a.length;
  43400. var i = -1;
  43401. while (++i < len) {
  43402. a[i] ^= b[i];
  43403. }
  43404. return a;
  43405. };
  43406. },{}],314:[function(require,module,exports){
  43407. (function (process,global){(function (){
  43408. 'use strict';
  43409. // limit of Crypto.getRandomValues()
  43410. // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
  43411. var MAX_BYTES = 65536;
  43412. // Node supports requesting up to this number of bytes
  43413. // https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
  43414. var MAX_UINT32 = 4294967295;
  43415. function oldBrowser() {
  43416. throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11');
  43417. }
  43418. var Buffer = require('safe-buffer').Buffer;
  43419. var crypto = global.crypto || global.msCrypto;
  43420. if (crypto && crypto.getRandomValues) {
  43421. module.exports = randomBytes;
  43422. } else {
  43423. module.exports = oldBrowser;
  43424. }
  43425. function randomBytes(size, cb) {
  43426. // phantomjs needs to throw
  43427. if (size > MAX_UINT32) throw new RangeError('requested too many random bytes');
  43428. var bytes = Buffer.allocUnsafe(size);
  43429. if (size > 0) {
  43430. // getRandomValues fails on IE if size == 0
  43431. if (size > MAX_BYTES) {
  43432. // this is the max bytes crypto.getRandomValues
  43433. // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
  43434. for (var generated = 0; generated < size; generated += MAX_BYTES) {
  43435. // buffer.slice automatically checks if the end is past the end of
  43436. // the buffer so we don't have to here
  43437. crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES));
  43438. }
  43439. } else {
  43440. crypto.getRandomValues(bytes);
  43441. }
  43442. }
  43443. if (typeof cb === 'function') {
  43444. return process.nextTick(function () {
  43445. cb(null, bytes);
  43446. });
  43447. }
  43448. return bytes;
  43449. }
  43450. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  43451. },{"_process":306,"safe-buffer":332}],315:[function(require,module,exports){
  43452. (function (process,global){(function (){
  43453. 'use strict';
  43454. function oldBrowser() {
  43455. throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11');
  43456. }
  43457. var safeBuffer = require('safe-buffer');
  43458. var randombytes = require('randombytes');
  43459. var Buffer = safeBuffer.Buffer;
  43460. var kBufferMaxLength = safeBuffer.kMaxLength;
  43461. var crypto = global.crypto || global.msCrypto;
  43462. var kMaxUint32 = Math.pow(2, 32) - 1;
  43463. function assertOffset(offset, length) {
  43464. if (typeof offset !== 'number' || offset !== offset) {
  43465. // eslint-disable-line no-self-compare
  43466. throw new TypeError('offset must be a number');
  43467. }
  43468. if (offset > kMaxUint32 || offset < 0) {
  43469. throw new TypeError('offset must be a uint32');
  43470. }
  43471. if (offset > kBufferMaxLength || offset > length) {
  43472. throw new RangeError('offset out of range');
  43473. }
  43474. }
  43475. function assertSize(size, offset, length) {
  43476. if (typeof size !== 'number' || size !== size) {
  43477. // eslint-disable-line no-self-compare
  43478. throw new TypeError('size must be a number');
  43479. }
  43480. if (size > kMaxUint32 || size < 0) {
  43481. throw new TypeError('size must be a uint32');
  43482. }
  43483. if (size + offset > length || size > kBufferMaxLength) {
  43484. throw new RangeError('buffer too small');
  43485. }
  43486. }
  43487. if (crypto && crypto.getRandomValues || !process.browser) {
  43488. exports.randomFill = randomFill;
  43489. exports.randomFillSync = randomFillSync;
  43490. } else {
  43491. exports.randomFill = oldBrowser;
  43492. exports.randomFillSync = oldBrowser;
  43493. }
  43494. function randomFill(buf, offset, size, cb) {
  43495. if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
  43496. throw new TypeError('"buf" argument must be a Buffer or Uint8Array');
  43497. }
  43498. if (typeof offset === 'function') {
  43499. cb = offset;
  43500. offset = 0;
  43501. size = buf.length;
  43502. } else if (typeof size === 'function') {
  43503. cb = size;
  43504. size = buf.length - offset;
  43505. } else if (typeof cb !== 'function') {
  43506. throw new TypeError('"cb" argument must be a function');
  43507. }
  43508. assertOffset(offset, buf.length);
  43509. assertSize(size, offset, buf.length);
  43510. return actualFill(buf, offset, size, cb);
  43511. }
  43512. function actualFill(buf, offset, size, cb) {
  43513. if (process.browser) {
  43514. var ourBuf = buf.buffer;
  43515. var uint = new Uint8Array(ourBuf, offset, size);
  43516. crypto.getRandomValues(uint);
  43517. if (cb) {
  43518. process.nextTick(function () {
  43519. cb(null, buf);
  43520. });
  43521. return;
  43522. }
  43523. return buf;
  43524. }
  43525. if (cb) {
  43526. randombytes(size, function (err, bytes) {
  43527. if (err) {
  43528. return cb(err);
  43529. }
  43530. bytes.copy(buf, offset);
  43531. cb(null, buf);
  43532. });
  43533. return;
  43534. }
  43535. var bytes = randombytes(size);
  43536. bytes.copy(buf, offset);
  43537. return buf;
  43538. }
  43539. function randomFillSync(buf, offset, size) {
  43540. if (typeof offset === 'undefined') {
  43541. offset = 0;
  43542. }
  43543. if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
  43544. throw new TypeError('"buf" argument must be a Buffer or Uint8Array');
  43545. }
  43546. assertOffset(offset, buf.length);
  43547. if (size === undefined) size = buf.length - offset;
  43548. assertSize(size, offset, buf.length);
  43549. return actualFill(buf, offset, size);
  43550. }
  43551. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  43552. },{"_process":306,"randombytes":314,"safe-buffer":332}],316:[function(require,module,exports){
  43553. 'use strict';
  43554. function _inheritsLoose(subClass, superClass) {
  43555. subClass.prototype = Object.create(superClass.prototype);
  43556. subClass.prototype.constructor = subClass;
  43557. subClass.__proto__ = superClass;
  43558. }
  43559. var codes = {};
  43560. function createErrorType(code, message, Base) {
  43561. if (!Base) {
  43562. Base = Error;
  43563. }
  43564. function getMessage(arg1, arg2, arg3) {
  43565. if (typeof message === 'string') {
  43566. return message;
  43567. } else {
  43568. return message(arg1, arg2, arg3);
  43569. }
  43570. }
  43571. var NodeError = /*#__PURE__*/
  43572. function (_Base) {
  43573. _inheritsLoose(NodeError, _Base);
  43574. function NodeError(arg1, arg2, arg3) {
  43575. return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
  43576. }
  43577. return NodeError;
  43578. }(Base);
  43579. NodeError.prototype.name = Base.name;
  43580. NodeError.prototype.code = code;
  43581. codes[code] = NodeError;
  43582. } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
  43583. function oneOf(expected, thing) {
  43584. if (Array.isArray(expected)) {
  43585. var len = expected.length;
  43586. expected = expected.map(function (i) {
  43587. return String(i);
  43588. });
  43589. if (len > 2) {
  43590. return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
  43591. } else if (len === 2) {
  43592. return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
  43593. } else {
  43594. return "of ".concat(thing, " ").concat(expected[0]);
  43595. }
  43596. } else {
  43597. return "of ".concat(thing, " ").concat(String(expected));
  43598. }
  43599. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
  43600. function startsWith(str, search, pos) {
  43601. return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
  43602. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
  43603. function endsWith(str, search, this_len) {
  43604. if (this_len === undefined || this_len > str.length) {
  43605. this_len = str.length;
  43606. }
  43607. return str.substring(this_len - search.length, this_len) === search;
  43608. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
  43609. function includes(str, search, start) {
  43610. if (typeof start !== 'number') {
  43611. start = 0;
  43612. }
  43613. if (start + search.length > str.length) {
  43614. return false;
  43615. } else {
  43616. return str.indexOf(search, start) !== -1;
  43617. }
  43618. }
  43619. createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
  43620. return 'The value "' + value + '" is invalid for option "' + name + '"';
  43621. }, TypeError);
  43622. createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
  43623. // determiner: 'must be' or 'must not be'
  43624. var determiner;
  43625. if (typeof expected === 'string' && startsWith(expected, 'not ')) {
  43626. determiner = 'must not be';
  43627. expected = expected.replace(/^not /, '');
  43628. } else {
  43629. determiner = 'must be';
  43630. }
  43631. var msg;
  43632. if (endsWith(name, ' argument')) {
  43633. // For cases like 'first argument'
  43634. msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  43635. } else {
  43636. var type = includes(name, '.') ? 'property' : 'argument';
  43637. msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  43638. }
  43639. msg += ". Received type ".concat(typeof actual);
  43640. return msg;
  43641. }, TypeError);
  43642. createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
  43643. createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
  43644. return 'The ' + name + ' method is not implemented';
  43645. });
  43646. createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
  43647. createErrorType('ERR_STREAM_DESTROYED', function (name) {
  43648. return 'Cannot call ' + name + ' after a stream was destroyed';
  43649. });
  43650. createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
  43651. createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
  43652. createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
  43653. createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
  43654. createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
  43655. return 'Unknown encoding: ' + arg;
  43656. }, TypeError);
  43657. createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
  43658. module.exports.codes = codes;
  43659. },{}],317:[function(require,module,exports){
  43660. (function (process){(function (){
  43661. // Copyright Joyent, Inc. and other Node contributors.
  43662. //
  43663. // Permission is hereby granted, free of charge, to any person obtaining a
  43664. // copy of this software and associated documentation files (the
  43665. // "Software"), to deal in the Software without restriction, including
  43666. // without limitation the rights to use, copy, modify, merge, publish,
  43667. // distribute, sublicense, and/or sell copies of the Software, and to permit
  43668. // persons to whom the Software is furnished to do so, subject to the
  43669. // following conditions:
  43670. //
  43671. // The above copyright notice and this permission notice shall be included
  43672. // in all copies or substantial portions of the Software.
  43673. //
  43674. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  43675. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  43676. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  43677. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  43678. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  43679. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  43680. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  43681. // a duplex stream is just a stream that is both readable and writable.
  43682. // Since JS doesn't have multiple prototypal inheritance, this class
  43683. // prototypally inherits from Readable, and then parasitically from
  43684. // Writable.
  43685. 'use strict';
  43686. /*<replacement>*/
  43687. var objectKeys = Object.keys || function (obj) {
  43688. var keys = [];
  43689. for (var key in obj) keys.push(key);
  43690. return keys;
  43691. };
  43692. /*</replacement>*/
  43693. module.exports = Duplex;
  43694. var Readable = require('./_stream_readable');
  43695. var Writable = require('./_stream_writable');
  43696. require('inherits')(Duplex, Readable);
  43697. {
  43698. // Allow the keys array to be GC'ed.
  43699. var keys = objectKeys(Writable.prototype);
  43700. for (var v = 0; v < keys.length; v++) {
  43701. var method = keys[v];
  43702. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  43703. }
  43704. }
  43705. function Duplex(options) {
  43706. if (!(this instanceof Duplex)) return new Duplex(options);
  43707. Readable.call(this, options);
  43708. Writable.call(this, options);
  43709. this.allowHalfOpen = true;
  43710. if (options) {
  43711. if (options.readable === false) this.readable = false;
  43712. if (options.writable === false) this.writable = false;
  43713. if (options.allowHalfOpen === false) {
  43714. this.allowHalfOpen = false;
  43715. this.once('end', onend);
  43716. }
  43717. }
  43718. }
  43719. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  43720. // making it explicit this property is not enumerable
  43721. // because otherwise some prototype manipulation in
  43722. // userland will fail
  43723. enumerable: false,
  43724. get: function get() {
  43725. return this._writableState.highWaterMark;
  43726. }
  43727. });
  43728. Object.defineProperty(Duplex.prototype, 'writableBuffer', {
  43729. // making it explicit this property is not enumerable
  43730. // because otherwise some prototype manipulation in
  43731. // userland will fail
  43732. enumerable: false,
  43733. get: function get() {
  43734. return this._writableState && this._writableState.getBuffer();
  43735. }
  43736. });
  43737. Object.defineProperty(Duplex.prototype, 'writableLength', {
  43738. // making it explicit this property is not enumerable
  43739. // because otherwise some prototype manipulation in
  43740. // userland will fail
  43741. enumerable: false,
  43742. get: function get() {
  43743. return this._writableState.length;
  43744. }
  43745. });
  43746. // the no-half-open enforcer
  43747. function onend() {
  43748. // If the writable side ended, then we're ok.
  43749. if (this._writableState.ended) return;
  43750. // no more data can be written.
  43751. // But allow more writes to happen in this tick.
  43752. process.nextTick(onEndNT, this);
  43753. }
  43754. function onEndNT(self) {
  43755. self.end();
  43756. }
  43757. Object.defineProperty(Duplex.prototype, 'destroyed', {
  43758. // making it explicit this property is not enumerable
  43759. // because otherwise some prototype manipulation in
  43760. // userland will fail
  43761. enumerable: false,
  43762. get: function get() {
  43763. if (this._readableState === undefined || this._writableState === undefined) {
  43764. return false;
  43765. }
  43766. return this._readableState.destroyed && this._writableState.destroyed;
  43767. },
  43768. set: function set(value) {
  43769. // we ignore the value if the stream
  43770. // has not been initialized yet
  43771. if (this._readableState === undefined || this._writableState === undefined) {
  43772. return;
  43773. }
  43774. // backward compatibility, the user is explicitly
  43775. // managing destroyed
  43776. this._readableState.destroyed = value;
  43777. this._writableState.destroyed = value;
  43778. }
  43779. });
  43780. }).call(this)}).call(this,require('_process'))
  43781. },{"./_stream_readable":319,"./_stream_writable":321,"_process":306,"inherits":279}],318:[function(require,module,exports){
  43782. // Copyright Joyent, Inc. and other Node contributors.
  43783. //
  43784. // Permission is hereby granted, free of charge, to any person obtaining a
  43785. // copy of this software and associated documentation files (the
  43786. // "Software"), to deal in the Software without restriction, including
  43787. // without limitation the rights to use, copy, modify, merge, publish,
  43788. // distribute, sublicense, and/or sell copies of the Software, and to permit
  43789. // persons to whom the Software is furnished to do so, subject to the
  43790. // following conditions:
  43791. //
  43792. // The above copyright notice and this permission notice shall be included
  43793. // in all copies or substantial portions of the Software.
  43794. //
  43795. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  43796. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  43797. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  43798. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  43799. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  43800. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  43801. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  43802. // a passthrough stream.
  43803. // basically just the most minimal sort of Transform stream.
  43804. // Every written chunk gets output as-is.
  43805. 'use strict';
  43806. module.exports = PassThrough;
  43807. var Transform = require('./_stream_transform');
  43808. require('inherits')(PassThrough, Transform);
  43809. function PassThrough(options) {
  43810. if (!(this instanceof PassThrough)) return new PassThrough(options);
  43811. Transform.call(this, options);
  43812. }
  43813. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  43814. cb(null, chunk);
  43815. };
  43816. },{"./_stream_transform":320,"inherits":279}],319:[function(require,module,exports){
  43817. (function (process,global){(function (){
  43818. // Copyright Joyent, Inc. and other Node contributors.
  43819. //
  43820. // Permission is hereby granted, free of charge, to any person obtaining a
  43821. // copy of this software and associated documentation files (the
  43822. // "Software"), to deal in the Software without restriction, including
  43823. // without limitation the rights to use, copy, modify, merge, publish,
  43824. // distribute, sublicense, and/or sell copies of the Software, and to permit
  43825. // persons to whom the Software is furnished to do so, subject to the
  43826. // following conditions:
  43827. //
  43828. // The above copyright notice and this permission notice shall be included
  43829. // in all copies or substantial portions of the Software.
  43830. //
  43831. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  43832. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  43833. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  43834. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  43835. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  43836. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  43837. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  43838. 'use strict';
  43839. module.exports = Readable;
  43840. /*<replacement>*/
  43841. var Duplex;
  43842. /*</replacement>*/
  43843. Readable.ReadableState = ReadableState;
  43844. /*<replacement>*/
  43845. var EE = require('events').EventEmitter;
  43846. var EElistenerCount = function EElistenerCount(emitter, type) {
  43847. return emitter.listeners(type).length;
  43848. };
  43849. /*</replacement>*/
  43850. /*<replacement>*/
  43851. var Stream = require('./internal/streams/stream');
  43852. /*</replacement>*/
  43853. var Buffer = require('buffer').Buffer;
  43854. var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
  43855. function _uint8ArrayToBuffer(chunk) {
  43856. return Buffer.from(chunk);
  43857. }
  43858. function _isUint8Array(obj) {
  43859. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  43860. }
  43861. /*<replacement>*/
  43862. var debugUtil = require('util');
  43863. var debug;
  43864. if (debugUtil && debugUtil.debuglog) {
  43865. debug = debugUtil.debuglog('stream');
  43866. } else {
  43867. debug = function debug() {};
  43868. }
  43869. /*</replacement>*/
  43870. var BufferList = require('./internal/streams/buffer_list');
  43871. var destroyImpl = require('./internal/streams/destroy');
  43872. var _require = require('./internal/streams/state'),
  43873. getHighWaterMark = _require.getHighWaterMark;
  43874. var _require$codes = require('../errors').codes,
  43875. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  43876. ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
  43877. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  43878. ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
  43879. // Lazy loaded to improve the startup performance.
  43880. var StringDecoder;
  43881. var createReadableStreamAsyncIterator;
  43882. var from;
  43883. require('inherits')(Readable, Stream);
  43884. var errorOrDestroy = destroyImpl.errorOrDestroy;
  43885. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  43886. function prependListener(emitter, event, fn) {
  43887. // Sadly this is not cacheable as some libraries bundle their own
  43888. // event emitter implementation with them.
  43889. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  43890. // This is a hack to make sure that our error handler is attached before any
  43891. // userland ones. NEVER DO THIS. This is here only because this code needs
  43892. // to continue to work with older versions of Node.js that do not include
  43893. // the prependListener() method. The goal is to eventually remove this hack.
  43894. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  43895. }
  43896. function ReadableState(options, stream, isDuplex) {
  43897. Duplex = Duplex || require('./_stream_duplex');
  43898. options = options || {};
  43899. // Duplex streams are both readable and writable, but share
  43900. // the same options object.
  43901. // However, some cases require setting options to different
  43902. // values for the readable and the writable sides of the duplex stream.
  43903. // These options can be provided separately as readableXXX and writableXXX.
  43904. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
  43905. // object stream flag. Used to make read(n) ignore n and to
  43906. // make all the buffer merging and length checks go away
  43907. this.objectMode = !!options.objectMode;
  43908. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  43909. // the point at which it stops calling _read() to fill the buffer
  43910. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  43911. this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);
  43912. // A linked list is used to store data chunks instead of an array because the
  43913. // linked list can remove elements from the beginning faster than
  43914. // array.shift()
  43915. this.buffer = new BufferList();
  43916. this.length = 0;
  43917. this.pipes = null;
  43918. this.pipesCount = 0;
  43919. this.flowing = null;
  43920. this.ended = false;
  43921. this.endEmitted = false;
  43922. this.reading = false;
  43923. // a flag to be able to tell if the event 'readable'/'data' is emitted
  43924. // immediately, or on a later tick. We set this to true at first, because
  43925. // any actions that shouldn't happen until "later" should generally also
  43926. // not happen before the first read call.
  43927. this.sync = true;
  43928. // whenever we return null, then we set a flag to say
  43929. // that we're awaiting a 'readable' event emission.
  43930. this.needReadable = false;
  43931. this.emittedReadable = false;
  43932. this.readableListening = false;
  43933. this.resumeScheduled = false;
  43934. this.paused = true;
  43935. // Should close be emitted on destroy. Defaults to true.
  43936. this.emitClose = options.emitClose !== false;
  43937. // Should .destroy() be called after 'end' (and potentially 'finish')
  43938. this.autoDestroy = !!options.autoDestroy;
  43939. // has it been destroyed
  43940. this.destroyed = false;
  43941. // Crypto is kind of old and crusty. Historically, its default string
  43942. // encoding is 'binary' so we have to make this configurable.
  43943. // Everything else in the universe uses 'utf8', though.
  43944. this.defaultEncoding = options.defaultEncoding || 'utf8';
  43945. // the number of writers that are awaiting a drain event in .pipe()s
  43946. this.awaitDrain = 0;
  43947. // if true, a maybeReadMore has been scheduled
  43948. this.readingMore = false;
  43949. this.decoder = null;
  43950. this.encoding = null;
  43951. if (options.encoding) {
  43952. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  43953. this.decoder = new StringDecoder(options.encoding);
  43954. this.encoding = options.encoding;
  43955. }
  43956. }
  43957. function Readable(options) {
  43958. Duplex = Duplex || require('./_stream_duplex');
  43959. if (!(this instanceof Readable)) return new Readable(options);
  43960. // Checking for a Stream.Duplex instance is faster here instead of inside
  43961. // the ReadableState constructor, at least with V8 6.5
  43962. var isDuplex = this instanceof Duplex;
  43963. this._readableState = new ReadableState(options, this, isDuplex);
  43964. // legacy
  43965. this.readable = true;
  43966. if (options) {
  43967. if (typeof options.read === 'function') this._read = options.read;
  43968. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  43969. }
  43970. Stream.call(this);
  43971. }
  43972. Object.defineProperty(Readable.prototype, 'destroyed', {
  43973. // making it explicit this property is not enumerable
  43974. // because otherwise some prototype manipulation in
  43975. // userland will fail
  43976. enumerable: false,
  43977. get: function get() {
  43978. if (this._readableState === undefined) {
  43979. return false;
  43980. }
  43981. return this._readableState.destroyed;
  43982. },
  43983. set: function set(value) {
  43984. // we ignore the value if the stream
  43985. // has not been initialized yet
  43986. if (!this._readableState) {
  43987. return;
  43988. }
  43989. // backward compatibility, the user is explicitly
  43990. // managing destroyed
  43991. this._readableState.destroyed = value;
  43992. }
  43993. });
  43994. Readable.prototype.destroy = destroyImpl.destroy;
  43995. Readable.prototype._undestroy = destroyImpl.undestroy;
  43996. Readable.prototype._destroy = function (err, cb) {
  43997. cb(err);
  43998. };
  43999. // Manually shove something into the read() buffer.
  44000. // This returns true if the highWaterMark has not been hit yet,
  44001. // similar to how Writable.write() returns true if you should
  44002. // write() some more.
  44003. Readable.prototype.push = function (chunk, encoding) {
  44004. var state = this._readableState;
  44005. var skipChunkCheck;
  44006. if (!state.objectMode) {
  44007. if (typeof chunk === 'string') {
  44008. encoding = encoding || state.defaultEncoding;
  44009. if (encoding !== state.encoding) {
  44010. chunk = Buffer.from(chunk, encoding);
  44011. encoding = '';
  44012. }
  44013. skipChunkCheck = true;
  44014. }
  44015. } else {
  44016. skipChunkCheck = true;
  44017. }
  44018. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  44019. };
  44020. // Unshift should *always* be something directly out of read()
  44021. Readable.prototype.unshift = function (chunk) {
  44022. return readableAddChunk(this, chunk, null, true, false);
  44023. };
  44024. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  44025. debug('readableAddChunk', chunk);
  44026. var state = stream._readableState;
  44027. if (chunk === null) {
  44028. state.reading = false;
  44029. onEofChunk(stream, state);
  44030. } else {
  44031. var er;
  44032. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  44033. if (er) {
  44034. errorOrDestroy(stream, er);
  44035. } else if (state.objectMode || chunk && chunk.length > 0) {
  44036. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  44037. chunk = _uint8ArrayToBuffer(chunk);
  44038. }
  44039. if (addToFront) {
  44040. if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
  44041. } else if (state.ended) {
  44042. errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
  44043. } else if (state.destroyed) {
  44044. return false;
  44045. } else {
  44046. state.reading = false;
  44047. if (state.decoder && !encoding) {
  44048. chunk = state.decoder.write(chunk);
  44049. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  44050. } else {
  44051. addChunk(stream, state, chunk, false);
  44052. }
  44053. }
  44054. } else if (!addToFront) {
  44055. state.reading = false;
  44056. maybeReadMore(stream, state);
  44057. }
  44058. }
  44059. // We can push more data if we are below the highWaterMark.
  44060. // Also, if we have no data yet, we can stand some more bytes.
  44061. // This is to work around cases where hwm=0, such as the repl.
  44062. return !state.ended && (state.length < state.highWaterMark || state.length === 0);
  44063. }
  44064. function addChunk(stream, state, chunk, addToFront) {
  44065. if (state.flowing && state.length === 0 && !state.sync) {
  44066. state.awaitDrain = 0;
  44067. stream.emit('data', chunk);
  44068. } else {
  44069. // update the buffer info.
  44070. state.length += state.objectMode ? 1 : chunk.length;
  44071. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  44072. if (state.needReadable) emitReadable(stream);
  44073. }
  44074. maybeReadMore(stream, state);
  44075. }
  44076. function chunkInvalid(state, chunk) {
  44077. var er;
  44078. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  44079. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
  44080. }
  44081. return er;
  44082. }
  44083. Readable.prototype.isPaused = function () {
  44084. return this._readableState.flowing === false;
  44085. };
  44086. // backwards compatibility.
  44087. Readable.prototype.setEncoding = function (enc) {
  44088. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  44089. var decoder = new StringDecoder(enc);
  44090. this._readableState.decoder = decoder;
  44091. // If setEncoding(null), decoder.encoding equals utf8
  44092. this._readableState.encoding = this._readableState.decoder.encoding;
  44093. // Iterate over current buffer to convert already stored Buffers:
  44094. var p = this._readableState.buffer.head;
  44095. var content = '';
  44096. while (p !== null) {
  44097. content += decoder.write(p.data);
  44098. p = p.next;
  44099. }
  44100. this._readableState.buffer.clear();
  44101. if (content !== '') this._readableState.buffer.push(content);
  44102. this._readableState.length = content.length;
  44103. return this;
  44104. };
  44105. // Don't raise the hwm > 1GB
  44106. var MAX_HWM = 0x40000000;
  44107. function computeNewHighWaterMark(n) {
  44108. if (n >= MAX_HWM) {
  44109. // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
  44110. n = MAX_HWM;
  44111. } else {
  44112. // Get the next highest power of 2 to prevent increasing hwm excessively in
  44113. // tiny amounts
  44114. n--;
  44115. n |= n >>> 1;
  44116. n |= n >>> 2;
  44117. n |= n >>> 4;
  44118. n |= n >>> 8;
  44119. n |= n >>> 16;
  44120. n++;
  44121. }
  44122. return n;
  44123. }
  44124. // This function is designed to be inlinable, so please take care when making
  44125. // changes to the function body.
  44126. function howMuchToRead(n, state) {
  44127. if (n <= 0 || state.length === 0 && state.ended) return 0;
  44128. if (state.objectMode) return 1;
  44129. if (n !== n) {
  44130. // Only flow one buffer at a time
  44131. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  44132. }
  44133. // If we're asking for more than the current hwm, then raise the hwm.
  44134. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  44135. if (n <= state.length) return n;
  44136. // Don't have enough
  44137. if (!state.ended) {
  44138. state.needReadable = true;
  44139. return 0;
  44140. }
  44141. return state.length;
  44142. }
  44143. // you can override either this method, or the async _read(n) below.
  44144. Readable.prototype.read = function (n) {
  44145. debug('read', n);
  44146. n = parseInt(n, 10);
  44147. var state = this._readableState;
  44148. var nOrig = n;
  44149. if (n !== 0) state.emittedReadable = false;
  44150. // if we're doing read(0) to trigger a readable event, but we
  44151. // already have a bunch of data in the buffer, then just trigger
  44152. // the 'readable' event and move on.
  44153. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
  44154. debug('read: emitReadable', state.length, state.ended);
  44155. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  44156. return null;
  44157. }
  44158. n = howMuchToRead(n, state);
  44159. // if we've ended, and we're now clear, then finish it up.
  44160. if (n === 0 && state.ended) {
  44161. if (state.length === 0) endReadable(this);
  44162. return null;
  44163. }
  44164. // All the actual chunk generation logic needs to be
  44165. // *below* the call to _read. The reason is that in certain
  44166. // synthetic stream cases, such as passthrough streams, _read
  44167. // may be a completely synchronous operation which may change
  44168. // the state of the read buffer, providing enough data when
  44169. // before there was *not* enough.
  44170. //
  44171. // So, the steps are:
  44172. // 1. Figure out what the state of things will be after we do
  44173. // a read from the buffer.
  44174. //
  44175. // 2. If that resulting state will trigger a _read, then call _read.
  44176. // Note that this may be asynchronous, or synchronous. Yes, it is
  44177. // deeply ugly to write APIs this way, but that still doesn't mean
  44178. // that the Readable class should behave improperly, as streams are
  44179. // designed to be sync/async agnostic.
  44180. // Take note if the _read call is sync or async (ie, if the read call
  44181. // has returned yet), so that we know whether or not it's safe to emit
  44182. // 'readable' etc.
  44183. //
  44184. // 3. Actually pull the requested chunks out of the buffer and return.
  44185. // if we need a readable event, then we need to do some reading.
  44186. var doRead = state.needReadable;
  44187. debug('need readable', doRead);
  44188. // if we currently have less than the highWaterMark, then also read some
  44189. if (state.length === 0 || state.length - n < state.highWaterMark) {
  44190. doRead = true;
  44191. debug('length less than watermark', doRead);
  44192. }
  44193. // however, if we've ended, then there's no point, and if we're already
  44194. // reading, then it's unnecessary.
  44195. if (state.ended || state.reading) {
  44196. doRead = false;
  44197. debug('reading or ended', doRead);
  44198. } else if (doRead) {
  44199. debug('do read');
  44200. state.reading = true;
  44201. state.sync = true;
  44202. // if the length is currently zero, then we *need* a readable event.
  44203. if (state.length === 0) state.needReadable = true;
  44204. // call internal read method
  44205. this._read(state.highWaterMark);
  44206. state.sync = false;
  44207. // If _read pushed data synchronously, then `reading` will be false,
  44208. // and we need to re-evaluate how much data we can return to the user.
  44209. if (!state.reading) n = howMuchToRead(nOrig, state);
  44210. }
  44211. var ret;
  44212. if (n > 0) ret = fromList(n, state);else ret = null;
  44213. if (ret === null) {
  44214. state.needReadable = state.length <= state.highWaterMark;
  44215. n = 0;
  44216. } else {
  44217. state.length -= n;
  44218. state.awaitDrain = 0;
  44219. }
  44220. if (state.length === 0) {
  44221. // If we have nothing in the buffer, then we want to know
  44222. // as soon as we *do* get something into the buffer.
  44223. if (!state.ended) state.needReadable = true;
  44224. // If we tried to read() past the EOF, then emit end on the next tick.
  44225. if (nOrig !== n && state.ended) endReadable(this);
  44226. }
  44227. if (ret !== null) this.emit('data', ret);
  44228. return ret;
  44229. };
  44230. function onEofChunk(stream, state) {
  44231. debug('onEofChunk');
  44232. if (state.ended) return;
  44233. if (state.decoder) {
  44234. var chunk = state.decoder.end();
  44235. if (chunk && chunk.length) {
  44236. state.buffer.push(chunk);
  44237. state.length += state.objectMode ? 1 : chunk.length;
  44238. }
  44239. }
  44240. state.ended = true;
  44241. if (state.sync) {
  44242. // if we are sync, wait until next tick to emit the data.
  44243. // Otherwise we risk emitting data in the flow()
  44244. // the readable code triggers during a read() call
  44245. emitReadable(stream);
  44246. } else {
  44247. // emit 'readable' now to make sure it gets picked up.
  44248. state.needReadable = false;
  44249. if (!state.emittedReadable) {
  44250. state.emittedReadable = true;
  44251. emitReadable_(stream);
  44252. }
  44253. }
  44254. }
  44255. // Don't emit readable right away in sync mode, because this can trigger
  44256. // another read() call => stack overflow. This way, it might trigger
  44257. // a nextTick recursion warning, but that's not so bad.
  44258. function emitReadable(stream) {
  44259. var state = stream._readableState;
  44260. debug('emitReadable', state.needReadable, state.emittedReadable);
  44261. state.needReadable = false;
  44262. if (!state.emittedReadable) {
  44263. debug('emitReadable', state.flowing);
  44264. state.emittedReadable = true;
  44265. process.nextTick(emitReadable_, stream);
  44266. }
  44267. }
  44268. function emitReadable_(stream) {
  44269. var state = stream._readableState;
  44270. debug('emitReadable_', state.destroyed, state.length, state.ended);
  44271. if (!state.destroyed && (state.length || state.ended)) {
  44272. stream.emit('readable');
  44273. state.emittedReadable = false;
  44274. }
  44275. // The stream needs another readable event if
  44276. // 1. It is not flowing, as the flow mechanism will take
  44277. // care of it.
  44278. // 2. It is not ended.
  44279. // 3. It is below the highWaterMark, so we can schedule
  44280. // another readable later.
  44281. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  44282. flow(stream);
  44283. }
  44284. // at this point, the user has presumably seen the 'readable' event,
  44285. // and called read() to consume some data. that may have triggered
  44286. // in turn another _read(n) call, in which case reading = true if
  44287. // it's in progress.
  44288. // However, if we're not ended, or reading, and the length < hwm,
  44289. // then go ahead and try to read some more preemptively.
  44290. function maybeReadMore(stream, state) {
  44291. if (!state.readingMore) {
  44292. state.readingMore = true;
  44293. process.nextTick(maybeReadMore_, stream, state);
  44294. }
  44295. }
  44296. function maybeReadMore_(stream, state) {
  44297. // Attempt to read more data if we should.
  44298. //
  44299. // The conditions for reading more data are (one of):
  44300. // - Not enough data buffered (state.length < state.highWaterMark). The loop
  44301. // is responsible for filling the buffer with enough data if such data
  44302. // is available. If highWaterMark is 0 and we are not in the flowing mode
  44303. // we should _not_ attempt to buffer any extra data. We'll get more data
  44304. // when the stream consumer calls read() instead.
  44305. // - No data in the buffer, and the stream is in flowing mode. In this mode
  44306. // the loop below is responsible for ensuring read() is called. Failing to
  44307. // call read here would abort the flow and there's no other mechanism for
  44308. // continuing the flow if the stream consumer has just subscribed to the
  44309. // 'data' event.
  44310. //
  44311. // In addition to the above conditions to keep reading data, the following
  44312. // conditions prevent the data from being read:
  44313. // - The stream has ended (state.ended).
  44314. // - There is already a pending 'read' operation (state.reading). This is a
  44315. // case where the the stream has called the implementation defined _read()
  44316. // method, but they are processing the call asynchronously and have _not_
  44317. // called push() with new data. In this case we skip performing more
  44318. // read()s. The execution ends in this method again after the _read() ends
  44319. // up calling push() with more data.
  44320. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
  44321. var len = state.length;
  44322. debug('maybeReadMore read 0');
  44323. stream.read(0);
  44324. if (len === state.length)
  44325. // didn't get any data, stop spinning.
  44326. break;
  44327. }
  44328. state.readingMore = false;
  44329. }
  44330. // abstract method. to be overridden in specific implementation classes.
  44331. // call cb(er, data) where data is <= n in length.
  44332. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  44333. // arbitrary, and perhaps not very meaningful.
  44334. Readable.prototype._read = function (n) {
  44335. errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
  44336. };
  44337. Readable.prototype.pipe = function (dest, pipeOpts) {
  44338. var src = this;
  44339. var state = this._readableState;
  44340. switch (state.pipesCount) {
  44341. case 0:
  44342. state.pipes = dest;
  44343. break;
  44344. case 1:
  44345. state.pipes = [state.pipes, dest];
  44346. break;
  44347. default:
  44348. state.pipes.push(dest);
  44349. break;
  44350. }
  44351. state.pipesCount += 1;
  44352. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  44353. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  44354. var endFn = doEnd ? onend : unpipe;
  44355. if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
  44356. dest.on('unpipe', onunpipe);
  44357. function onunpipe(readable, unpipeInfo) {
  44358. debug('onunpipe');
  44359. if (readable === src) {
  44360. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  44361. unpipeInfo.hasUnpiped = true;
  44362. cleanup();
  44363. }
  44364. }
  44365. }
  44366. function onend() {
  44367. debug('onend');
  44368. dest.end();
  44369. }
  44370. // when the dest drains, it reduces the awaitDrain counter
  44371. // on the source. This would be more elegant with a .once()
  44372. // handler in flow(), but adding and removing repeatedly is
  44373. // too slow.
  44374. var ondrain = pipeOnDrain(src);
  44375. dest.on('drain', ondrain);
  44376. var cleanedUp = false;
  44377. function cleanup() {
  44378. debug('cleanup');
  44379. // cleanup event handlers once the pipe is broken
  44380. dest.removeListener('close', onclose);
  44381. dest.removeListener('finish', onfinish);
  44382. dest.removeListener('drain', ondrain);
  44383. dest.removeListener('error', onerror);
  44384. dest.removeListener('unpipe', onunpipe);
  44385. src.removeListener('end', onend);
  44386. src.removeListener('end', unpipe);
  44387. src.removeListener('data', ondata);
  44388. cleanedUp = true;
  44389. // if the reader is waiting for a drain event from this
  44390. // specific writer, then it would cause it to never start
  44391. // flowing again.
  44392. // So, if this is awaiting a drain, then we just call it now.
  44393. // If we don't know, then assume that we are waiting for one.
  44394. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  44395. }
  44396. src.on('data', ondata);
  44397. function ondata(chunk) {
  44398. debug('ondata');
  44399. var ret = dest.write(chunk);
  44400. debug('dest.write', ret);
  44401. if (ret === false) {
  44402. // If the user unpiped during `dest.write()`, it is possible
  44403. // to get stuck in a permanently paused state if that write
  44404. // also returned false.
  44405. // => Check whether `dest` is still a piping destination.
  44406. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  44407. debug('false write response, pause', state.awaitDrain);
  44408. state.awaitDrain++;
  44409. }
  44410. src.pause();
  44411. }
  44412. }
  44413. // if the dest has an error, then stop piping into it.
  44414. // however, don't suppress the throwing behavior for this.
  44415. function onerror(er) {
  44416. debug('onerror', er);
  44417. unpipe();
  44418. dest.removeListener('error', onerror);
  44419. if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
  44420. }
  44421. // Make sure our error handler is attached before userland ones.
  44422. prependListener(dest, 'error', onerror);
  44423. // Both close and finish should trigger unpipe, but only once.
  44424. function onclose() {
  44425. dest.removeListener('finish', onfinish);
  44426. unpipe();
  44427. }
  44428. dest.once('close', onclose);
  44429. function onfinish() {
  44430. debug('onfinish');
  44431. dest.removeListener('close', onclose);
  44432. unpipe();
  44433. }
  44434. dest.once('finish', onfinish);
  44435. function unpipe() {
  44436. debug('unpipe');
  44437. src.unpipe(dest);
  44438. }
  44439. // tell the dest that it's being piped to
  44440. dest.emit('pipe', src);
  44441. // start the flow if it hasn't been started already.
  44442. if (!state.flowing) {
  44443. debug('pipe resume');
  44444. src.resume();
  44445. }
  44446. return dest;
  44447. };
  44448. function pipeOnDrain(src) {
  44449. return function pipeOnDrainFunctionResult() {
  44450. var state = src._readableState;
  44451. debug('pipeOnDrain', state.awaitDrain);
  44452. if (state.awaitDrain) state.awaitDrain--;
  44453. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  44454. state.flowing = true;
  44455. flow(src);
  44456. }
  44457. };
  44458. }
  44459. Readable.prototype.unpipe = function (dest) {
  44460. var state = this._readableState;
  44461. var unpipeInfo = {
  44462. hasUnpiped: false
  44463. };
  44464. // if we're not piping anywhere, then do nothing.
  44465. if (state.pipesCount === 0) return this;
  44466. // just one destination. most common case.
  44467. if (state.pipesCount === 1) {
  44468. // passed in one, but it's not the right one.
  44469. if (dest && dest !== state.pipes) return this;
  44470. if (!dest) dest = state.pipes;
  44471. // got a match.
  44472. state.pipes = null;
  44473. state.pipesCount = 0;
  44474. state.flowing = false;
  44475. if (dest) dest.emit('unpipe', this, unpipeInfo);
  44476. return this;
  44477. }
  44478. // slow case. multiple pipe destinations.
  44479. if (!dest) {
  44480. // remove all.
  44481. var dests = state.pipes;
  44482. var len = state.pipesCount;
  44483. state.pipes = null;
  44484. state.pipesCount = 0;
  44485. state.flowing = false;
  44486. for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {
  44487. hasUnpiped: false
  44488. });
  44489. return this;
  44490. }
  44491. // try to find the right one.
  44492. var index = indexOf(state.pipes, dest);
  44493. if (index === -1) return this;
  44494. state.pipes.splice(index, 1);
  44495. state.pipesCount -= 1;
  44496. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  44497. dest.emit('unpipe', this, unpipeInfo);
  44498. return this;
  44499. };
  44500. // set up data events if they are asked for
  44501. // Ensure readable listeners eventually get something
  44502. Readable.prototype.on = function (ev, fn) {
  44503. var res = Stream.prototype.on.call(this, ev, fn);
  44504. var state = this._readableState;
  44505. if (ev === 'data') {
  44506. // update readableListening so that resume() may be a no-op
  44507. // a few lines down. This is needed to support once('readable').
  44508. state.readableListening = this.listenerCount('readable') > 0;
  44509. // Try start flowing on next tick if stream isn't explicitly paused
  44510. if (state.flowing !== false) this.resume();
  44511. } else if (ev === 'readable') {
  44512. if (!state.endEmitted && !state.readableListening) {
  44513. state.readableListening = state.needReadable = true;
  44514. state.flowing = false;
  44515. state.emittedReadable = false;
  44516. debug('on readable', state.length, state.reading);
  44517. if (state.length) {
  44518. emitReadable(this);
  44519. } else if (!state.reading) {
  44520. process.nextTick(nReadingNextTick, this);
  44521. }
  44522. }
  44523. }
  44524. return res;
  44525. };
  44526. Readable.prototype.addListener = Readable.prototype.on;
  44527. Readable.prototype.removeListener = function (ev, fn) {
  44528. var res = Stream.prototype.removeListener.call(this, ev, fn);
  44529. if (ev === 'readable') {
  44530. // We need to check if there is someone still listening to
  44531. // readable and reset the state. However this needs to happen
  44532. // after readable has been emitted but before I/O (nextTick) to
  44533. // support once('readable', fn) cycles. This means that calling
  44534. // resume within the same tick will have no
  44535. // effect.
  44536. process.nextTick(updateReadableListening, this);
  44537. }
  44538. return res;
  44539. };
  44540. Readable.prototype.removeAllListeners = function (ev) {
  44541. var res = Stream.prototype.removeAllListeners.apply(this, arguments);
  44542. if (ev === 'readable' || ev === undefined) {
  44543. // We need to check if there is someone still listening to
  44544. // readable and reset the state. However this needs to happen
  44545. // after readable has been emitted but before I/O (nextTick) to
  44546. // support once('readable', fn) cycles. This means that calling
  44547. // resume within the same tick will have no
  44548. // effect.
  44549. process.nextTick(updateReadableListening, this);
  44550. }
  44551. return res;
  44552. };
  44553. function updateReadableListening(self) {
  44554. var state = self._readableState;
  44555. state.readableListening = self.listenerCount('readable') > 0;
  44556. if (state.resumeScheduled && !state.paused) {
  44557. // flowing needs to be set to true now, otherwise
  44558. // the upcoming resume will not flow.
  44559. state.flowing = true;
  44560. // crude way to check if we should resume
  44561. } else if (self.listenerCount('data') > 0) {
  44562. self.resume();
  44563. }
  44564. }
  44565. function nReadingNextTick(self) {
  44566. debug('readable nexttick read 0');
  44567. self.read(0);
  44568. }
  44569. // pause() and resume() are remnants of the legacy readable stream API
  44570. // If the user uses them, then switch into old mode.
  44571. Readable.prototype.resume = function () {
  44572. var state = this._readableState;
  44573. if (!state.flowing) {
  44574. debug('resume');
  44575. // we flow only if there is no one listening
  44576. // for readable, but we still have to call
  44577. // resume()
  44578. state.flowing = !state.readableListening;
  44579. resume(this, state);
  44580. }
  44581. state.paused = false;
  44582. return this;
  44583. };
  44584. function resume(stream, state) {
  44585. if (!state.resumeScheduled) {
  44586. state.resumeScheduled = true;
  44587. process.nextTick(resume_, stream, state);
  44588. }
  44589. }
  44590. function resume_(stream, state) {
  44591. debug('resume', state.reading);
  44592. if (!state.reading) {
  44593. stream.read(0);
  44594. }
  44595. state.resumeScheduled = false;
  44596. stream.emit('resume');
  44597. flow(stream);
  44598. if (state.flowing && !state.reading) stream.read(0);
  44599. }
  44600. Readable.prototype.pause = function () {
  44601. debug('call pause flowing=%j', this._readableState.flowing);
  44602. if (this._readableState.flowing !== false) {
  44603. debug('pause');
  44604. this._readableState.flowing = false;
  44605. this.emit('pause');
  44606. }
  44607. this._readableState.paused = true;
  44608. return this;
  44609. };
  44610. function flow(stream) {
  44611. var state = stream._readableState;
  44612. debug('flow', state.flowing);
  44613. while (state.flowing && stream.read() !== null);
  44614. }
  44615. // wrap an old-style stream as the async data source.
  44616. // This is *not* part of the readable stream interface.
  44617. // It is an ugly unfortunate mess of history.
  44618. Readable.prototype.wrap = function (stream) {
  44619. var _this = this;
  44620. var state = this._readableState;
  44621. var paused = false;
  44622. stream.on('end', function () {
  44623. debug('wrapped end');
  44624. if (state.decoder && !state.ended) {
  44625. var chunk = state.decoder.end();
  44626. if (chunk && chunk.length) _this.push(chunk);
  44627. }
  44628. _this.push(null);
  44629. });
  44630. stream.on('data', function (chunk) {
  44631. debug('wrapped data');
  44632. if (state.decoder) chunk = state.decoder.write(chunk);
  44633. // don't skip over falsy values in objectMode
  44634. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  44635. var ret = _this.push(chunk);
  44636. if (!ret) {
  44637. paused = true;
  44638. stream.pause();
  44639. }
  44640. });
  44641. // proxy all the other methods.
  44642. // important when wrapping filters and duplexes.
  44643. for (var i in stream) {
  44644. if (this[i] === undefined && typeof stream[i] === 'function') {
  44645. this[i] = function methodWrap(method) {
  44646. return function methodWrapReturnFunction() {
  44647. return stream[method].apply(stream, arguments);
  44648. };
  44649. }(i);
  44650. }
  44651. }
  44652. // proxy certain important events.
  44653. for (var n = 0; n < kProxyEvents.length; n++) {
  44654. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  44655. }
  44656. // when we try to consume some more bytes, simply unpause the
  44657. // underlying stream.
  44658. this._read = function (n) {
  44659. debug('wrapped _read', n);
  44660. if (paused) {
  44661. paused = false;
  44662. stream.resume();
  44663. }
  44664. };
  44665. return this;
  44666. };
  44667. if (typeof Symbol === 'function') {
  44668. Readable.prototype[Symbol.asyncIterator] = function () {
  44669. if (createReadableStreamAsyncIterator === undefined) {
  44670. createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
  44671. }
  44672. return createReadableStreamAsyncIterator(this);
  44673. };
  44674. }
  44675. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  44676. // making it explicit this property is not enumerable
  44677. // because otherwise some prototype manipulation in
  44678. // userland will fail
  44679. enumerable: false,
  44680. get: function get() {
  44681. return this._readableState.highWaterMark;
  44682. }
  44683. });
  44684. Object.defineProperty(Readable.prototype, 'readableBuffer', {
  44685. // making it explicit this property is not enumerable
  44686. // because otherwise some prototype manipulation in
  44687. // userland will fail
  44688. enumerable: false,
  44689. get: function get() {
  44690. return this._readableState && this._readableState.buffer;
  44691. }
  44692. });
  44693. Object.defineProperty(Readable.prototype, 'readableFlowing', {
  44694. // making it explicit this property is not enumerable
  44695. // because otherwise some prototype manipulation in
  44696. // userland will fail
  44697. enumerable: false,
  44698. get: function get() {
  44699. return this._readableState.flowing;
  44700. },
  44701. set: function set(state) {
  44702. if (this._readableState) {
  44703. this._readableState.flowing = state;
  44704. }
  44705. }
  44706. });
  44707. // exposed for testing purposes only.
  44708. Readable._fromList = fromList;
  44709. Object.defineProperty(Readable.prototype, 'readableLength', {
  44710. // making it explicit this property is not enumerable
  44711. // because otherwise some prototype manipulation in
  44712. // userland will fail
  44713. enumerable: false,
  44714. get: function get() {
  44715. return this._readableState.length;
  44716. }
  44717. });
  44718. // Pluck off n bytes from an array of buffers.
  44719. // Length is the combined lengths of all the buffers in the list.
  44720. // This function is designed to be inlinable, so please take care when making
  44721. // changes to the function body.
  44722. function fromList(n, state) {
  44723. // nothing buffered
  44724. if (state.length === 0) return null;
  44725. var ret;
  44726. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  44727. // read it all, truncate the list
  44728. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
  44729. state.buffer.clear();
  44730. } else {
  44731. // read part of list
  44732. ret = state.buffer.consume(n, state.decoder);
  44733. }
  44734. return ret;
  44735. }
  44736. function endReadable(stream) {
  44737. var state = stream._readableState;
  44738. debug('endReadable', state.endEmitted);
  44739. if (!state.endEmitted) {
  44740. state.ended = true;
  44741. process.nextTick(endReadableNT, state, stream);
  44742. }
  44743. }
  44744. function endReadableNT(state, stream) {
  44745. debug('endReadableNT', state.endEmitted, state.length);
  44746. // Check that we didn't get one last unshift.
  44747. if (!state.endEmitted && state.length === 0) {
  44748. state.endEmitted = true;
  44749. stream.readable = false;
  44750. stream.emit('end');
  44751. if (state.autoDestroy) {
  44752. // In case of duplex streams we need a way to detect
  44753. // if the writable side is ready for autoDestroy as well
  44754. var wState = stream._writableState;
  44755. if (!wState || wState.autoDestroy && wState.finished) {
  44756. stream.destroy();
  44757. }
  44758. }
  44759. }
  44760. }
  44761. if (typeof Symbol === 'function') {
  44762. Readable.from = function (iterable, opts) {
  44763. if (from === undefined) {
  44764. from = require('./internal/streams/from');
  44765. }
  44766. return from(Readable, iterable, opts);
  44767. };
  44768. }
  44769. function indexOf(xs, x) {
  44770. for (var i = 0, l = xs.length; i < l; i++) {
  44771. if (xs[i] === x) return i;
  44772. }
  44773. return -1;
  44774. }
  44775. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  44776. },{"../errors":316,"./_stream_duplex":317,"./internal/streams/async_iterator":322,"./internal/streams/buffer_list":323,"./internal/streams/destroy":324,"./internal/streams/from":326,"./internal/streams/state":328,"./internal/streams/stream":329,"_process":306,"buffer":220,"events":261,"inherits":279,"string_decoder/":360,"util":188}],320:[function(require,module,exports){
  44777. // Copyright Joyent, Inc. and other Node contributors.
  44778. //
  44779. // Permission is hereby granted, free of charge, to any person obtaining a
  44780. // copy of this software and associated documentation files (the
  44781. // "Software"), to deal in the Software without restriction, including
  44782. // without limitation the rights to use, copy, modify, merge, publish,
  44783. // distribute, sublicense, and/or sell copies of the Software, and to permit
  44784. // persons to whom the Software is furnished to do so, subject to the
  44785. // following conditions:
  44786. //
  44787. // The above copyright notice and this permission notice shall be included
  44788. // in all copies or substantial portions of the Software.
  44789. //
  44790. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  44791. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  44792. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  44793. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  44794. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  44795. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  44796. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  44797. // a transform stream is a readable/writable stream where you do
  44798. // something with the data. Sometimes it's called a "filter",
  44799. // but that's not a great name for it, since that implies a thing where
  44800. // some bits pass through, and others are simply ignored. (That would
  44801. // be a valid example of a transform, of course.)
  44802. //
  44803. // While the output is causally related to the input, it's not a
  44804. // necessarily symmetric or synchronous transformation. For example,
  44805. // a zlib stream might take multiple plain-text writes(), and then
  44806. // emit a single compressed chunk some time in the future.
  44807. //
  44808. // Here's how this works:
  44809. //
  44810. // The Transform stream has all the aspects of the readable and writable
  44811. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  44812. // internally, and returns false if there's a lot of pending writes
  44813. // buffered up. When you call read(), that calls _read(n) until
  44814. // there's enough pending readable data buffered up.
  44815. //
  44816. // In a transform stream, the written data is placed in a buffer. When
  44817. // _read(n) is called, it transforms the queued up data, calling the
  44818. // buffered _write cb's as it consumes chunks. If consuming a single
  44819. // written chunk would result in multiple output chunks, then the first
  44820. // outputted bit calls the readcb, and subsequent chunks just go into
  44821. // the read buffer, and will cause it to emit 'readable' if necessary.
  44822. //
  44823. // This way, back-pressure is actually determined by the reading side,
  44824. // since _read has to be called to start processing a new chunk. However,
  44825. // a pathological inflate type of transform can cause excessive buffering
  44826. // here. For example, imagine a stream where every byte of input is
  44827. // interpreted as an integer from 0-255, and then results in that many
  44828. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  44829. // 1kb of data being output. In this case, you could write a very small
  44830. // amount of input, and end up with a very large amount of output. In
  44831. // such a pathological inflating mechanism, there'd be no way to tell
  44832. // the system to stop doing the transform. A single 4MB write could
  44833. // cause the system to run out of memory.
  44834. //
  44835. // However, even in such a pathological case, only a single written chunk
  44836. // would be consumed, and then the rest would wait (un-transformed) until
  44837. // the results of the previous transformed chunk were consumed.
  44838. 'use strict';
  44839. module.exports = Transform;
  44840. var _require$codes = require('../errors').codes,
  44841. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  44842. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  44843. ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
  44844. ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
  44845. var Duplex = require('./_stream_duplex');
  44846. require('inherits')(Transform, Duplex);
  44847. function afterTransform(er, data) {
  44848. var ts = this._transformState;
  44849. ts.transforming = false;
  44850. var cb = ts.writecb;
  44851. if (cb === null) {
  44852. return this.emit('error', new ERR_MULTIPLE_CALLBACK());
  44853. }
  44854. ts.writechunk = null;
  44855. ts.writecb = null;
  44856. if (data != null)
  44857. // single equals check for both `null` and `undefined`
  44858. this.push(data);
  44859. cb(er);
  44860. var rs = this._readableState;
  44861. rs.reading = false;
  44862. if (rs.needReadable || rs.length < rs.highWaterMark) {
  44863. this._read(rs.highWaterMark);
  44864. }
  44865. }
  44866. function Transform(options) {
  44867. if (!(this instanceof Transform)) return new Transform(options);
  44868. Duplex.call(this, options);
  44869. this._transformState = {
  44870. afterTransform: afterTransform.bind(this),
  44871. needTransform: false,
  44872. transforming: false,
  44873. writecb: null,
  44874. writechunk: null,
  44875. writeencoding: null
  44876. };
  44877. // start out asking for a readable event once data is transformed.
  44878. this._readableState.needReadable = true;
  44879. // we have implemented the _read method, and done the other things
  44880. // that Readable wants before the first _read call, so unset the
  44881. // sync guard flag.
  44882. this._readableState.sync = false;
  44883. if (options) {
  44884. if (typeof options.transform === 'function') this._transform = options.transform;
  44885. if (typeof options.flush === 'function') this._flush = options.flush;
  44886. }
  44887. // When the writable side finishes, then flush out anything remaining.
  44888. this.on('prefinish', prefinish);
  44889. }
  44890. function prefinish() {
  44891. var _this = this;
  44892. if (typeof this._flush === 'function' && !this._readableState.destroyed) {
  44893. this._flush(function (er, data) {
  44894. done(_this, er, data);
  44895. });
  44896. } else {
  44897. done(this, null, null);
  44898. }
  44899. }
  44900. Transform.prototype.push = function (chunk, encoding) {
  44901. this._transformState.needTransform = false;
  44902. return Duplex.prototype.push.call(this, chunk, encoding);
  44903. };
  44904. // This is the part where you do stuff!
  44905. // override this function in implementation classes.
  44906. // 'chunk' is an input chunk.
  44907. //
  44908. // Call `push(newChunk)` to pass along transformed output
  44909. // to the readable side. You may call 'push' zero or more times.
  44910. //
  44911. // Call `cb(err)` when you are done with this chunk. If you pass
  44912. // an error, then that'll put the hurt on the whole operation. If you
  44913. // never call cb(), then you'll never get another chunk.
  44914. Transform.prototype._transform = function (chunk, encoding, cb) {
  44915. cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
  44916. };
  44917. Transform.prototype._write = function (chunk, encoding, cb) {
  44918. var ts = this._transformState;
  44919. ts.writecb = cb;
  44920. ts.writechunk = chunk;
  44921. ts.writeencoding = encoding;
  44922. if (!ts.transforming) {
  44923. var rs = this._readableState;
  44924. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  44925. }
  44926. };
  44927. // Doesn't matter what the args are here.
  44928. // _transform does all the work.
  44929. // That we got here means that the readable side wants more data.
  44930. Transform.prototype._read = function (n) {
  44931. var ts = this._transformState;
  44932. if (ts.writechunk !== null && !ts.transforming) {
  44933. ts.transforming = true;
  44934. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  44935. } else {
  44936. // mark that we need a transform, so that any data that comes in
  44937. // will get processed, now that we've asked for it.
  44938. ts.needTransform = true;
  44939. }
  44940. };
  44941. Transform.prototype._destroy = function (err, cb) {
  44942. Duplex.prototype._destroy.call(this, err, function (err2) {
  44943. cb(err2);
  44944. });
  44945. };
  44946. function done(stream, er, data) {
  44947. if (er) return stream.emit('error', er);
  44948. if (data != null)
  44949. // single equals check for both `null` and `undefined`
  44950. stream.push(data);
  44951. // TODO(BridgeAR): Write a test for these two error cases
  44952. // if there's nothing in the write buffer, then that means
  44953. // that nothing more will ever be provided
  44954. if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
  44955. if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
  44956. return stream.push(null);
  44957. }
  44958. },{"../errors":316,"./_stream_duplex":317,"inherits":279}],321:[function(require,module,exports){
  44959. (function (process,global){(function (){
  44960. // Copyright Joyent, Inc. and other Node contributors.
  44961. //
  44962. // Permission is hereby granted, free of charge, to any person obtaining a
  44963. // copy of this software and associated documentation files (the
  44964. // "Software"), to deal in the Software without restriction, including
  44965. // without limitation the rights to use, copy, modify, merge, publish,
  44966. // distribute, sublicense, and/or sell copies of the Software, and to permit
  44967. // persons to whom the Software is furnished to do so, subject to the
  44968. // following conditions:
  44969. //
  44970. // The above copyright notice and this permission notice shall be included
  44971. // in all copies or substantial portions of the Software.
  44972. //
  44973. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  44974. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  44975. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  44976. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  44977. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  44978. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  44979. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  44980. // A bit simpler than readable streams.
  44981. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  44982. // the drain event emission and buffering.
  44983. 'use strict';
  44984. module.exports = Writable;
  44985. /* <replacement> */
  44986. function WriteReq(chunk, encoding, cb) {
  44987. this.chunk = chunk;
  44988. this.encoding = encoding;
  44989. this.callback = cb;
  44990. this.next = null;
  44991. }
  44992. // It seems a linked list but it is not
  44993. // there will be only 2 of these for each stream
  44994. function CorkedRequest(state) {
  44995. var _this = this;
  44996. this.next = null;
  44997. this.entry = null;
  44998. this.finish = function () {
  44999. onCorkedFinish(_this, state);
  45000. };
  45001. }
  45002. /* </replacement> */
  45003. /*<replacement>*/
  45004. var Duplex;
  45005. /*</replacement>*/
  45006. Writable.WritableState = WritableState;
  45007. /*<replacement>*/
  45008. var internalUtil = {
  45009. deprecate: require('util-deprecate')
  45010. };
  45011. /*</replacement>*/
  45012. /*<replacement>*/
  45013. var Stream = require('./internal/streams/stream');
  45014. /*</replacement>*/
  45015. var Buffer = require('buffer').Buffer;
  45016. var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
  45017. function _uint8ArrayToBuffer(chunk) {
  45018. return Buffer.from(chunk);
  45019. }
  45020. function _isUint8Array(obj) {
  45021. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  45022. }
  45023. var destroyImpl = require('./internal/streams/destroy');
  45024. var _require = require('./internal/streams/state'),
  45025. getHighWaterMark = _require.getHighWaterMark;
  45026. var _require$codes = require('../errors').codes,
  45027. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  45028. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  45029. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  45030. ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
  45031. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
  45032. ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
  45033. ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
  45034. ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
  45035. var errorOrDestroy = destroyImpl.errorOrDestroy;
  45036. require('inherits')(Writable, Stream);
  45037. function nop() {}
  45038. function WritableState(options, stream, isDuplex) {
  45039. Duplex = Duplex || require('./_stream_duplex');
  45040. options = options || {};
  45041. // Duplex streams are both readable and writable, but share
  45042. // the same options object.
  45043. // However, some cases require setting options to different
  45044. // values for the readable and the writable sides of the duplex stream,
  45045. // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
  45046. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
  45047. // object stream flag to indicate whether or not this stream
  45048. // contains buffers or objects.
  45049. this.objectMode = !!options.objectMode;
  45050. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  45051. // the point at which write() starts returning false
  45052. // Note: 0 is a valid value, means that we always return false if
  45053. // the entire buffer is not flushed immediately on write()
  45054. this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);
  45055. // if _final has been called
  45056. this.finalCalled = false;
  45057. // drain event flag.
  45058. this.needDrain = false;
  45059. // at the start of calling end()
  45060. this.ending = false;
  45061. // when end() has been called, and returned
  45062. this.ended = false;
  45063. // when 'finish' is emitted
  45064. this.finished = false;
  45065. // has it been destroyed
  45066. this.destroyed = false;
  45067. // should we decode strings into buffers before passing to _write?
  45068. // this is here so that some node-core streams can optimize string
  45069. // handling at a lower level.
  45070. var noDecode = options.decodeStrings === false;
  45071. this.decodeStrings = !noDecode;
  45072. // Crypto is kind of old and crusty. Historically, its default string
  45073. // encoding is 'binary' so we have to make this configurable.
  45074. // Everything else in the universe uses 'utf8', though.
  45075. this.defaultEncoding = options.defaultEncoding || 'utf8';
  45076. // not an actual buffer we keep track of, but a measurement
  45077. // of how much we're waiting to get pushed to some underlying
  45078. // socket or file.
  45079. this.length = 0;
  45080. // a flag to see when we're in the middle of a write.
  45081. this.writing = false;
  45082. // when true all writes will be buffered until .uncork() call
  45083. this.corked = 0;
  45084. // a flag to be able to tell if the onwrite cb is called immediately,
  45085. // or on a later tick. We set this to true at first, because any
  45086. // actions that shouldn't happen until "later" should generally also
  45087. // not happen before the first write call.
  45088. this.sync = true;
  45089. // a flag to know if we're processing previously buffered items, which
  45090. // may call the _write() callback in the same tick, so that we don't
  45091. // end up in an overlapped onwrite situation.
  45092. this.bufferProcessing = false;
  45093. // the callback that's passed to _write(chunk,cb)
  45094. this.onwrite = function (er) {
  45095. onwrite(stream, er);
  45096. };
  45097. // the callback that the user supplies to write(chunk,encoding,cb)
  45098. this.writecb = null;
  45099. // the amount that is being written when _write is called.
  45100. this.writelen = 0;
  45101. this.bufferedRequest = null;
  45102. this.lastBufferedRequest = null;
  45103. // number of pending user-supplied write callbacks
  45104. // this must be 0 before 'finish' can be emitted
  45105. this.pendingcb = 0;
  45106. // emit prefinish if the only thing we're waiting for is _write cbs
  45107. // This is relevant for synchronous Transform streams
  45108. this.prefinished = false;
  45109. // True if the error was already emitted and should not be thrown again
  45110. this.errorEmitted = false;
  45111. // Should close be emitted on destroy. Defaults to true.
  45112. this.emitClose = options.emitClose !== false;
  45113. // Should .destroy() be called after 'finish' (and potentially 'end')
  45114. this.autoDestroy = !!options.autoDestroy;
  45115. // count buffered requests
  45116. this.bufferedRequestCount = 0;
  45117. // allocate the first CorkedRequest, there is always
  45118. // one allocated and free to use, and we maintain at most two
  45119. this.corkedRequestsFree = new CorkedRequest(this);
  45120. }
  45121. WritableState.prototype.getBuffer = function getBuffer() {
  45122. var current = this.bufferedRequest;
  45123. var out = [];
  45124. while (current) {
  45125. out.push(current);
  45126. current = current.next;
  45127. }
  45128. return out;
  45129. };
  45130. (function () {
  45131. try {
  45132. Object.defineProperty(WritableState.prototype, 'buffer', {
  45133. get: internalUtil.deprecate(function writableStateBufferGetter() {
  45134. return this.getBuffer();
  45135. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  45136. });
  45137. } catch (_) {}
  45138. })();
  45139. // Test _writableState for inheritance to account for Duplex streams,
  45140. // whose prototype chain only points to Readable.
  45141. var realHasInstance;
  45142. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  45143. realHasInstance = Function.prototype[Symbol.hasInstance];
  45144. Object.defineProperty(Writable, Symbol.hasInstance, {
  45145. value: function value(object) {
  45146. if (realHasInstance.call(this, object)) return true;
  45147. if (this !== Writable) return false;
  45148. return object && object._writableState instanceof WritableState;
  45149. }
  45150. });
  45151. } else {
  45152. realHasInstance = function realHasInstance(object) {
  45153. return object instanceof this;
  45154. };
  45155. }
  45156. function Writable(options) {
  45157. Duplex = Duplex || require('./_stream_duplex');
  45158. // Writable ctor is applied to Duplexes, too.
  45159. // `realHasInstance` is necessary because using plain `instanceof`
  45160. // would return false, as no `_writableState` property is attached.
  45161. // Trying to use the custom `instanceof` for Writable here will also break the
  45162. // Node.js LazyTransform implementation, which has a non-trivial getter for
  45163. // `_writableState` that would lead to infinite recursion.
  45164. // Checking for a Stream.Duplex instance is faster here instead of inside
  45165. // the WritableState constructor, at least with V8 6.5
  45166. var isDuplex = this instanceof Duplex;
  45167. if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
  45168. this._writableState = new WritableState(options, this, isDuplex);
  45169. // legacy.
  45170. this.writable = true;
  45171. if (options) {
  45172. if (typeof options.write === 'function') this._write = options.write;
  45173. if (typeof options.writev === 'function') this._writev = options.writev;
  45174. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  45175. if (typeof options.final === 'function') this._final = options.final;
  45176. }
  45177. Stream.call(this);
  45178. }
  45179. // Otherwise people can pipe Writable streams, which is just wrong.
  45180. Writable.prototype.pipe = function () {
  45181. errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
  45182. };
  45183. function writeAfterEnd(stream, cb) {
  45184. var er = new ERR_STREAM_WRITE_AFTER_END();
  45185. // TODO: defer error events consistently everywhere, not just the cb
  45186. errorOrDestroy(stream, er);
  45187. process.nextTick(cb, er);
  45188. }
  45189. // Checks that a user-supplied chunk is valid, especially for the particular
  45190. // mode the stream is in. Currently this means that `null` is never accepted
  45191. // and undefined/non-string values are only allowed in object mode.
  45192. function validChunk(stream, state, chunk, cb) {
  45193. var er;
  45194. if (chunk === null) {
  45195. er = new ERR_STREAM_NULL_VALUES();
  45196. } else if (typeof chunk !== 'string' && !state.objectMode) {
  45197. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
  45198. }
  45199. if (er) {
  45200. errorOrDestroy(stream, er);
  45201. process.nextTick(cb, er);
  45202. return false;
  45203. }
  45204. return true;
  45205. }
  45206. Writable.prototype.write = function (chunk, encoding, cb) {
  45207. var state = this._writableState;
  45208. var ret = false;
  45209. var isBuf = !state.objectMode && _isUint8Array(chunk);
  45210. if (isBuf && !Buffer.isBuffer(chunk)) {
  45211. chunk = _uint8ArrayToBuffer(chunk);
  45212. }
  45213. if (typeof encoding === 'function') {
  45214. cb = encoding;
  45215. encoding = null;
  45216. }
  45217. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  45218. if (typeof cb !== 'function') cb = nop;
  45219. if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  45220. state.pendingcb++;
  45221. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  45222. }
  45223. return ret;
  45224. };
  45225. Writable.prototype.cork = function () {
  45226. this._writableState.corked++;
  45227. };
  45228. Writable.prototype.uncork = function () {
  45229. var state = this._writableState;
  45230. if (state.corked) {
  45231. state.corked--;
  45232. if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  45233. }
  45234. };
  45235. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  45236. // node::ParseEncoding() requires lower case.
  45237. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  45238. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
  45239. this._writableState.defaultEncoding = encoding;
  45240. return this;
  45241. };
  45242. Object.defineProperty(Writable.prototype, 'writableBuffer', {
  45243. // making it explicit this property is not enumerable
  45244. // because otherwise some prototype manipulation in
  45245. // userland will fail
  45246. enumerable: false,
  45247. get: function get() {
  45248. return this._writableState && this._writableState.getBuffer();
  45249. }
  45250. });
  45251. function decodeChunk(state, chunk, encoding) {
  45252. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  45253. chunk = Buffer.from(chunk, encoding);
  45254. }
  45255. return chunk;
  45256. }
  45257. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  45258. // making it explicit this property is not enumerable
  45259. // because otherwise some prototype manipulation in
  45260. // userland will fail
  45261. enumerable: false,
  45262. get: function get() {
  45263. return this._writableState.highWaterMark;
  45264. }
  45265. });
  45266. // if we're already writing something, then just put this
  45267. // in the queue, and wait our turn. Otherwise, call _write
  45268. // If we return false, then we need a drain event, so set that flag.
  45269. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  45270. if (!isBuf) {
  45271. var newChunk = decodeChunk(state, chunk, encoding);
  45272. if (chunk !== newChunk) {
  45273. isBuf = true;
  45274. encoding = 'buffer';
  45275. chunk = newChunk;
  45276. }
  45277. }
  45278. var len = state.objectMode ? 1 : chunk.length;
  45279. state.length += len;
  45280. var ret = state.length < state.highWaterMark;
  45281. // we must ensure that previous needDrain will not be reset to false.
  45282. if (!ret) state.needDrain = true;
  45283. if (state.writing || state.corked) {
  45284. var last = state.lastBufferedRequest;
  45285. state.lastBufferedRequest = {
  45286. chunk: chunk,
  45287. encoding: encoding,
  45288. isBuf: isBuf,
  45289. callback: cb,
  45290. next: null
  45291. };
  45292. if (last) {
  45293. last.next = state.lastBufferedRequest;
  45294. } else {
  45295. state.bufferedRequest = state.lastBufferedRequest;
  45296. }
  45297. state.bufferedRequestCount += 1;
  45298. } else {
  45299. doWrite(stream, state, false, len, chunk, encoding, cb);
  45300. }
  45301. return ret;
  45302. }
  45303. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  45304. state.writelen = len;
  45305. state.writecb = cb;
  45306. state.writing = true;
  45307. state.sync = true;
  45308. if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  45309. state.sync = false;
  45310. }
  45311. function onwriteError(stream, state, sync, er, cb) {
  45312. --state.pendingcb;
  45313. if (sync) {
  45314. // defer the callback if we are being called synchronously
  45315. // to avoid piling up things on the stack
  45316. process.nextTick(cb, er);
  45317. // this can emit finish, and it will always happen
  45318. // after error
  45319. process.nextTick(finishMaybe, stream, state);
  45320. stream._writableState.errorEmitted = true;
  45321. errorOrDestroy(stream, er);
  45322. } else {
  45323. // the caller expect this to happen before if
  45324. // it is async
  45325. cb(er);
  45326. stream._writableState.errorEmitted = true;
  45327. errorOrDestroy(stream, er);
  45328. // this can emit finish, but finish must
  45329. // always follow error
  45330. finishMaybe(stream, state);
  45331. }
  45332. }
  45333. function onwriteStateUpdate(state) {
  45334. state.writing = false;
  45335. state.writecb = null;
  45336. state.length -= state.writelen;
  45337. state.writelen = 0;
  45338. }
  45339. function onwrite(stream, er) {
  45340. var state = stream._writableState;
  45341. var sync = state.sync;
  45342. var cb = state.writecb;
  45343. if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
  45344. onwriteStateUpdate(state);
  45345. if (er) onwriteError(stream, state, sync, er, cb);else {
  45346. // Check if we're actually ready to finish, but don't emit yet
  45347. var finished = needFinish(state) || stream.destroyed;
  45348. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  45349. clearBuffer(stream, state);
  45350. }
  45351. if (sync) {
  45352. process.nextTick(afterWrite, stream, state, finished, cb);
  45353. } else {
  45354. afterWrite(stream, state, finished, cb);
  45355. }
  45356. }
  45357. }
  45358. function afterWrite(stream, state, finished, cb) {
  45359. if (!finished) onwriteDrain(stream, state);
  45360. state.pendingcb--;
  45361. cb();
  45362. finishMaybe(stream, state);
  45363. }
  45364. // Must force callback to be called on nextTick, so that we don't
  45365. // emit 'drain' before the write() consumer gets the 'false' return
  45366. // value, and has a chance to attach a 'drain' listener.
  45367. function onwriteDrain(stream, state) {
  45368. if (state.length === 0 && state.needDrain) {
  45369. state.needDrain = false;
  45370. stream.emit('drain');
  45371. }
  45372. }
  45373. // if there's something in the buffer waiting, then process it
  45374. function clearBuffer(stream, state) {
  45375. state.bufferProcessing = true;
  45376. var entry = state.bufferedRequest;
  45377. if (stream._writev && entry && entry.next) {
  45378. // Fast case, write everything using _writev()
  45379. var l = state.bufferedRequestCount;
  45380. var buffer = new Array(l);
  45381. var holder = state.corkedRequestsFree;
  45382. holder.entry = entry;
  45383. var count = 0;
  45384. var allBuffers = true;
  45385. while (entry) {
  45386. buffer[count] = entry;
  45387. if (!entry.isBuf) allBuffers = false;
  45388. entry = entry.next;
  45389. count += 1;
  45390. }
  45391. buffer.allBuffers = allBuffers;
  45392. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  45393. // doWrite is almost always async, defer these to save a bit of time
  45394. // as the hot path ends with doWrite
  45395. state.pendingcb++;
  45396. state.lastBufferedRequest = null;
  45397. if (holder.next) {
  45398. state.corkedRequestsFree = holder.next;
  45399. holder.next = null;
  45400. } else {
  45401. state.corkedRequestsFree = new CorkedRequest(state);
  45402. }
  45403. state.bufferedRequestCount = 0;
  45404. } else {
  45405. // Slow case, write chunks one-by-one
  45406. while (entry) {
  45407. var chunk = entry.chunk;
  45408. var encoding = entry.encoding;
  45409. var cb = entry.callback;
  45410. var len = state.objectMode ? 1 : chunk.length;
  45411. doWrite(stream, state, false, len, chunk, encoding, cb);
  45412. entry = entry.next;
  45413. state.bufferedRequestCount--;
  45414. // if we didn't call the onwrite immediately, then
  45415. // it means that we need to wait until it does.
  45416. // also, that means that the chunk and cb are currently
  45417. // being processed, so move the buffer counter past them.
  45418. if (state.writing) {
  45419. break;
  45420. }
  45421. }
  45422. if (entry === null) state.lastBufferedRequest = null;
  45423. }
  45424. state.bufferedRequest = entry;
  45425. state.bufferProcessing = false;
  45426. }
  45427. Writable.prototype._write = function (chunk, encoding, cb) {
  45428. cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
  45429. };
  45430. Writable.prototype._writev = null;
  45431. Writable.prototype.end = function (chunk, encoding, cb) {
  45432. var state = this._writableState;
  45433. if (typeof chunk === 'function') {
  45434. cb = chunk;
  45435. chunk = null;
  45436. encoding = null;
  45437. } else if (typeof encoding === 'function') {
  45438. cb = encoding;
  45439. encoding = null;
  45440. }
  45441. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  45442. // .end() fully uncorks
  45443. if (state.corked) {
  45444. state.corked = 1;
  45445. this.uncork();
  45446. }
  45447. // ignore unnecessary end() calls.
  45448. if (!state.ending) endWritable(this, state, cb);
  45449. return this;
  45450. };
  45451. Object.defineProperty(Writable.prototype, 'writableLength', {
  45452. // making it explicit this property is not enumerable
  45453. // because otherwise some prototype manipulation in
  45454. // userland will fail
  45455. enumerable: false,
  45456. get: function get() {
  45457. return this._writableState.length;
  45458. }
  45459. });
  45460. function needFinish(state) {
  45461. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  45462. }
  45463. function callFinal(stream, state) {
  45464. stream._final(function (err) {
  45465. state.pendingcb--;
  45466. if (err) {
  45467. errorOrDestroy(stream, err);
  45468. }
  45469. state.prefinished = true;
  45470. stream.emit('prefinish');
  45471. finishMaybe(stream, state);
  45472. });
  45473. }
  45474. function prefinish(stream, state) {
  45475. if (!state.prefinished && !state.finalCalled) {
  45476. if (typeof stream._final === 'function' && !state.destroyed) {
  45477. state.pendingcb++;
  45478. state.finalCalled = true;
  45479. process.nextTick(callFinal, stream, state);
  45480. } else {
  45481. state.prefinished = true;
  45482. stream.emit('prefinish');
  45483. }
  45484. }
  45485. }
  45486. function finishMaybe(stream, state) {
  45487. var need = needFinish(state);
  45488. if (need) {
  45489. prefinish(stream, state);
  45490. if (state.pendingcb === 0) {
  45491. state.finished = true;
  45492. stream.emit('finish');
  45493. if (state.autoDestroy) {
  45494. // In case of duplex streams we need a way to detect
  45495. // if the readable side is ready for autoDestroy as well
  45496. var rState = stream._readableState;
  45497. if (!rState || rState.autoDestroy && rState.endEmitted) {
  45498. stream.destroy();
  45499. }
  45500. }
  45501. }
  45502. }
  45503. return need;
  45504. }
  45505. function endWritable(stream, state, cb) {
  45506. state.ending = true;
  45507. finishMaybe(stream, state);
  45508. if (cb) {
  45509. if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
  45510. }
  45511. state.ended = true;
  45512. stream.writable = false;
  45513. }
  45514. function onCorkedFinish(corkReq, state, err) {
  45515. var entry = corkReq.entry;
  45516. corkReq.entry = null;
  45517. while (entry) {
  45518. var cb = entry.callback;
  45519. state.pendingcb--;
  45520. cb(err);
  45521. entry = entry.next;
  45522. }
  45523. // reuse the free corkReq.
  45524. state.corkedRequestsFree.next = corkReq;
  45525. }
  45526. Object.defineProperty(Writable.prototype, 'destroyed', {
  45527. // making it explicit this property is not enumerable
  45528. // because otherwise some prototype manipulation in
  45529. // userland will fail
  45530. enumerable: false,
  45531. get: function get() {
  45532. if (this._writableState === undefined) {
  45533. return false;
  45534. }
  45535. return this._writableState.destroyed;
  45536. },
  45537. set: function set(value) {
  45538. // we ignore the value if the stream
  45539. // has not been initialized yet
  45540. if (!this._writableState) {
  45541. return;
  45542. }
  45543. // backward compatibility, the user is explicitly
  45544. // managing destroyed
  45545. this._writableState.destroyed = value;
  45546. }
  45547. });
  45548. Writable.prototype.destroy = destroyImpl.destroy;
  45549. Writable.prototype._undestroy = destroyImpl.undestroy;
  45550. Writable.prototype._destroy = function (err, cb) {
  45551. cb(err);
  45552. };
  45553. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  45554. },{"../errors":316,"./_stream_duplex":317,"./internal/streams/destroy":324,"./internal/streams/state":328,"./internal/streams/stream":329,"_process":306,"buffer":220,"inherits":279,"util-deprecate":362}],322:[function(require,module,exports){
  45555. (function (process){(function (){
  45556. 'use strict';
  45557. var _Object$setPrototypeO;
  45558. function _defineProperty(obj, key, value) {
  45559. key = _toPropertyKey(key);
  45560. if (key in obj) {
  45561. Object.defineProperty(obj, key, {
  45562. value: value,
  45563. enumerable: true,
  45564. configurable: true,
  45565. writable: true
  45566. });
  45567. } else {
  45568. obj[key] = value;
  45569. }
  45570. return obj;
  45571. }
  45572. function _toPropertyKey(arg) {
  45573. var key = _toPrimitive(arg, "string");
  45574. return typeof key === "symbol" ? key : String(key);
  45575. }
  45576. function _toPrimitive(input, hint) {
  45577. if (typeof input !== "object" || input === null) return input;
  45578. var prim = input[Symbol.toPrimitive];
  45579. if (prim !== undefined) {
  45580. var res = prim.call(input, hint || "default");
  45581. if (typeof res !== "object") return res;
  45582. throw new TypeError("@@toPrimitive must return a primitive value.");
  45583. }
  45584. return (hint === "string" ? String : Number)(input);
  45585. }
  45586. var finished = require('./end-of-stream');
  45587. var kLastResolve = Symbol('lastResolve');
  45588. var kLastReject = Symbol('lastReject');
  45589. var kError = Symbol('error');
  45590. var kEnded = Symbol('ended');
  45591. var kLastPromise = Symbol('lastPromise');
  45592. var kHandlePromise = Symbol('handlePromise');
  45593. var kStream = Symbol('stream');
  45594. function createIterResult(value, done) {
  45595. return {
  45596. value: value,
  45597. done: done
  45598. };
  45599. }
  45600. function readAndResolve(iter) {
  45601. var resolve = iter[kLastResolve];
  45602. if (resolve !== null) {
  45603. var data = iter[kStream].read();
  45604. // we defer if data is null
  45605. // we can be expecting either 'end' or
  45606. // 'error'
  45607. if (data !== null) {
  45608. iter[kLastPromise] = null;
  45609. iter[kLastResolve] = null;
  45610. iter[kLastReject] = null;
  45611. resolve(createIterResult(data, false));
  45612. }
  45613. }
  45614. }
  45615. function onReadable(iter) {
  45616. // we wait for the next tick, because it might
  45617. // emit an error with process.nextTick
  45618. process.nextTick(readAndResolve, iter);
  45619. }
  45620. function wrapForNext(lastPromise, iter) {
  45621. return function (resolve, reject) {
  45622. lastPromise.then(function () {
  45623. if (iter[kEnded]) {
  45624. resolve(createIterResult(undefined, true));
  45625. return;
  45626. }
  45627. iter[kHandlePromise](resolve, reject);
  45628. }, reject);
  45629. };
  45630. }
  45631. var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
  45632. var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
  45633. get stream() {
  45634. return this[kStream];
  45635. },
  45636. next: function next() {
  45637. var _this = this;
  45638. // if we have detected an error in the meanwhile
  45639. // reject straight away
  45640. var error = this[kError];
  45641. if (error !== null) {
  45642. return Promise.reject(error);
  45643. }
  45644. if (this[kEnded]) {
  45645. return Promise.resolve(createIterResult(undefined, true));
  45646. }
  45647. if (this[kStream].destroyed) {
  45648. // We need to defer via nextTick because if .destroy(err) is
  45649. // called, the error will be emitted via nextTick, and
  45650. // we cannot guarantee that there is no error lingering around
  45651. // waiting to be emitted.
  45652. return new Promise(function (resolve, reject) {
  45653. process.nextTick(function () {
  45654. if (_this[kError]) {
  45655. reject(_this[kError]);
  45656. } else {
  45657. resolve(createIterResult(undefined, true));
  45658. }
  45659. });
  45660. });
  45661. }
  45662. // if we have multiple next() calls
  45663. // we will wait for the previous Promise to finish
  45664. // this logic is optimized to support for await loops,
  45665. // where next() is only called once at a time
  45666. var lastPromise = this[kLastPromise];
  45667. var promise;
  45668. if (lastPromise) {
  45669. promise = new Promise(wrapForNext(lastPromise, this));
  45670. } else {
  45671. // fast path needed to support multiple this.push()
  45672. // without triggering the next() queue
  45673. var data = this[kStream].read();
  45674. if (data !== null) {
  45675. return Promise.resolve(createIterResult(data, false));
  45676. }
  45677. promise = new Promise(this[kHandlePromise]);
  45678. }
  45679. this[kLastPromise] = promise;
  45680. return promise;
  45681. }
  45682. }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
  45683. return this;
  45684. }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
  45685. var _this2 = this;
  45686. // destroy(err, cb) is a private API
  45687. // we can guarantee we have that here, because we control the
  45688. // Readable class this is attached to
  45689. return new Promise(function (resolve, reject) {
  45690. _this2[kStream].destroy(null, function (err) {
  45691. if (err) {
  45692. reject(err);
  45693. return;
  45694. }
  45695. resolve(createIterResult(undefined, true));
  45696. });
  45697. });
  45698. }), _Object$setPrototypeO), AsyncIteratorPrototype);
  45699. var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
  45700. var _Object$create;
  45701. var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
  45702. value: stream,
  45703. writable: true
  45704. }), _defineProperty(_Object$create, kLastResolve, {
  45705. value: null,
  45706. writable: true
  45707. }), _defineProperty(_Object$create, kLastReject, {
  45708. value: null,
  45709. writable: true
  45710. }), _defineProperty(_Object$create, kError, {
  45711. value: null,
  45712. writable: true
  45713. }), _defineProperty(_Object$create, kEnded, {
  45714. value: stream._readableState.endEmitted,
  45715. writable: true
  45716. }), _defineProperty(_Object$create, kHandlePromise, {
  45717. value: function value(resolve, reject) {
  45718. var data = iterator[kStream].read();
  45719. if (data) {
  45720. iterator[kLastPromise] = null;
  45721. iterator[kLastResolve] = null;
  45722. iterator[kLastReject] = null;
  45723. resolve(createIterResult(data, false));
  45724. } else {
  45725. iterator[kLastResolve] = resolve;
  45726. iterator[kLastReject] = reject;
  45727. }
  45728. },
  45729. writable: true
  45730. }), _Object$create));
  45731. iterator[kLastPromise] = null;
  45732. finished(stream, function (err) {
  45733. if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
  45734. var reject = iterator[kLastReject];
  45735. // reject if we are waiting for data in the Promise
  45736. // returned by next() and store the error
  45737. if (reject !== null) {
  45738. iterator[kLastPromise] = null;
  45739. iterator[kLastResolve] = null;
  45740. iterator[kLastReject] = null;
  45741. reject(err);
  45742. }
  45743. iterator[kError] = err;
  45744. return;
  45745. }
  45746. var resolve = iterator[kLastResolve];
  45747. if (resolve !== null) {
  45748. iterator[kLastPromise] = null;
  45749. iterator[kLastResolve] = null;
  45750. iterator[kLastReject] = null;
  45751. resolve(createIterResult(undefined, true));
  45752. }
  45753. iterator[kEnded] = true;
  45754. });
  45755. stream.on('readable', onReadable.bind(null, iterator));
  45756. return iterator;
  45757. };
  45758. module.exports = createReadableStreamAsyncIterator;
  45759. }).call(this)}).call(this,require('_process'))
  45760. },{"./end-of-stream":325,"_process":306}],323:[function(require,module,exports){
  45761. 'use strict';
  45762. function ownKeys(object, enumerableOnly) {
  45763. var keys = Object.keys(object);
  45764. if (Object.getOwnPropertySymbols) {
  45765. var symbols = Object.getOwnPropertySymbols(object);
  45766. enumerableOnly && (symbols = symbols.filter(function (sym) {
  45767. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  45768. })), keys.push.apply(keys, symbols);
  45769. }
  45770. return keys;
  45771. }
  45772. function _objectSpread(target) {
  45773. for (var i = 1; i < arguments.length; i++) {
  45774. var source = null != arguments[i] ? arguments[i] : {};
  45775. i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
  45776. _defineProperty(target, key, source[key]);
  45777. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
  45778. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  45779. });
  45780. }
  45781. return target;
  45782. }
  45783. function _defineProperty(obj, key, value) {
  45784. key = _toPropertyKey(key);
  45785. if (key in obj) {
  45786. Object.defineProperty(obj, key, {
  45787. value: value,
  45788. enumerable: true,
  45789. configurable: true,
  45790. writable: true
  45791. });
  45792. } else {
  45793. obj[key] = value;
  45794. }
  45795. return obj;
  45796. }
  45797. function _classCallCheck(instance, Constructor) {
  45798. if (!(instance instanceof Constructor)) {
  45799. throw new TypeError("Cannot call a class as a function");
  45800. }
  45801. }
  45802. function _defineProperties(target, props) {
  45803. for (var i = 0; i < props.length; i++) {
  45804. var descriptor = props[i];
  45805. descriptor.enumerable = descriptor.enumerable || false;
  45806. descriptor.configurable = true;
  45807. if ("value" in descriptor) descriptor.writable = true;
  45808. Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
  45809. }
  45810. }
  45811. function _createClass(Constructor, protoProps, staticProps) {
  45812. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  45813. if (staticProps) _defineProperties(Constructor, staticProps);
  45814. Object.defineProperty(Constructor, "prototype", {
  45815. writable: false
  45816. });
  45817. return Constructor;
  45818. }
  45819. function _toPropertyKey(arg) {
  45820. var key = _toPrimitive(arg, "string");
  45821. return typeof key === "symbol" ? key : String(key);
  45822. }
  45823. function _toPrimitive(input, hint) {
  45824. if (typeof input !== "object" || input === null) return input;
  45825. var prim = input[Symbol.toPrimitive];
  45826. if (prim !== undefined) {
  45827. var res = prim.call(input, hint || "default");
  45828. if (typeof res !== "object") return res;
  45829. throw new TypeError("@@toPrimitive must return a primitive value.");
  45830. }
  45831. return (hint === "string" ? String : Number)(input);
  45832. }
  45833. var _require = require('buffer'),
  45834. Buffer = _require.Buffer;
  45835. var _require2 = require('util'),
  45836. inspect = _require2.inspect;
  45837. var custom = inspect && inspect.custom || 'inspect';
  45838. function copyBuffer(src, target, offset) {
  45839. Buffer.prototype.copy.call(src, target, offset);
  45840. }
  45841. module.exports = /*#__PURE__*/function () {
  45842. function BufferList() {
  45843. _classCallCheck(this, BufferList);
  45844. this.head = null;
  45845. this.tail = null;
  45846. this.length = 0;
  45847. }
  45848. _createClass(BufferList, [{
  45849. key: "push",
  45850. value: function push(v) {
  45851. var entry = {
  45852. data: v,
  45853. next: null
  45854. };
  45855. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  45856. this.tail = entry;
  45857. ++this.length;
  45858. }
  45859. }, {
  45860. key: "unshift",
  45861. value: function unshift(v) {
  45862. var entry = {
  45863. data: v,
  45864. next: this.head
  45865. };
  45866. if (this.length === 0) this.tail = entry;
  45867. this.head = entry;
  45868. ++this.length;
  45869. }
  45870. }, {
  45871. key: "shift",
  45872. value: function shift() {
  45873. if (this.length === 0) return;
  45874. var ret = this.head.data;
  45875. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  45876. --this.length;
  45877. return ret;
  45878. }
  45879. }, {
  45880. key: "clear",
  45881. value: function clear() {
  45882. this.head = this.tail = null;
  45883. this.length = 0;
  45884. }
  45885. }, {
  45886. key: "join",
  45887. value: function join(s) {
  45888. if (this.length === 0) return '';
  45889. var p = this.head;
  45890. var ret = '' + p.data;
  45891. while (p = p.next) ret += s + p.data;
  45892. return ret;
  45893. }
  45894. }, {
  45895. key: "concat",
  45896. value: function concat(n) {
  45897. if (this.length === 0) return Buffer.alloc(0);
  45898. var ret = Buffer.allocUnsafe(n >>> 0);
  45899. var p = this.head;
  45900. var i = 0;
  45901. while (p) {
  45902. copyBuffer(p.data, ret, i);
  45903. i += p.data.length;
  45904. p = p.next;
  45905. }
  45906. return ret;
  45907. }
  45908. // Consumes a specified amount of bytes or characters from the buffered data.
  45909. }, {
  45910. key: "consume",
  45911. value: function consume(n, hasStrings) {
  45912. var ret;
  45913. if (n < this.head.data.length) {
  45914. // `slice` is the same for buffers and strings.
  45915. ret = this.head.data.slice(0, n);
  45916. this.head.data = this.head.data.slice(n);
  45917. } else if (n === this.head.data.length) {
  45918. // First chunk is a perfect match.
  45919. ret = this.shift();
  45920. } else {
  45921. // Result spans more than one buffer.
  45922. ret = hasStrings ? this._getString(n) : this._getBuffer(n);
  45923. }
  45924. return ret;
  45925. }
  45926. }, {
  45927. key: "first",
  45928. value: function first() {
  45929. return this.head.data;
  45930. }
  45931. // Consumes a specified amount of characters from the buffered data.
  45932. }, {
  45933. key: "_getString",
  45934. value: function _getString(n) {
  45935. var p = this.head;
  45936. var c = 1;
  45937. var ret = p.data;
  45938. n -= ret.length;
  45939. while (p = p.next) {
  45940. var str = p.data;
  45941. var nb = n > str.length ? str.length : n;
  45942. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  45943. n -= nb;
  45944. if (n === 0) {
  45945. if (nb === str.length) {
  45946. ++c;
  45947. if (p.next) this.head = p.next;else this.head = this.tail = null;
  45948. } else {
  45949. this.head = p;
  45950. p.data = str.slice(nb);
  45951. }
  45952. break;
  45953. }
  45954. ++c;
  45955. }
  45956. this.length -= c;
  45957. return ret;
  45958. }
  45959. // Consumes a specified amount of bytes from the buffered data.
  45960. }, {
  45961. key: "_getBuffer",
  45962. value: function _getBuffer(n) {
  45963. var ret = Buffer.allocUnsafe(n);
  45964. var p = this.head;
  45965. var c = 1;
  45966. p.data.copy(ret);
  45967. n -= p.data.length;
  45968. while (p = p.next) {
  45969. var buf = p.data;
  45970. var nb = n > buf.length ? buf.length : n;
  45971. buf.copy(ret, ret.length - n, 0, nb);
  45972. n -= nb;
  45973. if (n === 0) {
  45974. if (nb === buf.length) {
  45975. ++c;
  45976. if (p.next) this.head = p.next;else this.head = this.tail = null;
  45977. } else {
  45978. this.head = p;
  45979. p.data = buf.slice(nb);
  45980. }
  45981. break;
  45982. }
  45983. ++c;
  45984. }
  45985. this.length -= c;
  45986. return ret;
  45987. }
  45988. // Make sure the linked list only shows the minimal necessary information.
  45989. }, {
  45990. key: custom,
  45991. value: function value(_, options) {
  45992. return inspect(this, _objectSpread(_objectSpread({}, options), {}, {
  45993. // Only inspect one level.
  45994. depth: 0,
  45995. // It should not recurse.
  45996. customInspect: false
  45997. }));
  45998. }
  45999. }]);
  46000. return BufferList;
  46001. }();
  46002. },{"buffer":220,"util":188}],324:[function(require,module,exports){
  46003. (function (process){(function (){
  46004. 'use strict';
  46005. // undocumented cb() API, needed for core, not for public API
  46006. function destroy(err, cb) {
  46007. var _this = this;
  46008. var readableDestroyed = this._readableState && this._readableState.destroyed;
  46009. var writableDestroyed = this._writableState && this._writableState.destroyed;
  46010. if (readableDestroyed || writableDestroyed) {
  46011. if (cb) {
  46012. cb(err);
  46013. } else if (err) {
  46014. if (!this._writableState) {
  46015. process.nextTick(emitErrorNT, this, err);
  46016. } else if (!this._writableState.errorEmitted) {
  46017. this._writableState.errorEmitted = true;
  46018. process.nextTick(emitErrorNT, this, err);
  46019. }
  46020. }
  46021. return this;
  46022. }
  46023. // we set destroyed to true before firing error callbacks in order
  46024. // to make it re-entrance safe in case destroy() is called within callbacks
  46025. if (this._readableState) {
  46026. this._readableState.destroyed = true;
  46027. }
  46028. // if this is a duplex stream mark the writable part as destroyed as well
  46029. if (this._writableState) {
  46030. this._writableState.destroyed = true;
  46031. }
  46032. this._destroy(err || null, function (err) {
  46033. if (!cb && err) {
  46034. if (!_this._writableState) {
  46035. process.nextTick(emitErrorAndCloseNT, _this, err);
  46036. } else if (!_this._writableState.errorEmitted) {
  46037. _this._writableState.errorEmitted = true;
  46038. process.nextTick(emitErrorAndCloseNT, _this, err);
  46039. } else {
  46040. process.nextTick(emitCloseNT, _this);
  46041. }
  46042. } else if (cb) {
  46043. process.nextTick(emitCloseNT, _this);
  46044. cb(err);
  46045. } else {
  46046. process.nextTick(emitCloseNT, _this);
  46047. }
  46048. });
  46049. return this;
  46050. }
  46051. function emitErrorAndCloseNT(self, err) {
  46052. emitErrorNT(self, err);
  46053. emitCloseNT(self);
  46054. }
  46055. function emitCloseNT(self) {
  46056. if (self._writableState && !self._writableState.emitClose) return;
  46057. if (self._readableState && !self._readableState.emitClose) return;
  46058. self.emit('close');
  46059. }
  46060. function undestroy() {
  46061. if (this._readableState) {
  46062. this._readableState.destroyed = false;
  46063. this._readableState.reading = false;
  46064. this._readableState.ended = false;
  46065. this._readableState.endEmitted = false;
  46066. }
  46067. if (this._writableState) {
  46068. this._writableState.destroyed = false;
  46069. this._writableState.ended = false;
  46070. this._writableState.ending = false;
  46071. this._writableState.finalCalled = false;
  46072. this._writableState.prefinished = false;
  46073. this._writableState.finished = false;
  46074. this._writableState.errorEmitted = false;
  46075. }
  46076. }
  46077. function emitErrorNT(self, err) {
  46078. self.emit('error', err);
  46079. }
  46080. function errorOrDestroy(stream, err) {
  46081. // We have tests that rely on errors being emitted
  46082. // in the same tick, so changing this is semver major.
  46083. // For now when you opt-in to autoDestroy we allow
  46084. // the error to be emitted nextTick. In a future
  46085. // semver major update we should change the default to this.
  46086. var rState = stream._readableState;
  46087. var wState = stream._writableState;
  46088. if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
  46089. }
  46090. module.exports = {
  46091. destroy: destroy,
  46092. undestroy: undestroy,
  46093. errorOrDestroy: errorOrDestroy
  46094. };
  46095. }).call(this)}).call(this,require('_process'))
  46096. },{"_process":306}],325:[function(require,module,exports){
  46097. // Ported from https://github.com/mafintosh/end-of-stream with
  46098. // permission from the author, Mathias Buus (@mafintosh).
  46099. 'use strict';
  46100. var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
  46101. function once(callback) {
  46102. var called = false;
  46103. return function () {
  46104. if (called) return;
  46105. called = true;
  46106. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  46107. args[_key] = arguments[_key];
  46108. }
  46109. callback.apply(this, args);
  46110. };
  46111. }
  46112. function noop() {}
  46113. function isRequest(stream) {
  46114. return stream.setHeader && typeof stream.abort === 'function';
  46115. }
  46116. function eos(stream, opts, callback) {
  46117. if (typeof opts === 'function') return eos(stream, null, opts);
  46118. if (!opts) opts = {};
  46119. callback = once(callback || noop);
  46120. var readable = opts.readable || opts.readable !== false && stream.readable;
  46121. var writable = opts.writable || opts.writable !== false && stream.writable;
  46122. var onlegacyfinish = function onlegacyfinish() {
  46123. if (!stream.writable) onfinish();
  46124. };
  46125. var writableEnded = stream._writableState && stream._writableState.finished;
  46126. var onfinish = function onfinish() {
  46127. writable = false;
  46128. writableEnded = true;
  46129. if (!readable) callback.call(stream);
  46130. };
  46131. var readableEnded = stream._readableState && stream._readableState.endEmitted;
  46132. var onend = function onend() {
  46133. readable = false;
  46134. readableEnded = true;
  46135. if (!writable) callback.call(stream);
  46136. };
  46137. var onerror = function onerror(err) {
  46138. callback.call(stream, err);
  46139. };
  46140. var onclose = function onclose() {
  46141. var err;
  46142. if (readable && !readableEnded) {
  46143. if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  46144. return callback.call(stream, err);
  46145. }
  46146. if (writable && !writableEnded) {
  46147. if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  46148. return callback.call(stream, err);
  46149. }
  46150. };
  46151. var onrequest = function onrequest() {
  46152. stream.req.on('finish', onfinish);
  46153. };
  46154. if (isRequest(stream)) {
  46155. stream.on('complete', onfinish);
  46156. stream.on('abort', onclose);
  46157. if (stream.req) onrequest();else stream.on('request', onrequest);
  46158. } else if (writable && !stream._writableState) {
  46159. // legacy streams
  46160. stream.on('end', onlegacyfinish);
  46161. stream.on('close', onlegacyfinish);
  46162. }
  46163. stream.on('end', onend);
  46164. stream.on('finish', onfinish);
  46165. if (opts.error !== false) stream.on('error', onerror);
  46166. stream.on('close', onclose);
  46167. return function () {
  46168. stream.removeListener('complete', onfinish);
  46169. stream.removeListener('abort', onclose);
  46170. stream.removeListener('request', onrequest);
  46171. if (stream.req) stream.req.removeListener('finish', onfinish);
  46172. stream.removeListener('end', onlegacyfinish);
  46173. stream.removeListener('close', onlegacyfinish);
  46174. stream.removeListener('finish', onfinish);
  46175. stream.removeListener('end', onend);
  46176. stream.removeListener('error', onerror);
  46177. stream.removeListener('close', onclose);
  46178. };
  46179. }
  46180. module.exports = eos;
  46181. },{"../../../errors":316}],326:[function(require,module,exports){
  46182. "use strict";
  46183. module.exports = function () {
  46184. throw new Error('Readable.from is not available in the browser');
  46185. };
  46186. },{}],327:[function(require,module,exports){
  46187. // Ported from https://github.com/mafintosh/pump with
  46188. // permission from the author, Mathias Buus (@mafintosh).
  46189. 'use strict';
  46190. var eos;
  46191. function once(callback) {
  46192. var called = false;
  46193. return function () {
  46194. if (called) return;
  46195. called = true;
  46196. callback.apply(void 0, arguments);
  46197. };
  46198. }
  46199. var _require$codes = require('../../../errors').codes,
  46200. ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
  46201. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
  46202. function noop(err) {
  46203. // Rethrow the error if it exists to avoid swallowing it
  46204. if (err) throw err;
  46205. }
  46206. function isRequest(stream) {
  46207. return stream.setHeader && typeof stream.abort === 'function';
  46208. }
  46209. function destroyer(stream, reading, writing, callback) {
  46210. callback = once(callback);
  46211. var closed = false;
  46212. stream.on('close', function () {
  46213. closed = true;
  46214. });
  46215. if (eos === undefined) eos = require('./end-of-stream');
  46216. eos(stream, {
  46217. readable: reading,
  46218. writable: writing
  46219. }, function (err) {
  46220. if (err) return callback(err);
  46221. closed = true;
  46222. callback();
  46223. });
  46224. var destroyed = false;
  46225. return function (err) {
  46226. if (closed) return;
  46227. if (destroyed) return;
  46228. destroyed = true;
  46229. // request.destroy just do .end - .abort is what we want
  46230. if (isRequest(stream)) return stream.abort();
  46231. if (typeof stream.destroy === 'function') return stream.destroy();
  46232. callback(err || new ERR_STREAM_DESTROYED('pipe'));
  46233. };
  46234. }
  46235. function call(fn) {
  46236. fn();
  46237. }
  46238. function pipe(from, to) {
  46239. return from.pipe(to);
  46240. }
  46241. function popCallback(streams) {
  46242. if (!streams.length) return noop;
  46243. if (typeof streams[streams.length - 1] !== 'function') return noop;
  46244. return streams.pop();
  46245. }
  46246. function pipeline() {
  46247. for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
  46248. streams[_key] = arguments[_key];
  46249. }
  46250. var callback = popCallback(streams);
  46251. if (Array.isArray(streams[0])) streams = streams[0];
  46252. if (streams.length < 2) {
  46253. throw new ERR_MISSING_ARGS('streams');
  46254. }
  46255. var error;
  46256. var destroys = streams.map(function (stream, i) {
  46257. var reading = i < streams.length - 1;
  46258. var writing = i > 0;
  46259. return destroyer(stream, reading, writing, function (err) {
  46260. if (!error) error = err;
  46261. if (err) destroys.forEach(call);
  46262. if (reading) return;
  46263. destroys.forEach(call);
  46264. callback(error);
  46265. });
  46266. });
  46267. return streams.reduce(pipe);
  46268. }
  46269. module.exports = pipeline;
  46270. },{"../../../errors":316,"./end-of-stream":325}],328:[function(require,module,exports){
  46271. 'use strict';
  46272. var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
  46273. function highWaterMarkFrom(options, isDuplex, duplexKey) {
  46274. return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
  46275. }
  46276. function getHighWaterMark(state, options, duplexKey, isDuplex) {
  46277. var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  46278. if (hwm != null) {
  46279. if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
  46280. var name = isDuplex ? duplexKey : 'highWaterMark';
  46281. throw new ERR_INVALID_OPT_VALUE(name, hwm);
  46282. }
  46283. return Math.floor(hwm);
  46284. }
  46285. // Default value
  46286. return state.objectMode ? 16 : 16 * 1024;
  46287. }
  46288. module.exports = {
  46289. getHighWaterMark: getHighWaterMark
  46290. };
  46291. },{"../../../errors":316}],329:[function(require,module,exports){
  46292. "use strict";
  46293. module.exports = require('events').EventEmitter;
  46294. },{"events":261}],330:[function(require,module,exports){
  46295. "use strict";
  46296. exports = module.exports = require('./lib/_stream_readable.js');
  46297. exports.Stream = exports;
  46298. exports.Readable = exports;
  46299. exports.Writable = require('./lib/_stream_writable.js');
  46300. exports.Duplex = require('./lib/_stream_duplex.js');
  46301. exports.Transform = require('./lib/_stream_transform.js');
  46302. exports.PassThrough = require('./lib/_stream_passthrough.js');
  46303. exports.finished = require('./lib/internal/streams/end-of-stream.js');
  46304. exports.pipeline = require('./lib/internal/streams/pipeline.js');
  46305. },{"./lib/_stream_duplex.js":317,"./lib/_stream_passthrough.js":318,"./lib/_stream_readable.js":319,"./lib/_stream_transform.js":320,"./lib/_stream_writable.js":321,"./lib/internal/streams/end-of-stream.js":325,"./lib/internal/streams/pipeline.js":327}],331:[function(require,module,exports){
  46306. 'use strict';
  46307. var Buffer = require('buffer').Buffer;
  46308. var inherits = require('inherits');
  46309. var HashBase = require('hash-base');
  46310. var ARRAY16 = new Array(16);
  46311. var zl = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13];
  46312. var zr = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11];
  46313. var sl = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6];
  46314. var sr = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11];
  46315. var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e];
  46316. var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000];
  46317. function RIPEMD160() {
  46318. HashBase.call(this, 64);
  46319. // state
  46320. this._a = 0x67452301;
  46321. this._b = 0xefcdab89;
  46322. this._c = 0x98badcfe;
  46323. this._d = 0x10325476;
  46324. this._e = 0xc3d2e1f0;
  46325. }
  46326. inherits(RIPEMD160, HashBase);
  46327. RIPEMD160.prototype._update = function () {
  46328. var words = ARRAY16;
  46329. for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4);
  46330. var al = this._a | 0;
  46331. var bl = this._b | 0;
  46332. var cl = this._c | 0;
  46333. var dl = this._d | 0;
  46334. var el = this._e | 0;
  46335. var ar = this._a | 0;
  46336. var br = this._b | 0;
  46337. var cr = this._c | 0;
  46338. var dr = this._d | 0;
  46339. var er = this._e | 0;
  46340. // computation
  46341. for (var i = 0; i < 80; i += 1) {
  46342. var tl;
  46343. var tr;
  46344. if (i < 16) {
  46345. tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]);
  46346. tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]);
  46347. } else if (i < 32) {
  46348. tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]);
  46349. tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]);
  46350. } else if (i < 48) {
  46351. tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]);
  46352. tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]);
  46353. } else if (i < 64) {
  46354. tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]);
  46355. tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]);
  46356. } else {
  46357. // if (i<80) {
  46358. tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]);
  46359. tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]);
  46360. }
  46361. al = el;
  46362. el = dl;
  46363. dl = rotl(cl, 10);
  46364. cl = bl;
  46365. bl = tl;
  46366. ar = er;
  46367. er = dr;
  46368. dr = rotl(cr, 10);
  46369. cr = br;
  46370. br = tr;
  46371. }
  46372. // update state
  46373. var t = this._b + cl + dr | 0;
  46374. this._b = this._c + dl + er | 0;
  46375. this._c = this._d + el + ar | 0;
  46376. this._d = this._e + al + br | 0;
  46377. this._e = this._a + bl + cr | 0;
  46378. this._a = t;
  46379. };
  46380. RIPEMD160.prototype._digest = function () {
  46381. // create padding and handle blocks
  46382. this._block[this._blockOffset++] = 0x80;
  46383. if (this._blockOffset > 56) {
  46384. this._block.fill(0, this._blockOffset, 64);
  46385. this._update();
  46386. this._blockOffset = 0;
  46387. }
  46388. this._block.fill(0, this._blockOffset, 56);
  46389. this._block.writeUInt32LE(this._length[0], 56);
  46390. this._block.writeUInt32LE(this._length[1], 60);
  46391. this._update();
  46392. // produce result
  46393. var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20);
  46394. buffer.writeInt32LE(this._a, 0);
  46395. buffer.writeInt32LE(this._b, 4);
  46396. buffer.writeInt32LE(this._c, 8);
  46397. buffer.writeInt32LE(this._d, 12);
  46398. buffer.writeInt32LE(this._e, 16);
  46399. return buffer;
  46400. };
  46401. function rotl(x, n) {
  46402. return x << n | x >>> 32 - n;
  46403. }
  46404. function fn1(a, b, c, d, e, m, k, s) {
  46405. return rotl(a + (b ^ c ^ d) + m + k | 0, s) + e | 0;
  46406. }
  46407. function fn2(a, b, c, d, e, m, k, s) {
  46408. return rotl(a + (b & c | ~b & d) + m + k | 0, s) + e | 0;
  46409. }
  46410. function fn3(a, b, c, d, e, m, k, s) {
  46411. return rotl(a + ((b | ~c) ^ d) + m + k | 0, s) + e | 0;
  46412. }
  46413. function fn4(a, b, c, d, e, m, k, s) {
  46414. return rotl(a + (b & d | c & ~d) + m + k | 0, s) + e | 0;
  46415. }
  46416. function fn5(a, b, c, d, e, m, k, s) {
  46417. return rotl(a + (b ^ (c | ~d)) + m + k | 0, s) + e | 0;
  46418. }
  46419. module.exports = RIPEMD160;
  46420. },{"buffer":220,"hash-base":264,"inherits":279}],332:[function(require,module,exports){
  46421. "use strict";
  46422. /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  46423. /* eslint-disable node/no-deprecated-api */
  46424. var buffer = require('buffer');
  46425. var Buffer = buffer.Buffer;
  46426. // alternative to using Object.keys for old browsers
  46427. function copyProps(src, dst) {
  46428. for (var key in src) {
  46429. dst[key] = src[key];
  46430. }
  46431. }
  46432. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  46433. module.exports = buffer;
  46434. } else {
  46435. // Copy properties from require('buffer')
  46436. copyProps(buffer, exports);
  46437. exports.Buffer = SafeBuffer;
  46438. }
  46439. function SafeBuffer(arg, encodingOrOffset, length) {
  46440. return Buffer(arg, encodingOrOffset, length);
  46441. }
  46442. SafeBuffer.prototype = Object.create(Buffer.prototype);
  46443. // Copy static methods from Buffer
  46444. copyProps(Buffer, SafeBuffer);
  46445. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  46446. if (typeof arg === 'number') {
  46447. throw new TypeError('Argument must not be a number');
  46448. }
  46449. return Buffer(arg, encodingOrOffset, length);
  46450. };
  46451. SafeBuffer.alloc = function (size, fill, encoding) {
  46452. if (typeof size !== 'number') {
  46453. throw new TypeError('Argument must be a number');
  46454. }
  46455. var buf = Buffer(size);
  46456. if (fill !== undefined) {
  46457. if (typeof encoding === 'string') {
  46458. buf.fill(fill, encoding);
  46459. } else {
  46460. buf.fill(fill);
  46461. }
  46462. } else {
  46463. buf.fill(0);
  46464. }
  46465. return buf;
  46466. };
  46467. SafeBuffer.allocUnsafe = function (size) {
  46468. if (typeof size !== 'number') {
  46469. throw new TypeError('Argument must be a number');
  46470. }
  46471. return Buffer(size);
  46472. };
  46473. SafeBuffer.allocUnsafeSlow = function (size) {
  46474. if (typeof size !== 'number') {
  46475. throw new TypeError('Argument must be a number');
  46476. }
  46477. return buffer.SlowBuffer(size);
  46478. };
  46479. },{"buffer":220}],333:[function(require,module,exports){
  46480. (function (process){(function (){
  46481. /* eslint-disable node/no-deprecated-api */
  46482. 'use strict';
  46483. var buffer = require('buffer');
  46484. var Buffer = buffer.Buffer;
  46485. var safer = {};
  46486. var key;
  46487. for (key in buffer) {
  46488. if (!buffer.hasOwnProperty(key)) continue;
  46489. if (key === 'SlowBuffer' || key === 'Buffer') continue;
  46490. safer[key] = buffer[key];
  46491. }
  46492. var Safer = safer.Buffer = {};
  46493. for (key in Buffer) {
  46494. if (!Buffer.hasOwnProperty(key)) continue;
  46495. if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue;
  46496. Safer[key] = Buffer[key];
  46497. }
  46498. safer.Buffer.prototype = Buffer.prototype;
  46499. if (!Safer.from || Safer.from === Uint8Array.from) {
  46500. Safer.from = function (value, encodingOrOffset, length) {
  46501. if (typeof value === 'number') {
  46502. throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value);
  46503. }
  46504. if (value && typeof value.length === 'undefined') {
  46505. throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value);
  46506. }
  46507. return Buffer(value, encodingOrOffset, length);
  46508. };
  46509. }
  46510. if (!Safer.alloc) {
  46511. Safer.alloc = function (size, fill, encoding) {
  46512. if (typeof size !== 'number') {
  46513. throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size);
  46514. }
  46515. if (size < 0 || size >= 2 * (1 << 30)) {
  46516. throw new RangeError('The value "' + size + '" is invalid for option "size"');
  46517. }
  46518. var buf = Buffer(size);
  46519. if (!fill || fill.length === 0) {
  46520. buf.fill(0);
  46521. } else if (typeof encoding === 'string') {
  46522. buf.fill(fill, encoding);
  46523. } else {
  46524. buf.fill(fill);
  46525. }
  46526. return buf;
  46527. };
  46528. }
  46529. if (!safer.kStringMaxLength) {
  46530. try {
  46531. safer.kStringMaxLength = process.binding('buffer').kStringMaxLength;
  46532. } catch (e) {
  46533. // we can't determine kStringMaxLength in environments where process.binding
  46534. // is unsupported, so let's not set it
  46535. }
  46536. }
  46537. if (!safer.constants) {
  46538. safer.constants = {
  46539. MAX_LENGTH: safer.kMaxLength
  46540. };
  46541. if (safer.kStringMaxLength) {
  46542. safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength;
  46543. }
  46544. }
  46545. module.exports = safer;
  46546. }).call(this)}).call(this,require('_process'))
  46547. },{"_process":306,"buffer":220}],334:[function(require,module,exports){
  46548. "use strict";
  46549. Object.defineProperty(exports, "__esModule", {
  46550. value: true
  46551. });
  46552. const ed5 = require("xmlchars/xml/1.0/ed5");
  46553. const ed2 = require("xmlchars/xml/1.1/ed2");
  46554. const NSed3 = require("xmlchars/xmlns/1.0/ed3");
  46555. var isS = ed5.isS;
  46556. var isChar10 = ed5.isChar;
  46557. var isNameStartChar = ed5.isNameStartChar;
  46558. var isNameChar = ed5.isNameChar;
  46559. var S_LIST = ed5.S_LIST;
  46560. var NAME_RE = ed5.NAME_RE;
  46561. var isChar11 = ed2.isChar;
  46562. var isNCNameStartChar = NSed3.isNCNameStartChar;
  46563. var isNCNameChar = NSed3.isNCNameChar;
  46564. var NC_NAME_RE = NSed3.NC_NAME_RE;
  46565. const XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace";
  46566. const XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
  46567. const rootNS = {
  46568. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  46569. __proto__: null,
  46570. xml: XML_NAMESPACE,
  46571. xmlns: XMLNS_NAMESPACE
  46572. };
  46573. const XML_ENTITIES = {
  46574. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  46575. __proto__: null,
  46576. amp: "&",
  46577. gt: ">",
  46578. lt: "<",
  46579. quot: "\"",
  46580. apos: "'"
  46581. };
  46582. // EOC: end-of-chunk
  46583. const EOC = -1;
  46584. const NL_LIKE = -2;
  46585. const S_BEGIN = 0; // Initial state.
  46586. const S_BEGIN_WHITESPACE = 1; // leading whitespace
  46587. const S_DOCTYPE = 2; // <!DOCTYPE
  46588. const S_DOCTYPE_QUOTE = 3; // <!DOCTYPE "//blah
  46589. const S_DTD = 4; // <!DOCTYPE "//blah" [ ...
  46590. const S_DTD_QUOTED = 5; // <!DOCTYPE "//blah" [ "foo
  46591. const S_DTD_OPEN_WAKA = 6;
  46592. const S_DTD_OPEN_WAKA_BANG = 7;
  46593. const S_DTD_COMMENT = 8; // <!--
  46594. const S_DTD_COMMENT_ENDING = 9; // <!-- blah -
  46595. const S_DTD_COMMENT_ENDED = 10; // <!-- blah --
  46596. const S_DTD_PI = 11; // <?
  46597. const S_DTD_PI_ENDING = 12; // <?hi "there" ?
  46598. const S_TEXT = 13; // general stuff
  46599. const S_ENTITY = 14; // &amp and such
  46600. const S_OPEN_WAKA = 15; // <
  46601. const S_OPEN_WAKA_BANG = 16; // <!...
  46602. const S_COMMENT = 17; // <!--
  46603. const S_COMMENT_ENDING = 18; // <!-- blah -
  46604. const S_COMMENT_ENDED = 19; // <!-- blah --
  46605. const S_CDATA = 20; // <![CDATA[ something
  46606. const S_CDATA_ENDING = 21; // ]
  46607. const S_CDATA_ENDING_2 = 22; // ]]
  46608. const S_PI_FIRST_CHAR = 23; // <?hi, first char
  46609. const S_PI_REST = 24; // <?hi, rest of the name
  46610. const S_PI_BODY = 25; // <?hi there
  46611. const S_PI_ENDING = 26; // <?hi "there" ?
  46612. const S_XML_DECL_NAME_START = 27; // <?xml
  46613. const S_XML_DECL_NAME = 28; // <?xml foo
  46614. const S_XML_DECL_EQ = 29; // <?xml foo=
  46615. const S_XML_DECL_VALUE_START = 30; // <?xml foo=
  46616. const S_XML_DECL_VALUE = 31; // <?xml foo="bar"
  46617. const S_XML_DECL_SEPARATOR = 32; // <?xml foo="bar"
  46618. const S_XML_DECL_ENDING = 33; // <?xml ... ?
  46619. const S_OPEN_TAG = 34; // <strong
  46620. const S_OPEN_TAG_SLASH = 35; // <strong /
  46621. const S_ATTRIB = 36; // <a
  46622. const S_ATTRIB_NAME = 37; // <a foo
  46623. const S_ATTRIB_NAME_SAW_WHITE = 38; // <a foo _
  46624. const S_ATTRIB_VALUE = 39; // <a foo=
  46625. const S_ATTRIB_VALUE_QUOTED = 40; // <a foo="bar
  46626. const S_ATTRIB_VALUE_CLOSED = 41; // <a foo="bar"
  46627. const S_ATTRIB_VALUE_UNQUOTED = 42; // <a foo=bar
  46628. const S_CLOSE_TAG = 43; // </a
  46629. const S_CLOSE_TAG_SAW_WHITE = 44; // </a >
  46630. const TAB = 9;
  46631. const NL = 0xA;
  46632. const CR = 0xD;
  46633. const SPACE = 0x20;
  46634. const BANG = 0x21;
  46635. const DQUOTE = 0x22;
  46636. const AMP = 0x26;
  46637. const SQUOTE = 0x27;
  46638. const MINUS = 0x2D;
  46639. const FORWARD_SLASH = 0x2F;
  46640. const SEMICOLON = 0x3B;
  46641. const LESS = 0x3C;
  46642. const EQUAL = 0x3D;
  46643. const GREATER = 0x3E;
  46644. const QUESTION = 0x3F;
  46645. const OPEN_BRACKET = 0x5B;
  46646. const CLOSE_BRACKET = 0x5D;
  46647. const NEL = 0x85;
  46648. const LS = 0x2028; // Line Separator
  46649. const isQuote = c => c === DQUOTE || c === SQUOTE;
  46650. const QUOTES = [DQUOTE, SQUOTE];
  46651. const DOCTYPE_TERMINATOR = [...QUOTES, OPEN_BRACKET, GREATER];
  46652. const DTD_TERMINATOR = [...QUOTES, LESS, CLOSE_BRACKET];
  46653. const XML_DECL_NAME_TERMINATOR = [EQUAL, QUESTION, ...S_LIST];
  46654. const ATTRIB_VALUE_UNQUOTED_TERMINATOR = [...S_LIST, GREATER, AMP, LESS];
  46655. function nsPairCheck(parser, prefix, uri) {
  46656. switch (prefix) {
  46657. case "xml":
  46658. if (uri !== XML_NAMESPACE) {
  46659. parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);
  46660. }
  46661. break;
  46662. case "xmlns":
  46663. if (uri !== XMLNS_NAMESPACE) {
  46664. parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`);
  46665. }
  46666. break;
  46667. default:
  46668. }
  46669. switch (uri) {
  46670. case XMLNS_NAMESPACE:
  46671. parser.fail(prefix === "" ? `the default namespace may not be set to ${uri}.` : `may not assign a prefix (even "xmlns") to the URI \
  46672. ${XMLNS_NAMESPACE}.`);
  46673. break;
  46674. case XML_NAMESPACE:
  46675. switch (prefix) {
  46676. case "xml":
  46677. // Assinging the XML namespace to "xml" is fine.
  46678. break;
  46679. case "":
  46680. parser.fail(`the default namespace may not be set to ${uri}.`);
  46681. break;
  46682. default:
  46683. parser.fail("may not assign the xml namespace to another prefix.");
  46684. }
  46685. break;
  46686. default:
  46687. }
  46688. }
  46689. function nsMappingCheck(parser, mapping) {
  46690. for (const local of Object.keys(mapping)) {
  46691. nsPairCheck(parser, local, mapping[local]);
  46692. }
  46693. }
  46694. const isNCName = name => NC_NAME_RE.test(name);
  46695. const isName = name => NAME_RE.test(name);
  46696. const FORBIDDEN_START = 0;
  46697. const FORBIDDEN_BRACKET = 1;
  46698. const FORBIDDEN_BRACKET_BRACKET = 2;
  46699. /**
  46700. * The list of supported events.
  46701. */
  46702. exports.EVENTS = ["xmldecl", "text", "processinginstruction", "doctype", "comment", "opentagstart", "attribute", "opentag", "closetag", "cdata", "error", "end", "ready"];
  46703. const EVENT_NAME_TO_HANDLER_NAME = {
  46704. xmldecl: "xmldeclHandler",
  46705. text: "textHandler",
  46706. processinginstruction: "piHandler",
  46707. doctype: "doctypeHandler",
  46708. comment: "commentHandler",
  46709. opentagstart: "openTagStartHandler",
  46710. attribute: "attributeHandler",
  46711. opentag: "openTagHandler",
  46712. closetag: "closeTagHandler",
  46713. cdata: "cdataHandler",
  46714. error: "errorHandler",
  46715. end: "endHandler",
  46716. ready: "readyHandler"
  46717. };
  46718. class SaxesParser {
  46719. /**
  46720. * @param opt The parser options.
  46721. */
  46722. constructor(opt) {
  46723. this.opt = opt !== null && opt !== void 0 ? opt : {};
  46724. this.fragmentOpt = !!this.opt.fragment;
  46725. const xmlnsOpt = this.xmlnsOpt = !!this.opt.xmlns;
  46726. this.trackPosition = this.opt.position !== false;
  46727. this.fileName = this.opt.fileName;
  46728. if (xmlnsOpt) {
  46729. // This is the function we use to perform name checks on PIs and entities.
  46730. // When namespaces are used, colons are not allowed in PI target names or
  46731. // entity names. So the check depends on whether namespaces are used. See:
  46732. //
  46733. // https://www.w3.org/XML/xml-names-19990114-errata.html
  46734. // NE08
  46735. //
  46736. this.nameStartCheck = isNCNameStartChar;
  46737. this.nameCheck = isNCNameChar;
  46738. this.isName = isNCName;
  46739. // eslint-disable-next-line @typescript-eslint/unbound-method
  46740. this.processAttribs = this.processAttribsNS;
  46741. // eslint-disable-next-line @typescript-eslint/unbound-method
  46742. this.pushAttrib = this.pushAttribNS;
  46743. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  46744. this.ns = Object.assign({
  46745. __proto__: null
  46746. }, rootNS);
  46747. const additional = this.opt.additionalNamespaces;
  46748. if (additional != null) {
  46749. nsMappingCheck(this, additional);
  46750. Object.assign(this.ns, additional);
  46751. }
  46752. } else {
  46753. this.nameStartCheck = isNameStartChar;
  46754. this.nameCheck = isNameChar;
  46755. this.isName = isName;
  46756. // eslint-disable-next-line @typescript-eslint/unbound-method
  46757. this.processAttribs = this.processAttribsPlain;
  46758. // eslint-disable-next-line @typescript-eslint/unbound-method
  46759. this.pushAttrib = this.pushAttribPlain;
  46760. }
  46761. //
  46762. // The order of the members in this table needs to correspond to the state
  46763. // numbers given to the states that correspond to the methods being recorded
  46764. // here.
  46765. //
  46766. this.stateTable = [/* eslint-disable @typescript-eslint/unbound-method */
  46767. this.sBegin, this.sBeginWhitespace, this.sDoctype, this.sDoctypeQuote, this.sDTD, this.sDTDQuoted, this.sDTDOpenWaka, this.sDTDOpenWakaBang, this.sDTDComment, this.sDTDCommentEnding, this.sDTDCommentEnded, this.sDTDPI, this.sDTDPIEnding, this.sText, this.sEntity, this.sOpenWaka, this.sOpenWakaBang, this.sComment, this.sCommentEnding, this.sCommentEnded, this.sCData, this.sCDataEnding, this.sCDataEnding2, this.sPIFirstChar, this.sPIRest, this.sPIBody, this.sPIEnding, this.sXMLDeclNameStart, this.sXMLDeclName, this.sXMLDeclEq, this.sXMLDeclValueStart, this.sXMLDeclValue, this.sXMLDeclSeparator, this.sXMLDeclEnding, this.sOpenTag, this.sOpenTagSlash, this.sAttrib, this.sAttribName, this.sAttribNameSawWhite, this.sAttribValue, this.sAttribValueQuoted, this.sAttribValueClosed, this.sAttribValueUnquoted, this.sCloseTag, this.sCloseTagSawWhite];
  46768. this._init();
  46769. }
  46770. /**
  46771. * Indicates whether or not the parser is closed. If ``true``, wait for
  46772. * the ``ready`` event to write again.
  46773. */
  46774. get closed() {
  46775. return this._closed;
  46776. }
  46777. _init() {
  46778. var _a;
  46779. this.openWakaBang = "";
  46780. this.text = "";
  46781. this.name = "";
  46782. this.piTarget = "";
  46783. this.entity = "";
  46784. this.q = null;
  46785. this.tags = [];
  46786. this.tag = null;
  46787. this.topNS = null;
  46788. this.chunk = "";
  46789. this.chunkPosition = 0;
  46790. this.i = 0;
  46791. this.prevI = 0;
  46792. this.carriedFromPrevious = undefined;
  46793. this.forbiddenState = FORBIDDEN_START;
  46794. this.attribList = [];
  46795. // The logic is organized so as to minimize the need to check
  46796. // this.opt.fragment while parsing.
  46797. const {
  46798. fragmentOpt
  46799. } = this;
  46800. this.state = fragmentOpt ? S_TEXT : S_BEGIN;
  46801. // We want these to be all true if we are dealing with a fragment.
  46802. this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot = this.sawRoot = fragmentOpt;
  46803. // An XML declaration is intially possible only when parsing whole
  46804. // documents.
  46805. this.xmlDeclPossible = !fragmentOpt;
  46806. this.xmlDeclExpects = ["version"];
  46807. this.entityReturnState = undefined;
  46808. let {
  46809. defaultXMLVersion
  46810. } = this.opt;
  46811. if (defaultXMLVersion === undefined) {
  46812. if (this.opt.forceXMLVersion === true) {
  46813. throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
  46814. }
  46815. defaultXMLVersion = "1.0";
  46816. }
  46817. this.setXMLVersion(defaultXMLVersion);
  46818. this.positionAtNewLine = 0;
  46819. this.doctype = false;
  46820. this._closed = false;
  46821. this.xmlDecl = {
  46822. version: undefined,
  46823. encoding: undefined,
  46824. standalone: undefined
  46825. };
  46826. this.line = 1;
  46827. this.column = 0;
  46828. this.ENTITIES = Object.create(XML_ENTITIES);
  46829. // eslint-disable-next-line no-unused-expressions
  46830. (_a = this.readyHandler) === null || _a === void 0 ? void 0 : _a.call(this);
  46831. }
  46832. /**
  46833. * The stream position the parser is currently looking at. This field is
  46834. * zero-based.
  46835. *
  46836. * This field is not based on counting Unicode characters but is to be
  46837. * interpreted as a plain index into a JavaScript string.
  46838. */
  46839. get position() {
  46840. return this.chunkPosition + this.i;
  46841. }
  46842. /**
  46843. * The column number of the next character to be read by the parser. *
  46844. * This field is zero-based. (The first column in a line is 0.)
  46845. *
  46846. * This field reports the index at which the next character would be in the
  46847. * line if the line were represented as a JavaScript string. Note that this
  46848. * *can* be different to a count based on the number of *Unicode characters*
  46849. * due to how JavaScript handles astral plane characters.
  46850. *
  46851. * See [[column]] for a number that corresponds to a count of Unicode
  46852. * characters.
  46853. */
  46854. get columnIndex() {
  46855. return this.position - this.positionAtNewLine;
  46856. }
  46857. /**
  46858. * Set an event listener on an event. The parser supports one handler per
  46859. * event type. If you try to set an event handler over an existing handler,
  46860. * the old handler is silently overwritten.
  46861. *
  46862. * @param name The event to listen to.
  46863. *
  46864. * @param handler The handler to set.
  46865. */
  46866. on(name, handler) {
  46867. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  46868. this[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
  46869. }
  46870. /**
  46871. * Unset an event handler.
  46872. *
  46873. * @parma name The event to stop listening to.
  46874. */
  46875. off(name) {
  46876. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  46877. this[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;
  46878. }
  46879. /**
  46880. * Make an error object. The error object will have a message that contains
  46881. * the ``fileName`` option passed at the creation of the parser. If position
  46882. * tracking was turned on, it will also have line and column number
  46883. * information.
  46884. *
  46885. * @param message The message describing the error to report.
  46886. *
  46887. * @returns An error object with a properly formatted message.
  46888. */
  46889. makeError(message) {
  46890. var _a;
  46891. let msg = (_a = this.fileName) !== null && _a !== void 0 ? _a : "";
  46892. if (this.trackPosition) {
  46893. if (msg.length > 0) {
  46894. msg += ":";
  46895. }
  46896. msg += `${this.line}:${this.column}`;
  46897. }
  46898. if (msg.length > 0) {
  46899. msg += ": ";
  46900. }
  46901. return new Error(msg + message);
  46902. }
  46903. /**
  46904. * Report a parsing error. This method is made public so that client code may
  46905. * check for issues that are outside the scope of this project and can report
  46906. * errors.
  46907. *
  46908. * @param message The error to report.
  46909. *
  46910. * @returns this
  46911. */
  46912. fail(message) {
  46913. const err = this.makeError(message);
  46914. const handler = this.errorHandler;
  46915. if (handler === undefined) {
  46916. throw err;
  46917. } else {
  46918. handler(err);
  46919. }
  46920. return this;
  46921. }
  46922. /**
  46923. * Write a XML data to the parser.
  46924. *
  46925. * @param chunk The XML data to write.
  46926. *
  46927. * @returns this
  46928. */
  46929. write(chunk) {
  46930. if (this.closed) {
  46931. return this.fail("cannot write after close; assign an onready handler.");
  46932. }
  46933. let end = false;
  46934. if (chunk === null) {
  46935. // We cannot return immediately because carriedFromPrevious may need
  46936. // processing.
  46937. end = true;
  46938. chunk = "";
  46939. } else if (typeof chunk === "object") {
  46940. chunk = chunk.toString();
  46941. }
  46942. // We checked if performing a pre-decomposition of the string into an array
  46943. // of single complete characters (``Array.from(chunk)``) would be faster
  46944. // than the current repeated calls to ``charCodeAt``. As of August 2018, it
  46945. // isn't. (There may be Node-specific code that would perform faster than
  46946. // ``Array.from`` but don't want to be dependent on Node.)
  46947. if (this.carriedFromPrevious !== undefined) {
  46948. // The previous chunk had char we must carry over.
  46949. chunk = `${this.carriedFromPrevious}${chunk}`;
  46950. this.carriedFromPrevious = undefined;
  46951. }
  46952. let limit = chunk.length;
  46953. const lastCode = chunk.charCodeAt(limit - 1);
  46954. if (!end && (
  46955. // A trailing CR or surrogate must be carried over to the next
  46956. // chunk.
  46957. lastCode === CR || lastCode >= 0xD800 && lastCode <= 0xDBFF)) {
  46958. // The chunk ends with a character that must be carried over. We cannot
  46959. // know how to handle it until we get the next chunk or the end of the
  46960. // stream. So save it for later.
  46961. this.carriedFromPrevious = chunk[limit - 1];
  46962. limit--;
  46963. chunk = chunk.slice(0, limit);
  46964. }
  46965. const {
  46966. stateTable
  46967. } = this;
  46968. this.chunk = chunk;
  46969. this.i = 0;
  46970. while (this.i < limit) {
  46971. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  46972. stateTable[this.state].call(this);
  46973. }
  46974. this.chunkPosition += limit;
  46975. return end ? this.end() : this;
  46976. }
  46977. /**
  46978. * Close the current stream. Perform final well-formedness checks and reset
  46979. * the parser tstate.
  46980. *
  46981. * @returns this
  46982. */
  46983. close() {
  46984. return this.write(null);
  46985. }
  46986. /**
  46987. * Get a single code point out of the current chunk. This updates the current
  46988. * position if we do position tracking.
  46989. *
  46990. * This is the algorithm to use for XML 1.0.
  46991. *
  46992. * @returns The character read.
  46993. */
  46994. getCode10() {
  46995. const {
  46996. chunk,
  46997. i
  46998. } = this;
  46999. this.prevI = i;
  47000. // Yes, we do this instead of doing this.i++. Doing it this way, we do not
  47001. // read this.i again, which is a bit faster.
  47002. this.i = i + 1;
  47003. if (i >= chunk.length) {
  47004. return EOC;
  47005. }
  47006. // Using charCodeAt and handling the surrogates ourselves is faster
  47007. // than using codePointAt.
  47008. const code = chunk.charCodeAt(i);
  47009. this.column++;
  47010. if (code < 0xD800) {
  47011. if (code >= SPACE || code === TAB) {
  47012. return code;
  47013. }
  47014. switch (code) {
  47015. case NL:
  47016. this.line++;
  47017. this.column = 0;
  47018. this.positionAtNewLine = this.position;
  47019. return NL;
  47020. case CR:
  47021. // We may get NaN if we read past the end of the chunk, which is fine.
  47022. if (chunk.charCodeAt(i + 1) === NL) {
  47023. // A \r\n sequence is converted to \n so we have to skip over the
  47024. // next character. We already know it has a size of 1 so ++ is fine
  47025. // here.
  47026. this.i = i + 2;
  47027. }
  47028. // Otherwise, a \r is just converted to \n, so we don't have to skip
  47029. // ahead.
  47030. // In either case, \r becomes \n.
  47031. this.line++;
  47032. this.column = 0;
  47033. this.positionAtNewLine = this.position;
  47034. return NL_LIKE;
  47035. default:
  47036. // If we get here, then code < SPACE and it is not NL CR or TAB.
  47037. this.fail("disallowed character.");
  47038. return code;
  47039. }
  47040. }
  47041. if (code > 0xDBFF) {
  47042. // This is a specialized version of isChar10 that takes into account
  47043. // that in this context code > 0xDBFF and code <= 0xFFFF. So it does not
  47044. // test cases that don't need testing.
  47045. if (!(code >= 0xE000 && code <= 0xFFFD)) {
  47046. this.fail("disallowed character.");
  47047. }
  47048. return code;
  47049. }
  47050. const final = 0x10000 + (code - 0xD800) * 0x400 + (chunk.charCodeAt(i + 1) - 0xDC00);
  47051. this.i = i + 2;
  47052. // This is a specialized version of isChar10 that takes into account that in
  47053. // this context necessarily final >= 0x10000.
  47054. if (final > 0x10FFFF) {
  47055. this.fail("disallowed character.");
  47056. }
  47057. return final;
  47058. }
  47059. /**
  47060. * Get a single code point out of the current chunk. This updates the current
  47061. * position if we do position tracking.
  47062. *
  47063. * This is the algorithm to use for XML 1.1.
  47064. *
  47065. * @returns {number} The character read.
  47066. */
  47067. getCode11() {
  47068. const {
  47069. chunk,
  47070. i
  47071. } = this;
  47072. this.prevI = i;
  47073. // Yes, we do this instead of doing this.i++. Doing it this way, we do not
  47074. // read this.i again, which is a bit faster.
  47075. this.i = i + 1;
  47076. if (i >= chunk.length) {
  47077. return EOC;
  47078. }
  47079. // Using charCodeAt and handling the surrogates ourselves is faster
  47080. // than using codePointAt.
  47081. const code = chunk.charCodeAt(i);
  47082. this.column++;
  47083. if (code < 0xD800) {
  47084. if (code > 0x1F && code < 0x7F || code > 0x9F && code !== LS || code === TAB) {
  47085. return code;
  47086. }
  47087. switch (code) {
  47088. case NL:
  47089. // 0xA
  47090. this.line++;
  47091. this.column = 0;
  47092. this.positionAtNewLine = this.position;
  47093. return NL;
  47094. case CR:
  47095. {
  47096. // 0xD
  47097. // We may get NaN if we read past the end of the chunk, which is
  47098. // fine.
  47099. const next = chunk.charCodeAt(i + 1);
  47100. if (next === NL || next === NEL) {
  47101. // A CR NL or CR NEL sequence is converted to NL so we have to skip
  47102. // over the next character. We already know it has a size of 1.
  47103. this.i = i + 2;
  47104. }
  47105. // Otherwise, a CR is just converted to NL, no skip.
  47106. }
  47107. /* yes, fall through */
  47108. case NEL: // 0x85
  47109. case LS:
  47110. // Ox2028
  47111. this.line++;
  47112. this.column = 0;
  47113. this.positionAtNewLine = this.position;
  47114. return NL_LIKE;
  47115. default:
  47116. this.fail("disallowed character.");
  47117. return code;
  47118. }
  47119. }
  47120. if (code > 0xDBFF) {
  47121. // This is a specialized version of isCharAndNotRestricted that takes into
  47122. // account that in this context code > 0xDBFF and code <= 0xFFFF. So it
  47123. // does not test cases that don't need testing.
  47124. if (!(code >= 0xE000 && code <= 0xFFFD)) {
  47125. this.fail("disallowed character.");
  47126. }
  47127. return code;
  47128. }
  47129. const final = 0x10000 + (code - 0xD800) * 0x400 + (chunk.charCodeAt(i + 1) - 0xDC00);
  47130. this.i = i + 2;
  47131. // This is a specialized version of isCharAndNotRestricted that takes into
  47132. // account that in this context necessarily final >= 0x10000.
  47133. if (final > 0x10FFFF) {
  47134. this.fail("disallowed character.");
  47135. }
  47136. return final;
  47137. }
  47138. /**
  47139. * Like ``getCode`` but with the return value normalized so that ``NL`` is
  47140. * returned for ``NL_LIKE``.
  47141. */
  47142. getCodeNorm() {
  47143. const c = this.getCode();
  47144. return c === NL_LIKE ? NL : c;
  47145. }
  47146. unget() {
  47147. this.i = this.prevI;
  47148. this.column--;
  47149. }
  47150. /**
  47151. * Capture characters into a buffer until encountering one of a set of
  47152. * characters.
  47153. *
  47154. * @param chars An array of codepoints. Encountering a character in the array
  47155. * ends the capture. (``chars`` may safely contain ``NL``.)
  47156. *
  47157. * @return The character code that made the capture end, or ``EOC`` if we hit
  47158. * the end of the chunk. The return value cannot be NL_LIKE: NL is returned
  47159. * instead.
  47160. */
  47161. captureTo(chars) {
  47162. let {
  47163. i: start
  47164. } = this;
  47165. const {
  47166. chunk
  47167. } = this;
  47168. // eslint-disable-next-line no-constant-condition
  47169. while (true) {
  47170. const c = this.getCode();
  47171. const isNLLike = c === NL_LIKE;
  47172. const final = isNLLike ? NL : c;
  47173. if (final === EOC || chars.includes(final)) {
  47174. this.text += chunk.slice(start, this.prevI);
  47175. return final;
  47176. }
  47177. if (isNLLike) {
  47178. this.text += `${chunk.slice(start, this.prevI)}\n`;
  47179. start = this.i;
  47180. }
  47181. }
  47182. }
  47183. /**
  47184. * Capture characters into a buffer until encountering a character.
  47185. *
  47186. * @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
  47187. * CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
  47188. *
  47189. * @return ``true`` if we ran into the character. Otherwise, we ran into the
  47190. * end of the current chunk.
  47191. */
  47192. captureToChar(char) {
  47193. let {
  47194. i: start
  47195. } = this;
  47196. const {
  47197. chunk
  47198. } = this;
  47199. // eslint-disable-next-line no-constant-condition
  47200. while (true) {
  47201. let c = this.getCode();
  47202. switch (c) {
  47203. case NL_LIKE:
  47204. this.text += `${chunk.slice(start, this.prevI)}\n`;
  47205. start = this.i;
  47206. c = NL;
  47207. break;
  47208. case EOC:
  47209. this.text += chunk.slice(start);
  47210. return false;
  47211. default:
  47212. }
  47213. if (c === char) {
  47214. this.text += chunk.slice(start, this.prevI);
  47215. return true;
  47216. }
  47217. }
  47218. }
  47219. /**
  47220. * Capture characters that satisfy ``isNameChar`` into the ``name`` field of
  47221. * this parser.
  47222. *
  47223. * @return The character code that made the test fail, or ``EOC`` if we hit
  47224. * the end of the chunk. The return value cannot be NL_LIKE: NL is returned
  47225. * instead.
  47226. */
  47227. captureNameChars() {
  47228. const {
  47229. chunk,
  47230. i: start
  47231. } = this;
  47232. // eslint-disable-next-line no-constant-condition
  47233. while (true) {
  47234. const c = this.getCode();
  47235. if (c === EOC) {
  47236. this.name += chunk.slice(start);
  47237. return EOC;
  47238. }
  47239. // NL is not a name char so we don't have to test specifically for it.
  47240. if (!isNameChar(c)) {
  47241. this.name += chunk.slice(start, this.prevI);
  47242. return c === NL_LIKE ? NL : c;
  47243. }
  47244. }
  47245. }
  47246. /**
  47247. * Skip white spaces.
  47248. *
  47249. * @return The character that ended the skip, or ``EOC`` if we hit
  47250. * the end of the chunk. The return value cannot be NL_LIKE: NL is returned
  47251. * instead.
  47252. */
  47253. skipSpaces() {
  47254. // eslint-disable-next-line no-constant-condition
  47255. while (true) {
  47256. const c = this.getCodeNorm();
  47257. if (c === EOC || !isS(c)) {
  47258. return c;
  47259. }
  47260. }
  47261. }
  47262. setXMLVersion(version) {
  47263. this.currentXMLVersion = version;
  47264. /* eslint-disable @typescript-eslint/unbound-method */
  47265. if (version === "1.0") {
  47266. this.isChar = isChar10;
  47267. this.getCode = this.getCode10;
  47268. } else {
  47269. this.isChar = isChar11;
  47270. this.getCode = this.getCode11;
  47271. }
  47272. /* eslint-enable @typescript-eslint/unbound-method */
  47273. }
  47274. // STATE ENGINE METHODS
  47275. // This needs to be a state separate from S_BEGIN_WHITESPACE because we want
  47276. // to be sure never to come back to this state later.
  47277. sBegin() {
  47278. // We are essentially peeking at the first character of the chunk. Since
  47279. // S_BEGIN can be in effect only when we start working on the first chunk,
  47280. // the index at which we must look is necessarily 0. Note also that the
  47281. // following test does not depend on decoding surrogates.
  47282. // If the initial character is 0xFEFF, ignore it.
  47283. if (this.chunk.charCodeAt(0) === 0xFEFF) {
  47284. this.i++;
  47285. this.column++;
  47286. }
  47287. this.state = S_BEGIN_WHITESPACE;
  47288. }
  47289. sBeginWhitespace() {
  47290. // We need to know whether we've encountered spaces or not because as soon
  47291. // as we run into a space, an XML declaration is no longer possible. Rather
  47292. // than slow down skipSpaces even in places where we don't care whether it
  47293. // skipped anything or not, we check whether prevI is equal to the value of
  47294. // i from before we skip spaces.
  47295. const iBefore = this.i;
  47296. const c = this.skipSpaces();
  47297. if (this.prevI !== iBefore) {
  47298. this.xmlDeclPossible = false;
  47299. }
  47300. switch (c) {
  47301. case LESS:
  47302. this.state = S_OPEN_WAKA;
  47303. // We could naively call closeText but in this state, it is not normal
  47304. // to have text be filled with any data.
  47305. if (this.text.length !== 0) {
  47306. throw new Error("no-empty text at start");
  47307. }
  47308. break;
  47309. case EOC:
  47310. break;
  47311. default:
  47312. this.unget();
  47313. this.state = S_TEXT;
  47314. this.xmlDeclPossible = false;
  47315. }
  47316. }
  47317. sDoctype() {
  47318. var _a;
  47319. const c = this.captureTo(DOCTYPE_TERMINATOR);
  47320. switch (c) {
  47321. case GREATER:
  47322. {
  47323. // eslint-disable-next-line no-unused-expressions
  47324. (_a = this.doctypeHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.text);
  47325. this.text = "";
  47326. this.state = S_TEXT;
  47327. this.doctype = true; // just remember that we saw it.
  47328. break;
  47329. }
  47330. case EOC:
  47331. break;
  47332. default:
  47333. this.text += String.fromCodePoint(c);
  47334. if (c === OPEN_BRACKET) {
  47335. this.state = S_DTD;
  47336. } else if (isQuote(c)) {
  47337. this.state = S_DOCTYPE_QUOTE;
  47338. this.q = c;
  47339. }
  47340. }
  47341. }
  47342. sDoctypeQuote() {
  47343. const q = this.q;
  47344. if (this.captureToChar(q)) {
  47345. this.text += String.fromCodePoint(q);
  47346. this.q = null;
  47347. this.state = S_DOCTYPE;
  47348. }
  47349. }
  47350. sDTD() {
  47351. const c = this.captureTo(DTD_TERMINATOR);
  47352. if (c === EOC) {
  47353. return;
  47354. }
  47355. this.text += String.fromCodePoint(c);
  47356. if (c === CLOSE_BRACKET) {
  47357. this.state = S_DOCTYPE;
  47358. } else if (c === LESS) {
  47359. this.state = S_DTD_OPEN_WAKA;
  47360. } else if (isQuote(c)) {
  47361. this.state = S_DTD_QUOTED;
  47362. this.q = c;
  47363. }
  47364. }
  47365. sDTDQuoted() {
  47366. const q = this.q;
  47367. if (this.captureToChar(q)) {
  47368. this.text += String.fromCodePoint(q);
  47369. this.state = S_DTD;
  47370. this.q = null;
  47371. }
  47372. }
  47373. sDTDOpenWaka() {
  47374. const c = this.getCodeNorm();
  47375. this.text += String.fromCodePoint(c);
  47376. switch (c) {
  47377. case BANG:
  47378. this.state = S_DTD_OPEN_WAKA_BANG;
  47379. this.openWakaBang = "";
  47380. break;
  47381. case QUESTION:
  47382. this.state = S_DTD_PI;
  47383. break;
  47384. default:
  47385. this.state = S_DTD;
  47386. }
  47387. }
  47388. sDTDOpenWakaBang() {
  47389. const char = String.fromCodePoint(this.getCodeNorm());
  47390. const owb = this.openWakaBang += char;
  47391. this.text += char;
  47392. if (owb !== "-") {
  47393. this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
  47394. this.openWakaBang = "";
  47395. }
  47396. }
  47397. sDTDComment() {
  47398. if (this.captureToChar(MINUS)) {
  47399. this.text += "-";
  47400. this.state = S_DTD_COMMENT_ENDING;
  47401. }
  47402. }
  47403. sDTDCommentEnding() {
  47404. const c = this.getCodeNorm();
  47405. this.text += String.fromCodePoint(c);
  47406. this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
  47407. }
  47408. sDTDCommentEnded() {
  47409. const c = this.getCodeNorm();
  47410. this.text += String.fromCodePoint(c);
  47411. if (c === GREATER) {
  47412. this.state = S_DTD;
  47413. } else {
  47414. this.fail("malformed comment.");
  47415. // <!-- blah -- bloo --> will be recorded as
  47416. // a comment of " blah -- bloo "
  47417. this.state = S_DTD_COMMENT;
  47418. }
  47419. }
  47420. sDTDPI() {
  47421. if (this.captureToChar(QUESTION)) {
  47422. this.text += "?";
  47423. this.state = S_DTD_PI_ENDING;
  47424. }
  47425. }
  47426. sDTDPIEnding() {
  47427. const c = this.getCodeNorm();
  47428. this.text += String.fromCodePoint(c);
  47429. if (c === GREATER) {
  47430. this.state = S_DTD;
  47431. }
  47432. }
  47433. sText() {
  47434. //
  47435. // We did try a version of saxes where the S_TEXT state was split in two
  47436. // states: one for text inside the root element, and one for text
  47437. // outside. This was avoiding having to test this.tags.length to decide
  47438. // what implementation to actually use.
  47439. //
  47440. // Peformance testing on gigabyte-size files did not show any advantage to
  47441. // using the two states solution instead of the current one. Conversely, it
  47442. // made the code a bit more complicated elsewhere. For instance, a comment
  47443. // can appear before the root element so when a comment ended it was
  47444. // necessary to determine whether to return to the S_TEXT state or to the
  47445. // new text-outside-root state.
  47446. //
  47447. if (this.tags.length !== 0) {
  47448. this.handleTextInRoot();
  47449. } else {
  47450. this.handleTextOutsideRoot();
  47451. }
  47452. }
  47453. sEntity() {
  47454. // This is essentially a specialized version of captureToChar(SEMICOLON...)
  47455. let {
  47456. i: start
  47457. } = this;
  47458. const {
  47459. chunk
  47460. } = this;
  47461. // eslint-disable-next-line no-labels, no-restricted-syntax
  47462. loop:
  47463. // eslint-disable-next-line no-constant-condition
  47464. while (true) {
  47465. switch (this.getCode()) {
  47466. case NL_LIKE:
  47467. this.entity += `${chunk.slice(start, this.prevI)}\n`;
  47468. start = this.i;
  47469. break;
  47470. case SEMICOLON:
  47471. {
  47472. const {
  47473. entityReturnState
  47474. } = this;
  47475. const entity = this.entity + chunk.slice(start, this.prevI);
  47476. this.state = entityReturnState;
  47477. let parsed;
  47478. if (entity === "") {
  47479. this.fail("empty entity name.");
  47480. parsed = "&;";
  47481. } else {
  47482. parsed = this.parseEntity(entity);
  47483. this.entity = "";
  47484. }
  47485. if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {
  47486. this.text += parsed;
  47487. }
  47488. // eslint-disable-next-line no-labels
  47489. break loop;
  47490. }
  47491. case EOC:
  47492. this.entity += chunk.slice(start);
  47493. // eslint-disable-next-line no-labels
  47494. break loop;
  47495. default:
  47496. }
  47497. }
  47498. }
  47499. sOpenWaka() {
  47500. // Reminder: a state handler is called with at least one character
  47501. // available in the current chunk. So the first call to get code inside of
  47502. // a state handler cannot return ``EOC``. That's why we don't test
  47503. // for it.
  47504. const c = this.getCode();
  47505. // either a /, ?, !, or text is coming next.
  47506. if (isNameStartChar(c)) {
  47507. this.state = S_OPEN_TAG;
  47508. this.unget();
  47509. this.xmlDeclPossible = false;
  47510. } else {
  47511. switch (c) {
  47512. case FORWARD_SLASH:
  47513. this.state = S_CLOSE_TAG;
  47514. this.xmlDeclPossible = false;
  47515. break;
  47516. case BANG:
  47517. this.state = S_OPEN_WAKA_BANG;
  47518. this.openWakaBang = "";
  47519. this.xmlDeclPossible = false;
  47520. break;
  47521. case QUESTION:
  47522. this.state = S_PI_FIRST_CHAR;
  47523. break;
  47524. default:
  47525. this.fail("disallowed character in tag name");
  47526. this.state = S_TEXT;
  47527. this.xmlDeclPossible = false;
  47528. }
  47529. }
  47530. }
  47531. sOpenWakaBang() {
  47532. this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
  47533. switch (this.openWakaBang) {
  47534. case "[CDATA[":
  47535. if (!this.sawRoot && !this.reportedTextBeforeRoot) {
  47536. this.fail("text data outside of root node.");
  47537. this.reportedTextBeforeRoot = true;
  47538. }
  47539. if (this.closedRoot && !this.reportedTextAfterRoot) {
  47540. this.fail("text data outside of root node.");
  47541. this.reportedTextAfterRoot = true;
  47542. }
  47543. this.state = S_CDATA;
  47544. this.openWakaBang = "";
  47545. break;
  47546. case "--":
  47547. this.state = S_COMMENT;
  47548. this.openWakaBang = "";
  47549. break;
  47550. case "DOCTYPE":
  47551. this.state = S_DOCTYPE;
  47552. if (this.doctype || this.sawRoot) {
  47553. this.fail("inappropriately located doctype declaration.");
  47554. }
  47555. this.openWakaBang = "";
  47556. break;
  47557. default:
  47558. // 7 happens to be the maximum length of the string that can possibly
  47559. // match one of the cases above.
  47560. if (this.openWakaBang.length >= 7) {
  47561. this.fail("incorrect syntax.");
  47562. }
  47563. }
  47564. }
  47565. sComment() {
  47566. if (this.captureToChar(MINUS)) {
  47567. this.state = S_COMMENT_ENDING;
  47568. }
  47569. }
  47570. sCommentEnding() {
  47571. var _a;
  47572. const c = this.getCodeNorm();
  47573. if (c === MINUS) {
  47574. this.state = S_COMMENT_ENDED;
  47575. // eslint-disable-next-line no-unused-expressions
  47576. (_a = this.commentHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.text);
  47577. this.text = "";
  47578. } else {
  47579. this.text += `-${String.fromCodePoint(c)}`;
  47580. this.state = S_COMMENT;
  47581. }
  47582. }
  47583. sCommentEnded() {
  47584. const c = this.getCodeNorm();
  47585. if (c !== GREATER) {
  47586. this.fail("malformed comment.");
  47587. // <!-- blah -- bloo --> will be recorded as
  47588. // a comment of " blah -- bloo "
  47589. this.text += `--${String.fromCodePoint(c)}`;
  47590. this.state = S_COMMENT;
  47591. } else {
  47592. this.state = S_TEXT;
  47593. }
  47594. }
  47595. sCData() {
  47596. if (this.captureToChar(CLOSE_BRACKET)) {
  47597. this.state = S_CDATA_ENDING;
  47598. }
  47599. }
  47600. sCDataEnding() {
  47601. const c = this.getCodeNorm();
  47602. if (c === CLOSE_BRACKET) {
  47603. this.state = S_CDATA_ENDING_2;
  47604. } else {
  47605. this.text += `]${String.fromCodePoint(c)}`;
  47606. this.state = S_CDATA;
  47607. }
  47608. }
  47609. sCDataEnding2() {
  47610. var _a;
  47611. const c = this.getCodeNorm();
  47612. switch (c) {
  47613. case GREATER:
  47614. {
  47615. // eslint-disable-next-line no-unused-expressions
  47616. (_a = this.cdataHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.text);
  47617. this.text = "";
  47618. this.state = S_TEXT;
  47619. break;
  47620. }
  47621. case CLOSE_BRACKET:
  47622. this.text += "]";
  47623. break;
  47624. default:
  47625. this.text += `]]${String.fromCodePoint(c)}`;
  47626. this.state = S_CDATA;
  47627. }
  47628. }
  47629. // We need this separate state to check the first character fo the pi target
  47630. // with this.nameStartCheck which allows less characters than this.nameCheck.
  47631. sPIFirstChar() {
  47632. const c = this.getCodeNorm();
  47633. // This is first because in the case where the file is well-formed this is
  47634. // the branch taken. We optimize for well-formedness.
  47635. if (this.nameStartCheck(c)) {
  47636. this.piTarget += String.fromCodePoint(c);
  47637. this.state = S_PI_REST;
  47638. } else if (c === QUESTION || isS(c)) {
  47639. this.fail("processing instruction without a target.");
  47640. this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
  47641. } else {
  47642. this.fail("disallowed character in processing instruction name.");
  47643. this.piTarget += String.fromCodePoint(c);
  47644. this.state = S_PI_REST;
  47645. }
  47646. }
  47647. sPIRest() {
  47648. // Capture characters into a piTarget while ``this.nameCheck`` run on the
  47649. // character read returns true.
  47650. const {
  47651. chunk,
  47652. i: start
  47653. } = this;
  47654. // eslint-disable-next-line no-constant-condition
  47655. while (true) {
  47656. const c = this.getCodeNorm();
  47657. if (c === EOC) {
  47658. this.piTarget += chunk.slice(start);
  47659. return;
  47660. }
  47661. // NL cannot satisfy this.nameCheck so we don't have to test specifically
  47662. // for it.
  47663. if (!this.nameCheck(c)) {
  47664. this.piTarget += chunk.slice(start, this.prevI);
  47665. const isQuestion = c === QUESTION;
  47666. if (isQuestion || isS(c)) {
  47667. if (this.piTarget === "xml") {
  47668. if (!this.xmlDeclPossible) {
  47669. this.fail("an XML declaration must be at the start of the document.");
  47670. }
  47671. this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
  47672. } else {
  47673. this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
  47674. }
  47675. } else {
  47676. this.fail("disallowed character in processing instruction name.");
  47677. this.piTarget += String.fromCodePoint(c);
  47678. }
  47679. break;
  47680. }
  47681. }
  47682. }
  47683. sPIBody() {
  47684. if (this.text.length === 0) {
  47685. const c = this.getCodeNorm();
  47686. if (c === QUESTION) {
  47687. this.state = S_PI_ENDING;
  47688. } else if (!isS(c)) {
  47689. this.text = String.fromCodePoint(c);
  47690. }
  47691. }
  47692. // The question mark character is not valid inside any of the XML
  47693. // declaration name/value pairs.
  47694. else if (this.captureToChar(QUESTION)) {
  47695. this.state = S_PI_ENDING;
  47696. }
  47697. }
  47698. sPIEnding() {
  47699. var _a;
  47700. const c = this.getCodeNorm();
  47701. if (c === GREATER) {
  47702. const {
  47703. piTarget
  47704. } = this;
  47705. if (piTarget.toLowerCase() === "xml") {
  47706. this.fail("the XML declaration must appear at the start of the document.");
  47707. }
  47708. // eslint-disable-next-line no-unused-expressions
  47709. (_a = this.piHandler) === null || _a === void 0 ? void 0 : _a.call(this, {
  47710. target: piTarget,
  47711. body: this.text
  47712. });
  47713. this.piTarget = this.text = "";
  47714. this.state = S_TEXT;
  47715. } else if (c === QUESTION) {
  47716. // We ran into ?? as part of a processing instruction. We initially took
  47717. // the first ? as a sign that the PI was ending, but it is not. So we have
  47718. // to add it to the body but we take the new ? as a sign that the PI is
  47719. // ending.
  47720. this.text += "?";
  47721. } else {
  47722. this.text += `?${String.fromCodePoint(c)}`;
  47723. this.state = S_PI_BODY;
  47724. }
  47725. this.xmlDeclPossible = false;
  47726. }
  47727. sXMLDeclNameStart() {
  47728. const c = this.skipSpaces();
  47729. // The question mark character is not valid inside any of the XML
  47730. // declaration name/value pairs.
  47731. if (c === QUESTION) {
  47732. // It is valid to go to S_XML_DECL_ENDING from this state.
  47733. this.state = S_XML_DECL_ENDING;
  47734. return;
  47735. }
  47736. if (c !== EOC) {
  47737. this.state = S_XML_DECL_NAME;
  47738. this.name = String.fromCodePoint(c);
  47739. }
  47740. }
  47741. sXMLDeclName() {
  47742. const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
  47743. // The question mark character is not valid inside any of the XML
  47744. // declaration name/value pairs.
  47745. if (c === QUESTION) {
  47746. this.state = S_XML_DECL_ENDING;
  47747. this.name += this.text;
  47748. this.text = "";
  47749. this.fail("XML declaration is incomplete.");
  47750. return;
  47751. }
  47752. if (!(isS(c) || c === EQUAL)) {
  47753. return;
  47754. }
  47755. this.name += this.text;
  47756. this.text = "";
  47757. if (!this.xmlDeclExpects.includes(this.name)) {
  47758. switch (this.name.length) {
  47759. case 0:
  47760. this.fail("did not expect any more name/value pairs.");
  47761. break;
  47762. case 1:
  47763. this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
  47764. break;
  47765. default:
  47766. this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
  47767. }
  47768. }
  47769. this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
  47770. }
  47771. sXMLDeclEq() {
  47772. const c = this.getCodeNorm();
  47773. // The question mark character is not valid inside any of the XML
  47774. // declaration name/value pairs.
  47775. if (c === QUESTION) {
  47776. this.state = S_XML_DECL_ENDING;
  47777. this.fail("XML declaration is incomplete.");
  47778. return;
  47779. }
  47780. if (isS(c)) {
  47781. return;
  47782. }
  47783. if (c !== EQUAL) {
  47784. this.fail("value required.");
  47785. }
  47786. this.state = S_XML_DECL_VALUE_START;
  47787. }
  47788. sXMLDeclValueStart() {
  47789. const c = this.getCodeNorm();
  47790. // The question mark character is not valid inside any of the XML
  47791. // declaration name/value pairs.
  47792. if (c === QUESTION) {
  47793. this.state = S_XML_DECL_ENDING;
  47794. this.fail("XML declaration is incomplete.");
  47795. return;
  47796. }
  47797. if (isS(c)) {
  47798. return;
  47799. }
  47800. if (!isQuote(c)) {
  47801. this.fail("value must be quoted.");
  47802. this.q = SPACE;
  47803. } else {
  47804. this.q = c;
  47805. }
  47806. this.state = S_XML_DECL_VALUE;
  47807. }
  47808. sXMLDeclValue() {
  47809. const c = this.captureTo([this.q, QUESTION]);
  47810. // The question mark character is not valid inside any of the XML
  47811. // declaration name/value pairs.
  47812. if (c === QUESTION) {
  47813. this.state = S_XML_DECL_ENDING;
  47814. this.text = "";
  47815. this.fail("XML declaration is incomplete.");
  47816. return;
  47817. }
  47818. if (c === EOC) {
  47819. return;
  47820. }
  47821. const value = this.text;
  47822. this.text = "";
  47823. switch (this.name) {
  47824. case "version":
  47825. {
  47826. this.xmlDeclExpects = ["encoding", "standalone"];
  47827. const version = value;
  47828. this.xmlDecl.version = version;
  47829. // This is the test specified by XML 1.0 but it is fine for XML 1.1.
  47830. if (!/^1\.[0-9]+$/.test(version)) {
  47831. this.fail("version number must match /^1\\.[0-9]+$/.");
  47832. }
  47833. // When forceXMLVersion is set, the XML declaration is ignored.
  47834. else if (!this.opt.forceXMLVersion) {
  47835. this.setXMLVersion(version);
  47836. }
  47837. break;
  47838. }
  47839. case "encoding":
  47840. if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {
  47841. this.fail("encoding value must match \
  47842. /^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
  47843. }
  47844. this.xmlDeclExpects = ["standalone"];
  47845. this.xmlDecl.encoding = value;
  47846. break;
  47847. case "standalone":
  47848. if (value !== "yes" && value !== "no") {
  47849. this.fail("standalone value must match \"yes\" or \"no\".");
  47850. }
  47851. this.xmlDeclExpects = [];
  47852. this.xmlDecl.standalone = value;
  47853. break;
  47854. default:
  47855. // We don't need to raise an error here since we've already raised one
  47856. // when checking what name was expected.
  47857. }
  47858. this.name = "";
  47859. this.state = S_XML_DECL_SEPARATOR;
  47860. }
  47861. sXMLDeclSeparator() {
  47862. const c = this.getCodeNorm();
  47863. // The question mark character is not valid inside any of the XML
  47864. // declaration name/value pairs.
  47865. if (c === QUESTION) {
  47866. // It is valid to go to S_XML_DECL_ENDING from this state.
  47867. this.state = S_XML_DECL_ENDING;
  47868. return;
  47869. }
  47870. if (!isS(c)) {
  47871. this.fail("whitespace required.");
  47872. this.unget();
  47873. }
  47874. this.state = S_XML_DECL_NAME_START;
  47875. }
  47876. sXMLDeclEnding() {
  47877. var _a;
  47878. const c = this.getCodeNorm();
  47879. if (c === GREATER) {
  47880. if (this.piTarget !== "xml") {
  47881. this.fail("processing instructions are not allowed before root.");
  47882. } else if (this.name !== "version" && this.xmlDeclExpects.includes("version")) {
  47883. this.fail("XML declaration must contain a version.");
  47884. }
  47885. // eslint-disable-next-line no-unused-expressions
  47886. (_a = this.xmldeclHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.xmlDecl);
  47887. this.name = "";
  47888. this.piTarget = this.text = "";
  47889. this.state = S_TEXT;
  47890. } else {
  47891. // We got here because the previous character was a ?, but the question
  47892. // mark character is not valid inside any of the XML declaration
  47893. // name/value pairs.
  47894. this.fail("The character ? is disallowed anywhere in XML declarations.");
  47895. }
  47896. this.xmlDeclPossible = false;
  47897. }
  47898. sOpenTag() {
  47899. var _a;
  47900. const c = this.captureNameChars();
  47901. if (c === EOC) {
  47902. return;
  47903. }
  47904. const tag = this.tag = {
  47905. name: this.name,
  47906. attributes: Object.create(null)
  47907. };
  47908. this.name = "";
  47909. if (this.xmlnsOpt) {
  47910. this.topNS = tag.ns = Object.create(null);
  47911. }
  47912. // eslint-disable-next-line no-unused-expressions
  47913. (_a = this.openTagStartHandler) === null || _a === void 0 ? void 0 : _a.call(this, tag);
  47914. this.sawRoot = true;
  47915. if (!this.fragmentOpt && this.closedRoot) {
  47916. this.fail("documents may contain only one root.");
  47917. }
  47918. switch (c) {
  47919. case GREATER:
  47920. this.openTag();
  47921. break;
  47922. case FORWARD_SLASH:
  47923. this.state = S_OPEN_TAG_SLASH;
  47924. break;
  47925. default:
  47926. if (!isS(c)) {
  47927. this.fail("disallowed character in tag name.");
  47928. }
  47929. this.state = S_ATTRIB;
  47930. }
  47931. }
  47932. sOpenTagSlash() {
  47933. if (this.getCode() === GREATER) {
  47934. this.openSelfClosingTag();
  47935. } else {
  47936. this.fail("forward-slash in opening tag not followed by >.");
  47937. this.state = S_ATTRIB;
  47938. }
  47939. }
  47940. sAttrib() {
  47941. const c = this.skipSpaces();
  47942. if (c === EOC) {
  47943. return;
  47944. }
  47945. if (isNameStartChar(c)) {
  47946. this.unget();
  47947. this.state = S_ATTRIB_NAME;
  47948. } else if (c === GREATER) {
  47949. this.openTag();
  47950. } else if (c === FORWARD_SLASH) {
  47951. this.state = S_OPEN_TAG_SLASH;
  47952. } else {
  47953. this.fail("disallowed character in attribute name.");
  47954. }
  47955. }
  47956. sAttribName() {
  47957. const c = this.captureNameChars();
  47958. if (c === EQUAL) {
  47959. this.state = S_ATTRIB_VALUE;
  47960. } else if (isS(c)) {
  47961. this.state = S_ATTRIB_NAME_SAW_WHITE;
  47962. } else if (c === GREATER) {
  47963. this.fail("attribute without value.");
  47964. this.pushAttrib(this.name, this.name);
  47965. this.name = this.text = "";
  47966. this.openTag();
  47967. } else if (c !== EOC) {
  47968. this.fail("disallowed character in attribute name.");
  47969. }
  47970. }
  47971. sAttribNameSawWhite() {
  47972. const c = this.skipSpaces();
  47973. switch (c) {
  47974. case EOC:
  47975. return;
  47976. case EQUAL:
  47977. this.state = S_ATTRIB_VALUE;
  47978. break;
  47979. default:
  47980. this.fail("attribute without value.");
  47981. // Should we do this???
  47982. // this.tag.attributes[this.name] = "";
  47983. this.text = "";
  47984. this.name = "";
  47985. if (c === GREATER) {
  47986. this.openTag();
  47987. } else if (isNameStartChar(c)) {
  47988. this.unget();
  47989. this.state = S_ATTRIB_NAME;
  47990. } else {
  47991. this.fail("disallowed character in attribute name.");
  47992. this.state = S_ATTRIB;
  47993. }
  47994. }
  47995. }
  47996. sAttribValue() {
  47997. const c = this.getCodeNorm();
  47998. if (isQuote(c)) {
  47999. this.q = c;
  48000. this.state = S_ATTRIB_VALUE_QUOTED;
  48001. } else if (!isS(c)) {
  48002. this.fail("unquoted attribute value.");
  48003. this.state = S_ATTRIB_VALUE_UNQUOTED;
  48004. this.unget();
  48005. }
  48006. }
  48007. sAttribValueQuoted() {
  48008. // We deliberately do not use captureTo here. The specialized code we use
  48009. // here is faster than using captureTo.
  48010. const {
  48011. q,
  48012. chunk
  48013. } = this;
  48014. let {
  48015. i: start
  48016. } = this;
  48017. // eslint-disable-next-line no-constant-condition
  48018. while (true) {
  48019. switch (this.getCode()) {
  48020. case q:
  48021. this.pushAttrib(this.name, this.text + chunk.slice(start, this.prevI));
  48022. this.name = this.text = "";
  48023. this.q = null;
  48024. this.state = S_ATTRIB_VALUE_CLOSED;
  48025. return;
  48026. case AMP:
  48027. this.text += chunk.slice(start, this.prevI);
  48028. this.state = S_ENTITY;
  48029. this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
  48030. return;
  48031. case NL:
  48032. case NL_LIKE:
  48033. case TAB:
  48034. this.text += `${chunk.slice(start, this.prevI)} `;
  48035. start = this.i;
  48036. break;
  48037. case LESS:
  48038. this.text += chunk.slice(start, this.prevI);
  48039. this.fail("disallowed character.");
  48040. return;
  48041. case EOC:
  48042. this.text += chunk.slice(start);
  48043. return;
  48044. default:
  48045. }
  48046. }
  48047. }
  48048. sAttribValueClosed() {
  48049. const c = this.getCodeNorm();
  48050. if (isS(c)) {
  48051. this.state = S_ATTRIB;
  48052. } else if (c === GREATER) {
  48053. this.openTag();
  48054. } else if (c === FORWARD_SLASH) {
  48055. this.state = S_OPEN_TAG_SLASH;
  48056. } else if (isNameStartChar(c)) {
  48057. this.fail("no whitespace between attributes.");
  48058. this.unget();
  48059. this.state = S_ATTRIB_NAME;
  48060. } else {
  48061. this.fail("disallowed character in attribute name.");
  48062. }
  48063. }
  48064. sAttribValueUnquoted() {
  48065. // We don't do anything regarding EOL or space handling for unquoted
  48066. // attributes. We already have failed by the time we get here, and the
  48067. // contract that saxes upholds states that upon failure, it is not safe to
  48068. // rely on the data passed to event handlers (other than
  48069. // ``onerror``). Passing "bad" data is not a problem.
  48070. const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
  48071. switch (c) {
  48072. case AMP:
  48073. this.state = S_ENTITY;
  48074. this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
  48075. break;
  48076. case LESS:
  48077. this.fail("disallowed character.");
  48078. break;
  48079. case EOC:
  48080. break;
  48081. default:
  48082. if (this.text.includes("]]>")) {
  48083. this.fail("the string \"]]>\" is disallowed in char data.");
  48084. }
  48085. this.pushAttrib(this.name, this.text);
  48086. this.name = this.text = "";
  48087. if (c === GREATER) {
  48088. this.openTag();
  48089. } else {
  48090. this.state = S_ATTRIB;
  48091. }
  48092. }
  48093. }
  48094. sCloseTag() {
  48095. const c = this.captureNameChars();
  48096. if (c === GREATER) {
  48097. this.closeTag();
  48098. } else if (isS(c)) {
  48099. this.state = S_CLOSE_TAG_SAW_WHITE;
  48100. } else if (c !== EOC) {
  48101. this.fail("disallowed character in closing tag.");
  48102. }
  48103. }
  48104. sCloseTagSawWhite() {
  48105. switch (this.skipSpaces()) {
  48106. case GREATER:
  48107. this.closeTag();
  48108. break;
  48109. case EOC:
  48110. break;
  48111. default:
  48112. this.fail("disallowed character in closing tag.");
  48113. }
  48114. }
  48115. // END OF STATE ENGINE METHODS
  48116. handleTextInRoot() {
  48117. // This is essentially a specialized version of captureTo which is optimized
  48118. // for performing the ]]> check. A previous version of this code, checked
  48119. // ``this.text`` for the presence of ]]>. It simplified the code but was
  48120. // very costly when character data contained a lot of entities to be parsed.
  48121. //
  48122. // Since we are using a specialized loop, we also keep track of the presence
  48123. // of ]]> in text data. The sequence ]]> is forbidden to appear as-is.
  48124. //
  48125. let {
  48126. i: start,
  48127. forbiddenState
  48128. } = this;
  48129. const {
  48130. chunk,
  48131. textHandler: handler
  48132. } = this;
  48133. // eslint-disable-next-line no-labels, no-restricted-syntax
  48134. scanLoop:
  48135. // eslint-disable-next-line no-constant-condition
  48136. while (true) {
  48137. switch (this.getCode()) {
  48138. case LESS:
  48139. {
  48140. this.state = S_OPEN_WAKA;
  48141. if (handler !== undefined) {
  48142. const {
  48143. text
  48144. } = this;
  48145. const slice = chunk.slice(start, this.prevI);
  48146. if (text.length !== 0) {
  48147. handler(text + slice);
  48148. this.text = "";
  48149. } else if (slice.length !== 0) {
  48150. handler(slice);
  48151. }
  48152. }
  48153. forbiddenState = FORBIDDEN_START;
  48154. // eslint-disable-next-line no-labels
  48155. break scanLoop;
  48156. }
  48157. case AMP:
  48158. this.state = S_ENTITY;
  48159. this.entityReturnState = S_TEXT;
  48160. if (handler !== undefined) {
  48161. this.text += chunk.slice(start, this.prevI);
  48162. }
  48163. forbiddenState = FORBIDDEN_START;
  48164. // eslint-disable-next-line no-labels
  48165. break scanLoop;
  48166. case CLOSE_BRACKET:
  48167. switch (forbiddenState) {
  48168. case FORBIDDEN_START:
  48169. forbiddenState = FORBIDDEN_BRACKET;
  48170. break;
  48171. case FORBIDDEN_BRACKET:
  48172. forbiddenState = FORBIDDEN_BRACKET_BRACKET;
  48173. break;
  48174. case FORBIDDEN_BRACKET_BRACKET:
  48175. break;
  48176. default:
  48177. throw new Error("impossible state");
  48178. }
  48179. break;
  48180. case GREATER:
  48181. if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {
  48182. this.fail("the string \"]]>\" is disallowed in char data.");
  48183. }
  48184. forbiddenState = FORBIDDEN_START;
  48185. break;
  48186. case NL_LIKE:
  48187. if (handler !== undefined) {
  48188. this.text += `${chunk.slice(start, this.prevI)}\n`;
  48189. }
  48190. start = this.i;
  48191. forbiddenState = FORBIDDEN_START;
  48192. break;
  48193. case EOC:
  48194. if (handler !== undefined) {
  48195. this.text += chunk.slice(start);
  48196. }
  48197. // eslint-disable-next-line no-labels
  48198. break scanLoop;
  48199. default:
  48200. forbiddenState = FORBIDDEN_START;
  48201. }
  48202. }
  48203. this.forbiddenState = forbiddenState;
  48204. }
  48205. handleTextOutsideRoot() {
  48206. // This is essentially a specialized version of captureTo which is optimized
  48207. // for a specialized task. We keep track of the presence of non-space
  48208. // characters in the text since these are errors when appearing outside the
  48209. // document root element.
  48210. let {
  48211. i: start
  48212. } = this;
  48213. const {
  48214. chunk,
  48215. textHandler: handler
  48216. } = this;
  48217. let nonSpace = false;
  48218. // eslint-disable-next-line no-labels, no-restricted-syntax
  48219. outRootLoop:
  48220. // eslint-disable-next-line no-constant-condition
  48221. while (true) {
  48222. const code = this.getCode();
  48223. switch (code) {
  48224. case LESS:
  48225. {
  48226. this.state = S_OPEN_WAKA;
  48227. if (handler !== undefined) {
  48228. const {
  48229. text
  48230. } = this;
  48231. const slice = chunk.slice(start, this.prevI);
  48232. if (text.length !== 0) {
  48233. handler(text + slice);
  48234. this.text = "";
  48235. } else if (slice.length !== 0) {
  48236. handler(slice);
  48237. }
  48238. }
  48239. // eslint-disable-next-line no-labels
  48240. break outRootLoop;
  48241. }
  48242. case AMP:
  48243. this.state = S_ENTITY;
  48244. this.entityReturnState = S_TEXT;
  48245. if (handler !== undefined) {
  48246. this.text += chunk.slice(start, this.prevI);
  48247. }
  48248. nonSpace = true;
  48249. // eslint-disable-next-line no-labels
  48250. break outRootLoop;
  48251. case NL_LIKE:
  48252. if (handler !== undefined) {
  48253. this.text += `${chunk.slice(start, this.prevI)}\n`;
  48254. }
  48255. start = this.i;
  48256. break;
  48257. case EOC:
  48258. if (handler !== undefined) {
  48259. this.text += chunk.slice(start);
  48260. }
  48261. // eslint-disable-next-line no-labels
  48262. break outRootLoop;
  48263. default:
  48264. if (!isS(code)) {
  48265. nonSpace = true;
  48266. }
  48267. }
  48268. }
  48269. if (!nonSpace) {
  48270. return;
  48271. }
  48272. // We use the reportedTextBeforeRoot and reportedTextAfterRoot flags
  48273. // to avoid reporting errors for every single character that is out of
  48274. // place.
  48275. if (!this.sawRoot && !this.reportedTextBeforeRoot) {
  48276. this.fail("text data outside of root node.");
  48277. this.reportedTextBeforeRoot = true;
  48278. }
  48279. if (this.closedRoot && !this.reportedTextAfterRoot) {
  48280. this.fail("text data outside of root node.");
  48281. this.reportedTextAfterRoot = true;
  48282. }
  48283. }
  48284. pushAttribNS(name, value) {
  48285. var _a;
  48286. const {
  48287. prefix,
  48288. local
  48289. } = this.qname(name);
  48290. const attr = {
  48291. name,
  48292. prefix,
  48293. local,
  48294. value
  48295. };
  48296. this.attribList.push(attr);
  48297. // eslint-disable-next-line no-unused-expressions
  48298. (_a = this.attributeHandler) === null || _a === void 0 ? void 0 : _a.call(this, attr);
  48299. if (prefix === "xmlns") {
  48300. const trimmed = value.trim();
  48301. if (this.currentXMLVersion === "1.0" && trimmed === "") {
  48302. this.fail("invalid attempt to undefine prefix in XML 1.0");
  48303. }
  48304. this.topNS[local] = trimmed;
  48305. nsPairCheck(this, local, trimmed);
  48306. } else if (name === "xmlns") {
  48307. const trimmed = value.trim();
  48308. this.topNS[""] = trimmed;
  48309. nsPairCheck(this, "", trimmed);
  48310. }
  48311. }
  48312. pushAttribPlain(name, value) {
  48313. var _a;
  48314. const attr = {
  48315. name,
  48316. value
  48317. };
  48318. this.attribList.push(attr);
  48319. // eslint-disable-next-line no-unused-expressions
  48320. (_a = this.attributeHandler) === null || _a === void 0 ? void 0 : _a.call(this, attr);
  48321. }
  48322. /**
  48323. * End parsing. This performs final well-formedness checks and resets the
  48324. * parser to a clean state.
  48325. *
  48326. * @returns this
  48327. */
  48328. end() {
  48329. var _a, _b;
  48330. if (!this.sawRoot) {
  48331. this.fail("document must contain a root element.");
  48332. }
  48333. const {
  48334. tags
  48335. } = this;
  48336. while (tags.length > 0) {
  48337. const tag = tags.pop();
  48338. this.fail(`unclosed tag: ${tag.name}`);
  48339. }
  48340. if (this.state !== S_BEGIN && this.state !== S_TEXT) {
  48341. this.fail("unexpected end.");
  48342. }
  48343. const {
  48344. text
  48345. } = this;
  48346. if (text.length !== 0) {
  48347. // eslint-disable-next-line no-unused-expressions
  48348. (_a = this.textHandler) === null || _a === void 0 ? void 0 : _a.call(this, text);
  48349. this.text = "";
  48350. }
  48351. this._closed = true;
  48352. // eslint-disable-next-line no-unused-expressions
  48353. (_b = this.endHandler) === null || _b === void 0 ? void 0 : _b.call(this);
  48354. this._init();
  48355. return this;
  48356. }
  48357. /**
  48358. * Resolve a namespace prefix.
  48359. *
  48360. * @param prefix The prefix to resolve.
  48361. *
  48362. * @returns The namespace URI or ``undefined`` if the prefix is not defined.
  48363. */
  48364. resolve(prefix) {
  48365. var _a, _b;
  48366. let uri = this.topNS[prefix];
  48367. if (uri !== undefined) {
  48368. return uri;
  48369. }
  48370. const {
  48371. tags
  48372. } = this;
  48373. for (let index = tags.length - 1; index >= 0; index--) {
  48374. uri = tags[index].ns[prefix];
  48375. if (uri !== undefined) {
  48376. return uri;
  48377. }
  48378. }
  48379. uri = this.ns[prefix];
  48380. if (uri !== undefined) {
  48381. return uri;
  48382. }
  48383. return (_b = (_a = this.opt).resolvePrefix) === null || _b === void 0 ? void 0 : _b.call(_a, prefix);
  48384. }
  48385. /**
  48386. * Parse a qname into its prefix and local name parts.
  48387. *
  48388. * @param name The name to parse
  48389. *
  48390. * @returns
  48391. */
  48392. qname(name) {
  48393. // This is faster than using name.split(":").
  48394. const colon = name.indexOf(":");
  48395. if (colon === -1) {
  48396. return {
  48397. prefix: "",
  48398. local: name
  48399. };
  48400. }
  48401. const local = name.slice(colon + 1);
  48402. const prefix = name.slice(0, colon);
  48403. if (prefix === "" || local === "" || local.includes(":")) {
  48404. this.fail(`malformed name: ${name}.`);
  48405. }
  48406. return {
  48407. prefix,
  48408. local
  48409. };
  48410. }
  48411. processAttribsNS() {
  48412. var _a;
  48413. const {
  48414. attribList
  48415. } = this;
  48416. const tag = this.tag;
  48417. {
  48418. // add namespace info to tag
  48419. const {
  48420. prefix,
  48421. local
  48422. } = this.qname(tag.name);
  48423. tag.prefix = prefix;
  48424. tag.local = local;
  48425. const uri = tag.uri = (_a = this.resolve(prefix)) !== null && _a !== void 0 ? _a : "";
  48426. if (prefix !== "") {
  48427. if (prefix === "xmlns") {
  48428. this.fail("tags may not have \"xmlns\" as prefix.");
  48429. }
  48430. if (uri === "") {
  48431. this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
  48432. tag.uri = prefix;
  48433. }
  48434. }
  48435. }
  48436. if (attribList.length === 0) {
  48437. return;
  48438. }
  48439. const {
  48440. attributes
  48441. } = tag;
  48442. const seen = new Set();
  48443. // Note: do not apply default ns to attributes:
  48444. // http://www.w3.org/TR/REC-xml-names/#defaulting
  48445. for (const attr of attribList) {
  48446. const {
  48447. name,
  48448. prefix,
  48449. local
  48450. } = attr;
  48451. let uri;
  48452. let eqname;
  48453. if (prefix === "") {
  48454. uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
  48455. eqname = name;
  48456. } else {
  48457. uri = this.resolve(prefix);
  48458. // if there's any attributes with an undefined namespace,
  48459. // then fail on them now.
  48460. if (uri === undefined) {
  48461. this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
  48462. uri = prefix;
  48463. }
  48464. eqname = `{${uri}}${local}`;
  48465. }
  48466. if (seen.has(eqname)) {
  48467. this.fail(`duplicate attribute: ${eqname}.`);
  48468. }
  48469. seen.add(eqname);
  48470. attr.uri = uri;
  48471. attributes[name] = attr;
  48472. }
  48473. this.attribList = [];
  48474. }
  48475. processAttribsPlain() {
  48476. const {
  48477. attribList
  48478. } = this;
  48479. // eslint-disable-next-line prefer-destructuring
  48480. const attributes = this.tag.attributes;
  48481. for (const {
  48482. name,
  48483. value
  48484. } of attribList) {
  48485. if (attributes[name] !== undefined) {
  48486. this.fail(`duplicate attribute: ${name}.`);
  48487. }
  48488. attributes[name] = value;
  48489. }
  48490. this.attribList = [];
  48491. }
  48492. /**
  48493. * Handle a complete open tag. This parser code calls this once it has seen
  48494. * the whole tag. This method checks for well-formeness and then emits
  48495. * ``onopentag``.
  48496. */
  48497. openTag() {
  48498. var _a;
  48499. this.processAttribs();
  48500. const {
  48501. tags
  48502. } = this;
  48503. const tag = this.tag;
  48504. tag.isSelfClosing = false;
  48505. // There cannot be any pending text here due to the onopentagstart that was
  48506. // necessarily emitted before we get here. So we do not check text.
  48507. // eslint-disable-next-line no-unused-expressions
  48508. (_a = this.openTagHandler) === null || _a === void 0 ? void 0 : _a.call(this, tag);
  48509. tags.push(tag);
  48510. this.state = S_TEXT;
  48511. this.name = "";
  48512. }
  48513. /**
  48514. * Handle a complete self-closing tag. This parser code calls this once it has
  48515. * seen the whole tag. This method checks for well-formeness and then emits
  48516. * ``onopentag`` and ``onclosetag``.
  48517. */
  48518. openSelfClosingTag() {
  48519. var _a, _b, _c;
  48520. this.processAttribs();
  48521. const {
  48522. tags
  48523. } = this;
  48524. const tag = this.tag;
  48525. tag.isSelfClosing = true;
  48526. // There cannot be any pending text here due to the onopentagstart that was
  48527. // necessarily emitted before we get here. So we do not check text.
  48528. // eslint-disable-next-line no-unused-expressions
  48529. (_a = this.openTagHandler) === null || _a === void 0 ? void 0 : _a.call(this, tag);
  48530. // eslint-disable-next-line no-unused-expressions
  48531. (_b = this.closeTagHandler) === null || _b === void 0 ? void 0 : _b.call(this, tag);
  48532. const top = this.tag = (_c = tags[tags.length - 1]) !== null && _c !== void 0 ? _c : null;
  48533. if (top === null) {
  48534. this.closedRoot = true;
  48535. }
  48536. this.state = S_TEXT;
  48537. this.name = "";
  48538. }
  48539. /**
  48540. * Handle a complete close tag. This parser code calls this once it has seen
  48541. * the whole tag. This method checks for well-formeness and then emits
  48542. * ``onclosetag``.
  48543. */
  48544. closeTag() {
  48545. const {
  48546. tags,
  48547. name
  48548. } = this;
  48549. // Our state after this will be S_TEXT, no matter what, and we can clear
  48550. // tagName now.
  48551. this.state = S_TEXT;
  48552. this.name = "";
  48553. if (name === "") {
  48554. this.fail("weird empty close tag.");
  48555. this.text += "</>";
  48556. return;
  48557. }
  48558. const handler = this.closeTagHandler;
  48559. let l = tags.length;
  48560. while (l-- > 0) {
  48561. const tag = this.tag = tags.pop();
  48562. this.topNS = tag.ns;
  48563. // eslint-disable-next-line no-unused-expressions
  48564. handler === null || handler === void 0 ? void 0 : handler(tag);
  48565. if (tag.name === name) {
  48566. break;
  48567. }
  48568. this.fail("unexpected close tag.");
  48569. }
  48570. if (l === 0) {
  48571. this.closedRoot = true;
  48572. } else if (l < 0) {
  48573. this.fail(`unmatched closing tag: ${name}.`);
  48574. this.text += `</${name}>`;
  48575. }
  48576. }
  48577. /**
  48578. * Resolves an entity. Makes any necessary well-formedness checks.
  48579. *
  48580. * @param entity The entity to resolve.
  48581. *
  48582. * @returns The parsed entity.
  48583. */
  48584. parseEntity(entity) {
  48585. // startsWith would be significantly slower for this test.
  48586. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
  48587. if (entity[0] !== "#") {
  48588. const defined = this.ENTITIES[entity];
  48589. if (defined !== undefined) {
  48590. return defined;
  48591. }
  48592. this.fail(this.isName(entity) ? "undefined entity." : "disallowed character in entity name.");
  48593. return `&${entity};`;
  48594. }
  48595. let num = NaN;
  48596. if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) {
  48597. num = parseInt(entity.slice(2), 16);
  48598. } else if (/^#[0-9]+$/.test(entity)) {
  48599. num = parseInt(entity.slice(1), 10);
  48600. }
  48601. // The character reference is required to match the CHAR production.
  48602. if (!this.isChar(num)) {
  48603. this.fail("malformed character entity.");
  48604. return `&${entity};`;
  48605. }
  48606. return String.fromCodePoint(num);
  48607. }
  48608. }
  48609. exports.SaxesParser = SaxesParser;
  48610. },{"xmlchars/xml/1.0/ed5":381,"xmlchars/xml/1.1/ed2":382,"xmlchars/xmlns/1.0/ed3":383}],335:[function(require,module,exports){
  48611. "use strict";
  48612. var Buffer = require('safe-buffer').Buffer;
  48613. // prototype class for hash functions
  48614. function Hash(blockSize, finalSize) {
  48615. this._block = Buffer.alloc(blockSize);
  48616. this._finalSize = finalSize;
  48617. this._blockSize = blockSize;
  48618. this._len = 0;
  48619. }
  48620. Hash.prototype.update = function (data, enc) {
  48621. if (typeof data === 'string') {
  48622. enc = enc || 'utf8';
  48623. data = Buffer.from(data, enc);
  48624. }
  48625. var block = this._block;
  48626. var blockSize = this._blockSize;
  48627. var length = data.length;
  48628. var accum = this._len;
  48629. for (var offset = 0; offset < length;) {
  48630. var assigned = accum % blockSize;
  48631. var remainder = Math.min(length - offset, blockSize - assigned);
  48632. for (var i = 0; i < remainder; i++) {
  48633. block[assigned + i] = data[offset + i];
  48634. }
  48635. accum += remainder;
  48636. offset += remainder;
  48637. if (accum % blockSize === 0) {
  48638. this._update(block);
  48639. }
  48640. }
  48641. this._len += length;
  48642. return this;
  48643. };
  48644. Hash.prototype.digest = function (enc) {
  48645. var rem = this._len % this._blockSize;
  48646. this._block[rem] = 0x80;
  48647. // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
  48648. // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
  48649. this._block.fill(0, rem + 1);
  48650. if (rem >= this._finalSize) {
  48651. this._update(this._block);
  48652. this._block.fill(0);
  48653. }
  48654. var bits = this._len * 8;
  48655. // uint32
  48656. if (bits <= 0xffffffff) {
  48657. this._block.writeUInt32BE(bits, this._blockSize - 4);
  48658. // uint64
  48659. } else {
  48660. var lowBits = (bits & 0xffffffff) >>> 0;
  48661. var highBits = (bits - lowBits) / 0x100000000;
  48662. this._block.writeUInt32BE(highBits, this._blockSize - 8);
  48663. this._block.writeUInt32BE(lowBits, this._blockSize - 4);
  48664. }
  48665. this._update(this._block);
  48666. var hash = this._hash();
  48667. return enc ? hash.toString(enc) : hash;
  48668. };
  48669. Hash.prototype._update = function () {
  48670. throw new Error('_update must be implemented by subclass');
  48671. };
  48672. module.exports = Hash;
  48673. },{"safe-buffer":332}],336:[function(require,module,exports){
  48674. "use strict";
  48675. var _exports = module.exports = function SHA(algorithm) {
  48676. algorithm = algorithm.toLowerCase();
  48677. var Algorithm = _exports[algorithm];
  48678. if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)');
  48679. return new Algorithm();
  48680. };
  48681. _exports.sha = require('./sha');
  48682. _exports.sha1 = require('./sha1');
  48683. _exports.sha224 = require('./sha224');
  48684. _exports.sha256 = require('./sha256');
  48685. _exports.sha384 = require('./sha384');
  48686. _exports.sha512 = require('./sha512');
  48687. },{"./sha":337,"./sha1":338,"./sha224":339,"./sha256":340,"./sha384":341,"./sha512":342}],337:[function(require,module,exports){
  48688. "use strict";
  48689. /*
  48690. * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
  48691. * in FIPS PUB 180-1
  48692. * This source code is derived from sha1.js of the same repository.
  48693. * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
  48694. * operation was added.
  48695. */
  48696. var inherits = require('inherits');
  48697. var Hash = require('./hash');
  48698. var Buffer = require('safe-buffer').Buffer;
  48699. var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0];
  48700. var W = new Array(80);
  48701. function Sha() {
  48702. this.init();
  48703. this._w = W;
  48704. Hash.call(this, 64, 56);
  48705. }
  48706. inherits(Sha, Hash);
  48707. Sha.prototype.init = function () {
  48708. this._a = 0x67452301;
  48709. this._b = 0xefcdab89;
  48710. this._c = 0x98badcfe;
  48711. this._d = 0x10325476;
  48712. this._e = 0xc3d2e1f0;
  48713. return this;
  48714. };
  48715. function rotl5(num) {
  48716. return num << 5 | num >>> 27;
  48717. }
  48718. function rotl30(num) {
  48719. return num << 30 | num >>> 2;
  48720. }
  48721. function ft(s, b, c, d) {
  48722. if (s === 0) return b & c | ~b & d;
  48723. if (s === 2) return b & c | b & d | c & d;
  48724. return b ^ c ^ d;
  48725. }
  48726. Sha.prototype._update = function (M) {
  48727. var W = this._w;
  48728. var a = this._a | 0;
  48729. var b = this._b | 0;
  48730. var c = this._c | 0;
  48731. var d = this._d | 0;
  48732. var e = this._e | 0;
  48733. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4);
  48734. for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
  48735. for (var j = 0; j < 80; ++j) {
  48736. var s = ~~(j / 20);
  48737. var t = rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s] | 0;
  48738. e = d;
  48739. d = c;
  48740. c = rotl30(b);
  48741. b = a;
  48742. a = t;
  48743. }
  48744. this._a = a + this._a | 0;
  48745. this._b = b + this._b | 0;
  48746. this._c = c + this._c | 0;
  48747. this._d = d + this._d | 0;
  48748. this._e = e + this._e | 0;
  48749. };
  48750. Sha.prototype._hash = function () {
  48751. var H = Buffer.allocUnsafe(20);
  48752. H.writeInt32BE(this._a | 0, 0);
  48753. H.writeInt32BE(this._b | 0, 4);
  48754. H.writeInt32BE(this._c | 0, 8);
  48755. H.writeInt32BE(this._d | 0, 12);
  48756. H.writeInt32BE(this._e | 0, 16);
  48757. return H;
  48758. };
  48759. module.exports = Sha;
  48760. },{"./hash":335,"inherits":279,"safe-buffer":332}],338:[function(require,module,exports){
  48761. "use strict";
  48762. /*
  48763. * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
  48764. * in FIPS PUB 180-1
  48765. * Version 2.1a Copyright Paul Johnston 2000 - 2002.
  48766. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  48767. * Distributed under the BSD License
  48768. * See http://pajhome.org.uk/crypt/md5 for details.
  48769. */
  48770. var inherits = require('inherits');
  48771. var Hash = require('./hash');
  48772. var Buffer = require('safe-buffer').Buffer;
  48773. var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0];
  48774. var W = new Array(80);
  48775. function Sha1() {
  48776. this.init();
  48777. this._w = W;
  48778. Hash.call(this, 64, 56);
  48779. }
  48780. inherits(Sha1, Hash);
  48781. Sha1.prototype.init = function () {
  48782. this._a = 0x67452301;
  48783. this._b = 0xefcdab89;
  48784. this._c = 0x98badcfe;
  48785. this._d = 0x10325476;
  48786. this._e = 0xc3d2e1f0;
  48787. return this;
  48788. };
  48789. function rotl1(num) {
  48790. return num << 1 | num >>> 31;
  48791. }
  48792. function rotl5(num) {
  48793. return num << 5 | num >>> 27;
  48794. }
  48795. function rotl30(num) {
  48796. return num << 30 | num >>> 2;
  48797. }
  48798. function ft(s, b, c, d) {
  48799. if (s === 0) return b & c | ~b & d;
  48800. if (s === 2) return b & c | b & d | c & d;
  48801. return b ^ c ^ d;
  48802. }
  48803. Sha1.prototype._update = function (M) {
  48804. var W = this._w;
  48805. var a = this._a | 0;
  48806. var b = this._b | 0;
  48807. var c = this._c | 0;
  48808. var d = this._d | 0;
  48809. var e = this._e | 0;
  48810. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4);
  48811. for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]);
  48812. for (var j = 0; j < 80; ++j) {
  48813. var s = ~~(j / 20);
  48814. var t = rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s] | 0;
  48815. e = d;
  48816. d = c;
  48817. c = rotl30(b);
  48818. b = a;
  48819. a = t;
  48820. }
  48821. this._a = a + this._a | 0;
  48822. this._b = b + this._b | 0;
  48823. this._c = c + this._c | 0;
  48824. this._d = d + this._d | 0;
  48825. this._e = e + this._e | 0;
  48826. };
  48827. Sha1.prototype._hash = function () {
  48828. var H = Buffer.allocUnsafe(20);
  48829. H.writeInt32BE(this._a | 0, 0);
  48830. H.writeInt32BE(this._b | 0, 4);
  48831. H.writeInt32BE(this._c | 0, 8);
  48832. H.writeInt32BE(this._d | 0, 12);
  48833. H.writeInt32BE(this._e | 0, 16);
  48834. return H;
  48835. };
  48836. module.exports = Sha1;
  48837. },{"./hash":335,"inherits":279,"safe-buffer":332}],339:[function(require,module,exports){
  48838. "use strict";
  48839. /**
  48840. * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
  48841. * in FIPS 180-2
  48842. * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
  48843. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  48844. *
  48845. */
  48846. var inherits = require('inherits');
  48847. var Sha256 = require('./sha256');
  48848. var Hash = require('./hash');
  48849. var Buffer = require('safe-buffer').Buffer;
  48850. var W = new Array(64);
  48851. function Sha224() {
  48852. this.init();
  48853. this._w = W; // new Array(64)
  48854. Hash.call(this, 64, 56);
  48855. }
  48856. inherits(Sha224, Sha256);
  48857. Sha224.prototype.init = function () {
  48858. this._a = 0xc1059ed8;
  48859. this._b = 0x367cd507;
  48860. this._c = 0x3070dd17;
  48861. this._d = 0xf70e5939;
  48862. this._e = 0xffc00b31;
  48863. this._f = 0x68581511;
  48864. this._g = 0x64f98fa7;
  48865. this._h = 0xbefa4fa4;
  48866. return this;
  48867. };
  48868. Sha224.prototype._hash = function () {
  48869. var H = Buffer.allocUnsafe(28);
  48870. H.writeInt32BE(this._a, 0);
  48871. H.writeInt32BE(this._b, 4);
  48872. H.writeInt32BE(this._c, 8);
  48873. H.writeInt32BE(this._d, 12);
  48874. H.writeInt32BE(this._e, 16);
  48875. H.writeInt32BE(this._f, 20);
  48876. H.writeInt32BE(this._g, 24);
  48877. return H;
  48878. };
  48879. module.exports = Sha224;
  48880. },{"./hash":335,"./sha256":340,"inherits":279,"safe-buffer":332}],340:[function(require,module,exports){
  48881. "use strict";
  48882. /**
  48883. * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
  48884. * in FIPS 180-2
  48885. * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
  48886. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  48887. *
  48888. */
  48889. var inherits = require('inherits');
  48890. var Hash = require('./hash');
  48891. var Buffer = require('safe-buffer').Buffer;
  48892. var K = [0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2];
  48893. var W = new Array(64);
  48894. function Sha256() {
  48895. this.init();
  48896. this._w = W; // new Array(64)
  48897. Hash.call(this, 64, 56);
  48898. }
  48899. inherits(Sha256, Hash);
  48900. Sha256.prototype.init = function () {
  48901. this._a = 0x6a09e667;
  48902. this._b = 0xbb67ae85;
  48903. this._c = 0x3c6ef372;
  48904. this._d = 0xa54ff53a;
  48905. this._e = 0x510e527f;
  48906. this._f = 0x9b05688c;
  48907. this._g = 0x1f83d9ab;
  48908. this._h = 0x5be0cd19;
  48909. return this;
  48910. };
  48911. function ch(x, y, z) {
  48912. return z ^ x & (y ^ z);
  48913. }
  48914. function maj(x, y, z) {
  48915. return x & y | z & (x | y);
  48916. }
  48917. function sigma0(x) {
  48918. return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10);
  48919. }
  48920. function sigma1(x) {
  48921. return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7);
  48922. }
  48923. function gamma0(x) {
  48924. return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ x >>> 3;
  48925. }
  48926. function gamma1(x) {
  48927. return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ x >>> 10;
  48928. }
  48929. Sha256.prototype._update = function (M) {
  48930. var W = this._w;
  48931. var a = this._a | 0;
  48932. var b = this._b | 0;
  48933. var c = this._c | 0;
  48934. var d = this._d | 0;
  48935. var e = this._e | 0;
  48936. var f = this._f | 0;
  48937. var g = this._g | 0;
  48938. var h = this._h | 0;
  48939. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4);
  48940. for (; i < 64; ++i) W[i] = gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16] | 0;
  48941. for (var j = 0; j < 64; ++j) {
  48942. var T1 = h + sigma1(e) + ch(e, f, g) + K[j] + W[j] | 0;
  48943. var T2 = sigma0(a) + maj(a, b, c) | 0;
  48944. h = g;
  48945. g = f;
  48946. f = e;
  48947. e = d + T1 | 0;
  48948. d = c;
  48949. c = b;
  48950. b = a;
  48951. a = T1 + T2 | 0;
  48952. }
  48953. this._a = a + this._a | 0;
  48954. this._b = b + this._b | 0;
  48955. this._c = c + this._c | 0;
  48956. this._d = d + this._d | 0;
  48957. this._e = e + this._e | 0;
  48958. this._f = f + this._f | 0;
  48959. this._g = g + this._g | 0;
  48960. this._h = h + this._h | 0;
  48961. };
  48962. Sha256.prototype._hash = function () {
  48963. var H = Buffer.allocUnsafe(32);
  48964. H.writeInt32BE(this._a, 0);
  48965. H.writeInt32BE(this._b, 4);
  48966. H.writeInt32BE(this._c, 8);
  48967. H.writeInt32BE(this._d, 12);
  48968. H.writeInt32BE(this._e, 16);
  48969. H.writeInt32BE(this._f, 20);
  48970. H.writeInt32BE(this._g, 24);
  48971. H.writeInt32BE(this._h, 28);
  48972. return H;
  48973. };
  48974. module.exports = Sha256;
  48975. },{"./hash":335,"inherits":279,"safe-buffer":332}],341:[function(require,module,exports){
  48976. "use strict";
  48977. var inherits = require('inherits');
  48978. var SHA512 = require('./sha512');
  48979. var Hash = require('./hash');
  48980. var Buffer = require('safe-buffer').Buffer;
  48981. var W = new Array(160);
  48982. function Sha384() {
  48983. this.init();
  48984. this._w = W;
  48985. Hash.call(this, 128, 112);
  48986. }
  48987. inherits(Sha384, SHA512);
  48988. Sha384.prototype.init = function () {
  48989. this._ah = 0xcbbb9d5d;
  48990. this._bh = 0x629a292a;
  48991. this._ch = 0x9159015a;
  48992. this._dh = 0x152fecd8;
  48993. this._eh = 0x67332667;
  48994. this._fh = 0x8eb44a87;
  48995. this._gh = 0xdb0c2e0d;
  48996. this._hh = 0x47b5481d;
  48997. this._al = 0xc1059ed8;
  48998. this._bl = 0x367cd507;
  48999. this._cl = 0x3070dd17;
  49000. this._dl = 0xf70e5939;
  49001. this._el = 0xffc00b31;
  49002. this._fl = 0x68581511;
  49003. this._gl = 0x64f98fa7;
  49004. this._hl = 0xbefa4fa4;
  49005. return this;
  49006. };
  49007. Sha384.prototype._hash = function () {
  49008. var H = Buffer.allocUnsafe(48);
  49009. function writeInt64BE(h, l, offset) {
  49010. H.writeInt32BE(h, offset);
  49011. H.writeInt32BE(l, offset + 4);
  49012. }
  49013. writeInt64BE(this._ah, this._al, 0);
  49014. writeInt64BE(this._bh, this._bl, 8);
  49015. writeInt64BE(this._ch, this._cl, 16);
  49016. writeInt64BE(this._dh, this._dl, 24);
  49017. writeInt64BE(this._eh, this._el, 32);
  49018. writeInt64BE(this._fh, this._fl, 40);
  49019. return H;
  49020. };
  49021. module.exports = Sha384;
  49022. },{"./hash":335,"./sha512":342,"inherits":279,"safe-buffer":332}],342:[function(require,module,exports){
  49023. "use strict";
  49024. var inherits = require('inherits');
  49025. var Hash = require('./hash');
  49026. var Buffer = require('safe-buffer').Buffer;
  49027. var K = [0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817];
  49028. var W = new Array(160);
  49029. function Sha512() {
  49030. this.init();
  49031. this._w = W;
  49032. Hash.call(this, 128, 112);
  49033. }
  49034. inherits(Sha512, Hash);
  49035. Sha512.prototype.init = function () {
  49036. this._ah = 0x6a09e667;
  49037. this._bh = 0xbb67ae85;
  49038. this._ch = 0x3c6ef372;
  49039. this._dh = 0xa54ff53a;
  49040. this._eh = 0x510e527f;
  49041. this._fh = 0x9b05688c;
  49042. this._gh = 0x1f83d9ab;
  49043. this._hh = 0x5be0cd19;
  49044. this._al = 0xf3bcc908;
  49045. this._bl = 0x84caa73b;
  49046. this._cl = 0xfe94f82b;
  49047. this._dl = 0x5f1d36f1;
  49048. this._el = 0xade682d1;
  49049. this._fl = 0x2b3e6c1f;
  49050. this._gl = 0xfb41bd6b;
  49051. this._hl = 0x137e2179;
  49052. return this;
  49053. };
  49054. function Ch(x, y, z) {
  49055. return z ^ x & (y ^ z);
  49056. }
  49057. function maj(x, y, z) {
  49058. return x & y | z & (x | y);
  49059. }
  49060. function sigma0(x, xl) {
  49061. return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25);
  49062. }
  49063. function sigma1(x, xl) {
  49064. return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23);
  49065. }
  49066. function Gamma0(x, xl) {
  49067. return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ x >>> 7;
  49068. }
  49069. function Gamma0l(x, xl) {
  49070. return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25);
  49071. }
  49072. function Gamma1(x, xl) {
  49073. return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ x >>> 6;
  49074. }
  49075. function Gamma1l(x, xl) {
  49076. return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26);
  49077. }
  49078. function getCarry(a, b) {
  49079. return a >>> 0 < b >>> 0 ? 1 : 0;
  49080. }
  49081. Sha512.prototype._update = function (M) {
  49082. var W = this._w;
  49083. var ah = this._ah | 0;
  49084. var bh = this._bh | 0;
  49085. var ch = this._ch | 0;
  49086. var dh = this._dh | 0;
  49087. var eh = this._eh | 0;
  49088. var fh = this._fh | 0;
  49089. var gh = this._gh | 0;
  49090. var hh = this._hh | 0;
  49091. var al = this._al | 0;
  49092. var bl = this._bl | 0;
  49093. var cl = this._cl | 0;
  49094. var dl = this._dl | 0;
  49095. var el = this._el | 0;
  49096. var fl = this._fl | 0;
  49097. var gl = this._gl | 0;
  49098. var hl = this._hl | 0;
  49099. for (var i = 0; i < 32; i += 2) {
  49100. W[i] = M.readInt32BE(i * 4);
  49101. W[i + 1] = M.readInt32BE(i * 4 + 4);
  49102. }
  49103. for (; i < 160; i += 2) {
  49104. var xh = W[i - 15 * 2];
  49105. var xl = W[i - 15 * 2 + 1];
  49106. var gamma0 = Gamma0(xh, xl);
  49107. var gamma0l = Gamma0l(xl, xh);
  49108. xh = W[i - 2 * 2];
  49109. xl = W[i - 2 * 2 + 1];
  49110. var gamma1 = Gamma1(xh, xl);
  49111. var gamma1l = Gamma1l(xl, xh);
  49112. // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
  49113. var Wi7h = W[i - 7 * 2];
  49114. var Wi7l = W[i - 7 * 2 + 1];
  49115. var Wi16h = W[i - 16 * 2];
  49116. var Wi16l = W[i - 16 * 2 + 1];
  49117. var Wil = gamma0l + Wi7l | 0;
  49118. var Wih = gamma0 + Wi7h + getCarry(Wil, gamma0l) | 0;
  49119. Wil = Wil + gamma1l | 0;
  49120. Wih = Wih + gamma1 + getCarry(Wil, gamma1l) | 0;
  49121. Wil = Wil + Wi16l | 0;
  49122. Wih = Wih + Wi16h + getCarry(Wil, Wi16l) | 0;
  49123. W[i] = Wih;
  49124. W[i + 1] = Wil;
  49125. }
  49126. for (var j = 0; j < 160; j += 2) {
  49127. Wih = W[j];
  49128. Wil = W[j + 1];
  49129. var majh = maj(ah, bh, ch);
  49130. var majl = maj(al, bl, cl);
  49131. var sigma0h = sigma0(ah, al);
  49132. var sigma0l = sigma0(al, ah);
  49133. var sigma1h = sigma1(eh, el);
  49134. var sigma1l = sigma1(el, eh);
  49135. // t1 = h + sigma1 + ch + K[j] + W[j]
  49136. var Kih = K[j];
  49137. var Kil = K[j + 1];
  49138. var chh = Ch(eh, fh, gh);
  49139. var chl = Ch(el, fl, gl);
  49140. var t1l = hl + sigma1l | 0;
  49141. var t1h = hh + sigma1h + getCarry(t1l, hl) | 0;
  49142. t1l = t1l + chl | 0;
  49143. t1h = t1h + chh + getCarry(t1l, chl) | 0;
  49144. t1l = t1l + Kil | 0;
  49145. t1h = t1h + Kih + getCarry(t1l, Kil) | 0;
  49146. t1l = t1l + Wil | 0;
  49147. t1h = t1h + Wih + getCarry(t1l, Wil) | 0;
  49148. // t2 = sigma0 + maj
  49149. var t2l = sigma0l + majl | 0;
  49150. var t2h = sigma0h + majh + getCarry(t2l, sigma0l) | 0;
  49151. hh = gh;
  49152. hl = gl;
  49153. gh = fh;
  49154. gl = fl;
  49155. fh = eh;
  49156. fl = el;
  49157. el = dl + t1l | 0;
  49158. eh = dh + t1h + getCarry(el, dl) | 0;
  49159. dh = ch;
  49160. dl = cl;
  49161. ch = bh;
  49162. cl = bl;
  49163. bh = ah;
  49164. bl = al;
  49165. al = t1l + t2l | 0;
  49166. ah = t1h + t2h + getCarry(al, t1l) | 0;
  49167. }
  49168. this._al = this._al + al | 0;
  49169. this._bl = this._bl + bl | 0;
  49170. this._cl = this._cl + cl | 0;
  49171. this._dl = this._dl + dl | 0;
  49172. this._el = this._el + el | 0;
  49173. this._fl = this._fl + fl | 0;
  49174. this._gl = this._gl + gl | 0;
  49175. this._hl = this._hl + hl | 0;
  49176. this._ah = this._ah + ah + getCarry(this._al, al) | 0;
  49177. this._bh = this._bh + bh + getCarry(this._bl, bl) | 0;
  49178. this._ch = this._ch + ch + getCarry(this._cl, cl) | 0;
  49179. this._dh = this._dh + dh + getCarry(this._dl, dl) | 0;
  49180. this._eh = this._eh + eh + getCarry(this._el, el) | 0;
  49181. this._fh = this._fh + fh + getCarry(this._fl, fl) | 0;
  49182. this._gh = this._gh + gh + getCarry(this._gl, gl) | 0;
  49183. this._hh = this._hh + hh + getCarry(this._hl, hl) | 0;
  49184. };
  49185. Sha512.prototype._hash = function () {
  49186. var H = Buffer.allocUnsafe(64);
  49187. function writeInt64BE(h, l, offset) {
  49188. H.writeInt32BE(h, offset);
  49189. H.writeInt32BE(l, offset + 4);
  49190. }
  49191. writeInt64BE(this._ah, this._al, 0);
  49192. writeInt64BE(this._bh, this._bl, 8);
  49193. writeInt64BE(this._ch, this._cl, 16);
  49194. writeInt64BE(this._dh, this._dl, 24);
  49195. writeInt64BE(this._eh, this._el, 32);
  49196. writeInt64BE(this._fh, this._fl, 40);
  49197. writeInt64BE(this._gh, this._gl, 48);
  49198. writeInt64BE(this._hh, this._hl, 56);
  49199. return H;
  49200. };
  49201. module.exports = Sha512;
  49202. },{"./hash":335,"inherits":279,"safe-buffer":332}],343:[function(require,module,exports){
  49203. "use strict";
  49204. // Copyright Joyent, Inc. and other Node contributors.
  49205. //
  49206. // Permission is hereby granted, free of charge, to any person obtaining a
  49207. // copy of this software and associated documentation files (the
  49208. // "Software"), to deal in the Software without restriction, including
  49209. // without limitation the rights to use, copy, modify, merge, publish,
  49210. // distribute, sublicense, and/or sell copies of the Software, and to permit
  49211. // persons to whom the Software is furnished to do so, subject to the
  49212. // following conditions:
  49213. //
  49214. // The above copyright notice and this permission notice shall be included
  49215. // in all copies or substantial portions of the Software.
  49216. //
  49217. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  49218. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  49219. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  49220. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  49221. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  49222. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  49223. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  49224. module.exports = Stream;
  49225. var EE = require('events').EventEmitter;
  49226. var inherits = require('inherits');
  49227. inherits(Stream, EE);
  49228. Stream.Readable = require('readable-stream/readable.js');
  49229. Stream.Writable = require('readable-stream/writable.js');
  49230. Stream.Duplex = require('readable-stream/duplex.js');
  49231. Stream.Transform = require('readable-stream/transform.js');
  49232. Stream.PassThrough = require('readable-stream/passthrough.js');
  49233. // Backwards-compat with node 0.4.x
  49234. Stream.Stream = Stream;
  49235. // old-style streams. Note that the pipe method (the only relevant
  49236. // part of this class) is overridden in the Readable class.
  49237. function Stream() {
  49238. EE.call(this);
  49239. }
  49240. Stream.prototype.pipe = function (dest, options) {
  49241. var source = this;
  49242. function ondata(chunk) {
  49243. if (dest.writable) {
  49244. if (false === dest.write(chunk) && source.pause) {
  49245. source.pause();
  49246. }
  49247. }
  49248. }
  49249. source.on('data', ondata);
  49250. function ondrain() {
  49251. if (source.readable && source.resume) {
  49252. source.resume();
  49253. }
  49254. }
  49255. dest.on('drain', ondrain);
  49256. // If the 'end' option is not supplied, dest.end() will be called when
  49257. // source gets the 'end' or 'close' events. Only dest.end() once.
  49258. if (!dest._isStdio && (!options || options.end !== false)) {
  49259. source.on('end', onend);
  49260. source.on('close', onclose);
  49261. }
  49262. var didOnEnd = false;
  49263. function onend() {
  49264. if (didOnEnd) return;
  49265. didOnEnd = true;
  49266. dest.end();
  49267. }
  49268. function onclose() {
  49269. if (didOnEnd) return;
  49270. didOnEnd = true;
  49271. if (typeof dest.destroy === 'function') dest.destroy();
  49272. }
  49273. // don't leave dangling pipes when there are errors.
  49274. function onerror(er) {
  49275. cleanup();
  49276. if (EE.listenerCount(this, 'error') === 0) {
  49277. throw er; // Unhandled stream error in pipe.
  49278. }
  49279. }
  49280. source.on('error', onerror);
  49281. dest.on('error', onerror);
  49282. // remove all the event listeners that were added.
  49283. function cleanup() {
  49284. source.removeListener('data', ondata);
  49285. dest.removeListener('drain', ondrain);
  49286. source.removeListener('end', onend);
  49287. source.removeListener('close', onclose);
  49288. source.removeListener('error', onerror);
  49289. dest.removeListener('error', onerror);
  49290. source.removeListener('end', cleanup);
  49291. source.removeListener('close', cleanup);
  49292. dest.removeListener('close', cleanup);
  49293. }
  49294. source.on('end', cleanup);
  49295. source.on('close', cleanup);
  49296. dest.on('close', cleanup);
  49297. dest.emit('pipe', source);
  49298. // Allow for unix-like usage: A.pipe(B).pipe(C)
  49299. return dest;
  49300. };
  49301. },{"events":261,"inherits":279,"readable-stream/duplex.js":345,"readable-stream/passthrough.js":354,"readable-stream/readable.js":355,"readable-stream/transform.js":356,"readable-stream/writable.js":357}],344:[function(require,module,exports){
  49302. "use strict";
  49303. var toString = {}.toString;
  49304. module.exports = Array.isArray || function (arr) {
  49305. return toString.call(arr) == '[object Array]';
  49306. };
  49307. },{}],345:[function(require,module,exports){
  49308. "use strict";
  49309. module.exports = require('./lib/_stream_duplex.js');
  49310. },{"./lib/_stream_duplex.js":346}],346:[function(require,module,exports){
  49311. // Copyright Joyent, Inc. and other Node contributors.
  49312. //
  49313. // Permission is hereby granted, free of charge, to any person obtaining a
  49314. // copy of this software and associated documentation files (the
  49315. // "Software"), to deal in the Software without restriction, including
  49316. // without limitation the rights to use, copy, modify, merge, publish,
  49317. // distribute, sublicense, and/or sell copies of the Software, and to permit
  49318. // persons to whom the Software is furnished to do so, subject to the
  49319. // following conditions:
  49320. //
  49321. // The above copyright notice and this permission notice shall be included
  49322. // in all copies or substantial portions of the Software.
  49323. //
  49324. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  49325. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  49326. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  49327. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  49328. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  49329. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  49330. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  49331. // a duplex stream is just a stream that is both readable and writable.
  49332. // Since JS doesn't have multiple prototypal inheritance, this class
  49333. // prototypally inherits from Readable, and then parasitically from
  49334. // Writable.
  49335. 'use strict';
  49336. /*<replacement>*/
  49337. var pna = require('process-nextick-args');
  49338. /*</replacement>*/
  49339. /*<replacement>*/
  49340. var objectKeys = Object.keys || function (obj) {
  49341. var keys = [];
  49342. for (var key in obj) {
  49343. keys.push(key);
  49344. }
  49345. return keys;
  49346. };
  49347. /*</replacement>*/
  49348. module.exports = Duplex;
  49349. /*<replacement>*/
  49350. var util = Object.create(require('core-util-is'));
  49351. util.inherits = require('inherits');
  49352. /*</replacement>*/
  49353. var Readable = require('./_stream_readable');
  49354. var Writable = require('./_stream_writable');
  49355. util.inherits(Duplex, Readable);
  49356. {
  49357. // avoid scope creep, the keys array can then be collected
  49358. var keys = objectKeys(Writable.prototype);
  49359. for (var v = 0; v < keys.length; v++) {
  49360. var method = keys[v];
  49361. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  49362. }
  49363. }
  49364. function Duplex(options) {
  49365. if (!(this instanceof Duplex)) return new Duplex(options);
  49366. Readable.call(this, options);
  49367. Writable.call(this, options);
  49368. if (options && options.readable === false) this.readable = false;
  49369. if (options && options.writable === false) this.writable = false;
  49370. this.allowHalfOpen = true;
  49371. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  49372. this.once('end', onend);
  49373. }
  49374. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  49375. // making it explicit this property is not enumerable
  49376. // because otherwise some prototype manipulation in
  49377. // userland will fail
  49378. enumerable: false,
  49379. get: function () {
  49380. return this._writableState.highWaterMark;
  49381. }
  49382. });
  49383. // the no-half-open enforcer
  49384. function onend() {
  49385. // if we allow half-open state, or if the writable side ended,
  49386. // then we're ok.
  49387. if (this.allowHalfOpen || this._writableState.ended) return;
  49388. // no more data can be written.
  49389. // But allow more writes to happen in this tick.
  49390. pna.nextTick(onEndNT, this);
  49391. }
  49392. function onEndNT(self) {
  49393. self.end();
  49394. }
  49395. Object.defineProperty(Duplex.prototype, 'destroyed', {
  49396. get: function () {
  49397. if (this._readableState === undefined || this._writableState === undefined) {
  49398. return false;
  49399. }
  49400. return this._readableState.destroyed && this._writableState.destroyed;
  49401. },
  49402. set: function (value) {
  49403. // we ignore the value if the stream
  49404. // has not been initialized yet
  49405. if (this._readableState === undefined || this._writableState === undefined) {
  49406. return;
  49407. }
  49408. // backward compatibility, the user is explicitly
  49409. // managing destroyed
  49410. this._readableState.destroyed = value;
  49411. this._writableState.destroyed = value;
  49412. }
  49413. });
  49414. Duplex.prototype._destroy = function (err, cb) {
  49415. this.push(null);
  49416. this.end();
  49417. pna.nextTick(cb, err);
  49418. };
  49419. },{"./_stream_readable":348,"./_stream_writable":350,"core-util-is":222,"inherits":279,"process-nextick-args":305}],347:[function(require,module,exports){
  49420. // Copyright Joyent, Inc. and other Node contributors.
  49421. //
  49422. // Permission is hereby granted, free of charge, to any person obtaining a
  49423. // copy of this software and associated documentation files (the
  49424. // "Software"), to deal in the Software without restriction, including
  49425. // without limitation the rights to use, copy, modify, merge, publish,
  49426. // distribute, sublicense, and/or sell copies of the Software, and to permit
  49427. // persons to whom the Software is furnished to do so, subject to the
  49428. // following conditions:
  49429. //
  49430. // The above copyright notice and this permission notice shall be included
  49431. // in all copies or substantial portions of the Software.
  49432. //
  49433. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  49434. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  49435. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  49436. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  49437. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  49438. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  49439. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  49440. // a passthrough stream.
  49441. // basically just the most minimal sort of Transform stream.
  49442. // Every written chunk gets output as-is.
  49443. 'use strict';
  49444. module.exports = PassThrough;
  49445. var Transform = require('./_stream_transform');
  49446. /*<replacement>*/
  49447. var util = Object.create(require('core-util-is'));
  49448. util.inherits = require('inherits');
  49449. /*</replacement>*/
  49450. util.inherits(PassThrough, Transform);
  49451. function PassThrough(options) {
  49452. if (!(this instanceof PassThrough)) return new PassThrough(options);
  49453. Transform.call(this, options);
  49454. }
  49455. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  49456. cb(null, chunk);
  49457. };
  49458. },{"./_stream_transform":349,"core-util-is":222,"inherits":279}],348:[function(require,module,exports){
  49459. (function (process,global){(function (){
  49460. // Copyright Joyent, Inc. and other Node contributors.
  49461. //
  49462. // Permission is hereby granted, free of charge, to any person obtaining a
  49463. // copy of this software and associated documentation files (the
  49464. // "Software"), to deal in the Software without restriction, including
  49465. // without limitation the rights to use, copy, modify, merge, publish,
  49466. // distribute, sublicense, and/or sell copies of the Software, and to permit
  49467. // persons to whom the Software is furnished to do so, subject to the
  49468. // following conditions:
  49469. //
  49470. // The above copyright notice and this permission notice shall be included
  49471. // in all copies or substantial portions of the Software.
  49472. //
  49473. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  49474. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  49475. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  49476. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  49477. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  49478. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  49479. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  49480. 'use strict';
  49481. /*<replacement>*/
  49482. var pna = require('process-nextick-args');
  49483. /*</replacement>*/
  49484. module.exports = Readable;
  49485. /*<replacement>*/
  49486. var isArray = require('isarray');
  49487. /*</replacement>*/
  49488. /*<replacement>*/
  49489. var Duplex;
  49490. /*</replacement>*/
  49491. Readable.ReadableState = ReadableState;
  49492. /*<replacement>*/
  49493. var EE = require('events').EventEmitter;
  49494. var EElistenerCount = function (emitter, type) {
  49495. return emitter.listeners(type).length;
  49496. };
  49497. /*</replacement>*/
  49498. /*<replacement>*/
  49499. var Stream = require('./internal/streams/stream');
  49500. /*</replacement>*/
  49501. /*<replacement>*/
  49502. var Buffer = require('safe-buffer').Buffer;
  49503. var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
  49504. function _uint8ArrayToBuffer(chunk) {
  49505. return Buffer.from(chunk);
  49506. }
  49507. function _isUint8Array(obj) {
  49508. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  49509. }
  49510. /*</replacement>*/
  49511. /*<replacement>*/
  49512. var util = Object.create(require('core-util-is'));
  49513. util.inherits = require('inherits');
  49514. /*</replacement>*/
  49515. /*<replacement>*/
  49516. var debugUtil = require('util');
  49517. var debug = void 0;
  49518. if (debugUtil && debugUtil.debuglog) {
  49519. debug = debugUtil.debuglog('stream');
  49520. } else {
  49521. debug = function () {};
  49522. }
  49523. /*</replacement>*/
  49524. var BufferList = require('./internal/streams/BufferList');
  49525. var destroyImpl = require('./internal/streams/destroy');
  49526. var StringDecoder;
  49527. util.inherits(Readable, Stream);
  49528. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  49529. function prependListener(emitter, event, fn) {
  49530. // Sadly this is not cacheable as some libraries bundle their own
  49531. // event emitter implementation with them.
  49532. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  49533. // This is a hack to make sure that our error handler is attached before any
  49534. // userland ones. NEVER DO THIS. This is here only because this code needs
  49535. // to continue to work with older versions of Node.js that do not include
  49536. // the prependListener() method. The goal is to eventually remove this hack.
  49537. 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]];
  49538. }
  49539. function ReadableState(options, stream) {
  49540. Duplex = Duplex || require('./_stream_duplex');
  49541. options = options || {};
  49542. // Duplex streams are both readable and writable, but share
  49543. // the same options object.
  49544. // However, some cases require setting options to different
  49545. // values for the readable and the writable sides of the duplex stream.
  49546. // These options can be provided separately as readableXXX and writableXXX.
  49547. var isDuplex = stream instanceof Duplex;
  49548. // object stream flag. Used to make read(n) ignore n and to
  49549. // make all the buffer merging and length checks go away
  49550. this.objectMode = !!options.objectMode;
  49551. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  49552. // the point at which it stops calling _read() to fill the buffer
  49553. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  49554. var hwm = options.highWaterMark;
  49555. var readableHwm = options.readableHighWaterMark;
  49556. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  49557. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  49558. // cast to ints.
  49559. this.highWaterMark = Math.floor(this.highWaterMark);
  49560. // A linked list is used to store data chunks instead of an array because the
  49561. // linked list can remove elements from the beginning faster than
  49562. // array.shift()
  49563. this.buffer = new BufferList();
  49564. this.length = 0;
  49565. this.pipes = null;
  49566. this.pipesCount = 0;
  49567. this.flowing = null;
  49568. this.ended = false;
  49569. this.endEmitted = false;
  49570. this.reading = false;
  49571. // a flag to be able to tell if the event 'readable'/'data' is emitted
  49572. // immediately, or on a later tick. We set this to true at first, because
  49573. // any actions that shouldn't happen until "later" should generally also
  49574. // not happen before the first read call.
  49575. this.sync = true;
  49576. // whenever we return null, then we set a flag to say
  49577. // that we're awaiting a 'readable' event emission.
  49578. this.needReadable = false;
  49579. this.emittedReadable = false;
  49580. this.readableListening = false;
  49581. this.resumeScheduled = false;
  49582. // has it been destroyed
  49583. this.destroyed = false;
  49584. // Crypto is kind of old and crusty. Historically, its default string
  49585. // encoding is 'binary' so we have to make this configurable.
  49586. // Everything else in the universe uses 'utf8', though.
  49587. this.defaultEncoding = options.defaultEncoding || 'utf8';
  49588. // the number of writers that are awaiting a drain event in .pipe()s
  49589. this.awaitDrain = 0;
  49590. // if true, a maybeReadMore has been scheduled
  49591. this.readingMore = false;
  49592. this.decoder = null;
  49593. this.encoding = null;
  49594. if (options.encoding) {
  49595. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  49596. this.decoder = new StringDecoder(options.encoding);
  49597. this.encoding = options.encoding;
  49598. }
  49599. }
  49600. function Readable(options) {
  49601. Duplex = Duplex || require('./_stream_duplex');
  49602. if (!(this instanceof Readable)) return new Readable(options);
  49603. this._readableState = new ReadableState(options, this);
  49604. // legacy
  49605. this.readable = true;
  49606. if (options) {
  49607. if (typeof options.read === 'function') this._read = options.read;
  49608. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  49609. }
  49610. Stream.call(this);
  49611. }
  49612. Object.defineProperty(Readable.prototype, 'destroyed', {
  49613. get: function () {
  49614. if (this._readableState === undefined) {
  49615. return false;
  49616. }
  49617. return this._readableState.destroyed;
  49618. },
  49619. set: function (value) {
  49620. // we ignore the value if the stream
  49621. // has not been initialized yet
  49622. if (!this._readableState) {
  49623. return;
  49624. }
  49625. // backward compatibility, the user is explicitly
  49626. // managing destroyed
  49627. this._readableState.destroyed = value;
  49628. }
  49629. });
  49630. Readable.prototype.destroy = destroyImpl.destroy;
  49631. Readable.prototype._undestroy = destroyImpl.undestroy;
  49632. Readable.prototype._destroy = function (err, cb) {
  49633. this.push(null);
  49634. cb(err);
  49635. };
  49636. // Manually shove something into the read() buffer.
  49637. // This returns true if the highWaterMark has not been hit yet,
  49638. // similar to how Writable.write() returns true if you should
  49639. // write() some more.
  49640. Readable.prototype.push = function (chunk, encoding) {
  49641. var state = this._readableState;
  49642. var skipChunkCheck;
  49643. if (!state.objectMode) {
  49644. if (typeof chunk === 'string') {
  49645. encoding = encoding || state.defaultEncoding;
  49646. if (encoding !== state.encoding) {
  49647. chunk = Buffer.from(chunk, encoding);
  49648. encoding = '';
  49649. }
  49650. skipChunkCheck = true;
  49651. }
  49652. } else {
  49653. skipChunkCheck = true;
  49654. }
  49655. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  49656. };
  49657. // Unshift should *always* be something directly out of read()
  49658. Readable.prototype.unshift = function (chunk) {
  49659. return readableAddChunk(this, chunk, null, true, false);
  49660. };
  49661. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  49662. var state = stream._readableState;
  49663. if (chunk === null) {
  49664. state.reading = false;
  49665. onEofChunk(stream, state);
  49666. } else {
  49667. var er;
  49668. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  49669. if (er) {
  49670. stream.emit('error', er);
  49671. } else if (state.objectMode || chunk && chunk.length > 0) {
  49672. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  49673. chunk = _uint8ArrayToBuffer(chunk);
  49674. }
  49675. if (addToFront) {
  49676. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  49677. } else if (state.ended) {
  49678. stream.emit('error', new Error('stream.push() after EOF'));
  49679. } else {
  49680. state.reading = false;
  49681. if (state.decoder && !encoding) {
  49682. chunk = state.decoder.write(chunk);
  49683. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  49684. } else {
  49685. addChunk(stream, state, chunk, false);
  49686. }
  49687. }
  49688. } else if (!addToFront) {
  49689. state.reading = false;
  49690. }
  49691. }
  49692. return needMoreData(state);
  49693. }
  49694. function addChunk(stream, state, chunk, addToFront) {
  49695. if (state.flowing && state.length === 0 && !state.sync) {
  49696. stream.emit('data', chunk);
  49697. stream.read(0);
  49698. } else {
  49699. // update the buffer info.
  49700. state.length += state.objectMode ? 1 : chunk.length;
  49701. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  49702. if (state.needReadable) emitReadable(stream);
  49703. }
  49704. maybeReadMore(stream, state);
  49705. }
  49706. function chunkInvalid(state, chunk) {
  49707. var er;
  49708. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  49709. er = new TypeError('Invalid non-string/buffer chunk');
  49710. }
  49711. return er;
  49712. }
  49713. // if it's past the high water mark, we can push in some more.
  49714. // Also, if we have no data yet, we can stand some
  49715. // more bytes. This is to work around cases where hwm=0,
  49716. // such as the repl. Also, if the push() triggered a
  49717. // readable event, and the user called read(largeNumber) such that
  49718. // needReadable was set, then we ought to push more, so that another
  49719. // 'readable' event will be triggered.
  49720. function needMoreData(state) {
  49721. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  49722. }
  49723. Readable.prototype.isPaused = function () {
  49724. return this._readableState.flowing === false;
  49725. };
  49726. // backwards compatibility.
  49727. Readable.prototype.setEncoding = function (enc) {
  49728. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  49729. this._readableState.decoder = new StringDecoder(enc);
  49730. this._readableState.encoding = enc;
  49731. return this;
  49732. };
  49733. // Don't raise the hwm > 8MB
  49734. var MAX_HWM = 0x800000;
  49735. function computeNewHighWaterMark(n) {
  49736. if (n >= MAX_HWM) {
  49737. n = MAX_HWM;
  49738. } else {
  49739. // Get the next highest power of 2 to prevent increasing hwm excessively in
  49740. // tiny amounts
  49741. n--;
  49742. n |= n >>> 1;
  49743. n |= n >>> 2;
  49744. n |= n >>> 4;
  49745. n |= n >>> 8;
  49746. n |= n >>> 16;
  49747. n++;
  49748. }
  49749. return n;
  49750. }
  49751. // This function is designed to be inlinable, so please take care when making
  49752. // changes to the function body.
  49753. function howMuchToRead(n, state) {
  49754. if (n <= 0 || state.length === 0 && state.ended) return 0;
  49755. if (state.objectMode) return 1;
  49756. if (n !== n) {
  49757. // Only flow one buffer at a time
  49758. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  49759. }
  49760. // If we're asking for more than the current hwm, then raise the hwm.
  49761. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  49762. if (n <= state.length) return n;
  49763. // Don't have enough
  49764. if (!state.ended) {
  49765. state.needReadable = true;
  49766. return 0;
  49767. }
  49768. return state.length;
  49769. }
  49770. // you can override either this method, or the async _read(n) below.
  49771. Readable.prototype.read = function (n) {
  49772. debug('read', n);
  49773. n = parseInt(n, 10);
  49774. var state = this._readableState;
  49775. var nOrig = n;
  49776. if (n !== 0) state.emittedReadable = false;
  49777. // if we're doing read(0) to trigger a readable event, but we
  49778. // already have a bunch of data in the buffer, then just trigger
  49779. // the 'readable' event and move on.
  49780. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  49781. debug('read: emitReadable', state.length, state.ended);
  49782. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  49783. return null;
  49784. }
  49785. n = howMuchToRead(n, state);
  49786. // if we've ended, and we're now clear, then finish it up.
  49787. if (n === 0 && state.ended) {
  49788. if (state.length === 0) endReadable(this);
  49789. return null;
  49790. }
  49791. // All the actual chunk generation logic needs to be
  49792. // *below* the call to _read. The reason is that in certain
  49793. // synthetic stream cases, such as passthrough streams, _read
  49794. // may be a completely synchronous operation which may change
  49795. // the state of the read buffer, providing enough data when
  49796. // before there was *not* enough.
  49797. //
  49798. // So, the steps are:
  49799. // 1. Figure out what the state of things will be after we do
  49800. // a read from the buffer.
  49801. //
  49802. // 2. If that resulting state will trigger a _read, then call _read.
  49803. // Note that this may be asynchronous, or synchronous. Yes, it is
  49804. // deeply ugly to write APIs this way, but that still doesn't mean
  49805. // that the Readable class should behave improperly, as streams are
  49806. // designed to be sync/async agnostic.
  49807. // Take note if the _read call is sync or async (ie, if the read call
  49808. // has returned yet), so that we know whether or not it's safe to emit
  49809. // 'readable' etc.
  49810. //
  49811. // 3. Actually pull the requested chunks out of the buffer and return.
  49812. // if we need a readable event, then we need to do some reading.
  49813. var doRead = state.needReadable;
  49814. debug('need readable', doRead);
  49815. // if we currently have less than the highWaterMark, then also read some
  49816. if (state.length === 0 || state.length - n < state.highWaterMark) {
  49817. doRead = true;
  49818. debug('length less than watermark', doRead);
  49819. }
  49820. // however, if we've ended, then there's no point, and if we're already
  49821. // reading, then it's unnecessary.
  49822. if (state.ended || state.reading) {
  49823. doRead = false;
  49824. debug('reading or ended', doRead);
  49825. } else if (doRead) {
  49826. debug('do read');
  49827. state.reading = true;
  49828. state.sync = true;
  49829. // if the length is currently zero, then we *need* a readable event.
  49830. if (state.length === 0) state.needReadable = true;
  49831. // call internal read method
  49832. this._read(state.highWaterMark);
  49833. state.sync = false;
  49834. // If _read pushed data synchronously, then `reading` will be false,
  49835. // and we need to re-evaluate how much data we can return to the user.
  49836. if (!state.reading) n = howMuchToRead(nOrig, state);
  49837. }
  49838. var ret;
  49839. if (n > 0) ret = fromList(n, state);else ret = null;
  49840. if (ret === null) {
  49841. state.needReadable = true;
  49842. n = 0;
  49843. } else {
  49844. state.length -= n;
  49845. }
  49846. if (state.length === 0) {
  49847. // If we have nothing in the buffer, then we want to know
  49848. // as soon as we *do* get something into the buffer.
  49849. if (!state.ended) state.needReadable = true;
  49850. // If we tried to read() past the EOF, then emit end on the next tick.
  49851. if (nOrig !== n && state.ended) endReadable(this);
  49852. }
  49853. if (ret !== null) this.emit('data', ret);
  49854. return ret;
  49855. };
  49856. function onEofChunk(stream, state) {
  49857. if (state.ended) return;
  49858. if (state.decoder) {
  49859. var chunk = state.decoder.end();
  49860. if (chunk && chunk.length) {
  49861. state.buffer.push(chunk);
  49862. state.length += state.objectMode ? 1 : chunk.length;
  49863. }
  49864. }
  49865. state.ended = true;
  49866. // emit 'readable' now to make sure it gets picked up.
  49867. emitReadable(stream);
  49868. }
  49869. // Don't emit readable right away in sync mode, because this can trigger
  49870. // another read() call => stack overflow. This way, it might trigger
  49871. // a nextTick recursion warning, but that's not so bad.
  49872. function emitReadable(stream) {
  49873. var state = stream._readableState;
  49874. state.needReadable = false;
  49875. if (!state.emittedReadable) {
  49876. debug('emitReadable', state.flowing);
  49877. state.emittedReadable = true;
  49878. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  49879. }
  49880. }
  49881. function emitReadable_(stream) {
  49882. debug('emit readable');
  49883. stream.emit('readable');
  49884. flow(stream);
  49885. }
  49886. // at this point, the user has presumably seen the 'readable' event,
  49887. // and called read() to consume some data. that may have triggered
  49888. // in turn another _read(n) call, in which case reading = true if
  49889. // it's in progress.
  49890. // However, if we're not ended, or reading, and the length < hwm,
  49891. // then go ahead and try to read some more preemptively.
  49892. function maybeReadMore(stream, state) {
  49893. if (!state.readingMore) {
  49894. state.readingMore = true;
  49895. pna.nextTick(maybeReadMore_, stream, state);
  49896. }
  49897. }
  49898. function maybeReadMore_(stream, state) {
  49899. var len = state.length;
  49900. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  49901. debug('maybeReadMore read 0');
  49902. stream.read(0);
  49903. if (len === state.length)
  49904. // didn't get any data, stop spinning.
  49905. break;else len = state.length;
  49906. }
  49907. state.readingMore = false;
  49908. }
  49909. // abstract method. to be overridden in specific implementation classes.
  49910. // call cb(er, data) where data is <= n in length.
  49911. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  49912. // arbitrary, and perhaps not very meaningful.
  49913. Readable.prototype._read = function (n) {
  49914. this.emit('error', new Error('_read() is not implemented'));
  49915. };
  49916. Readable.prototype.pipe = function (dest, pipeOpts) {
  49917. var src = this;
  49918. var state = this._readableState;
  49919. switch (state.pipesCount) {
  49920. case 0:
  49921. state.pipes = dest;
  49922. break;
  49923. case 1:
  49924. state.pipes = [state.pipes, dest];
  49925. break;
  49926. default:
  49927. state.pipes.push(dest);
  49928. break;
  49929. }
  49930. state.pipesCount += 1;
  49931. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  49932. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  49933. var endFn = doEnd ? onend : unpipe;
  49934. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  49935. dest.on('unpipe', onunpipe);
  49936. function onunpipe(readable, unpipeInfo) {
  49937. debug('onunpipe');
  49938. if (readable === src) {
  49939. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  49940. unpipeInfo.hasUnpiped = true;
  49941. cleanup();
  49942. }
  49943. }
  49944. }
  49945. function onend() {
  49946. debug('onend');
  49947. dest.end();
  49948. }
  49949. // when the dest drains, it reduces the awaitDrain counter
  49950. // on the source. This would be more elegant with a .once()
  49951. // handler in flow(), but adding and removing repeatedly is
  49952. // too slow.
  49953. var ondrain = pipeOnDrain(src);
  49954. dest.on('drain', ondrain);
  49955. var cleanedUp = false;
  49956. function cleanup() {
  49957. debug('cleanup');
  49958. // cleanup event handlers once the pipe is broken
  49959. dest.removeListener('close', onclose);
  49960. dest.removeListener('finish', onfinish);
  49961. dest.removeListener('drain', ondrain);
  49962. dest.removeListener('error', onerror);
  49963. dest.removeListener('unpipe', onunpipe);
  49964. src.removeListener('end', onend);
  49965. src.removeListener('end', unpipe);
  49966. src.removeListener('data', ondata);
  49967. cleanedUp = true;
  49968. // if the reader is waiting for a drain event from this
  49969. // specific writer, then it would cause it to never start
  49970. // flowing again.
  49971. // So, if this is awaiting a drain, then we just call it now.
  49972. // If we don't know, then assume that we are waiting for one.
  49973. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  49974. }
  49975. // If the user pushes more data while we're writing to dest then we'll end up
  49976. // in ondata again. However, we only want to increase awaitDrain once because
  49977. // dest will only emit one 'drain' event for the multiple writes.
  49978. // => Introduce a guard on increasing awaitDrain.
  49979. var increasedAwaitDrain = false;
  49980. src.on('data', ondata);
  49981. function ondata(chunk) {
  49982. debug('ondata');
  49983. increasedAwaitDrain = false;
  49984. var ret = dest.write(chunk);
  49985. if (false === ret && !increasedAwaitDrain) {
  49986. // If the user unpiped during `dest.write()`, it is possible
  49987. // to get stuck in a permanently paused state if that write
  49988. // also returned false.
  49989. // => Check whether `dest` is still a piping destination.
  49990. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  49991. debug('false write response, pause', state.awaitDrain);
  49992. state.awaitDrain++;
  49993. increasedAwaitDrain = true;
  49994. }
  49995. src.pause();
  49996. }
  49997. }
  49998. // if the dest has an error, then stop piping into it.
  49999. // however, don't suppress the throwing behavior for this.
  50000. function onerror(er) {
  50001. debug('onerror', er);
  50002. unpipe();
  50003. dest.removeListener('error', onerror);
  50004. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  50005. }
  50006. // Make sure our error handler is attached before userland ones.
  50007. prependListener(dest, 'error', onerror);
  50008. // Both close and finish should trigger unpipe, but only once.
  50009. function onclose() {
  50010. dest.removeListener('finish', onfinish);
  50011. unpipe();
  50012. }
  50013. dest.once('close', onclose);
  50014. function onfinish() {
  50015. debug('onfinish');
  50016. dest.removeListener('close', onclose);
  50017. unpipe();
  50018. }
  50019. dest.once('finish', onfinish);
  50020. function unpipe() {
  50021. debug('unpipe');
  50022. src.unpipe(dest);
  50023. }
  50024. // tell the dest that it's being piped to
  50025. dest.emit('pipe', src);
  50026. // start the flow if it hasn't been started already.
  50027. if (!state.flowing) {
  50028. debug('pipe resume');
  50029. src.resume();
  50030. }
  50031. return dest;
  50032. };
  50033. function pipeOnDrain(src) {
  50034. return function () {
  50035. var state = src._readableState;
  50036. debug('pipeOnDrain', state.awaitDrain);
  50037. if (state.awaitDrain) state.awaitDrain--;
  50038. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  50039. state.flowing = true;
  50040. flow(src);
  50041. }
  50042. };
  50043. }
  50044. Readable.prototype.unpipe = function (dest) {
  50045. var state = this._readableState;
  50046. var unpipeInfo = {
  50047. hasUnpiped: false
  50048. };
  50049. // if we're not piping anywhere, then do nothing.
  50050. if (state.pipesCount === 0) return this;
  50051. // just one destination. most common case.
  50052. if (state.pipesCount === 1) {
  50053. // passed in one, but it's not the right one.
  50054. if (dest && dest !== state.pipes) return this;
  50055. if (!dest) dest = state.pipes;
  50056. // got a match.
  50057. state.pipes = null;
  50058. state.pipesCount = 0;
  50059. state.flowing = false;
  50060. if (dest) dest.emit('unpipe', this, unpipeInfo);
  50061. return this;
  50062. }
  50063. // slow case. multiple pipe destinations.
  50064. if (!dest) {
  50065. // remove all.
  50066. var dests = state.pipes;
  50067. var len = state.pipesCount;
  50068. state.pipes = null;
  50069. state.pipesCount = 0;
  50070. state.flowing = false;
  50071. for (var i = 0; i < len; i++) {
  50072. dests[i].emit('unpipe', this, {
  50073. hasUnpiped: false
  50074. });
  50075. }
  50076. return this;
  50077. }
  50078. // try to find the right one.
  50079. var index = indexOf(state.pipes, dest);
  50080. if (index === -1) return this;
  50081. state.pipes.splice(index, 1);
  50082. state.pipesCount -= 1;
  50083. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  50084. dest.emit('unpipe', this, unpipeInfo);
  50085. return this;
  50086. };
  50087. // set up data events if they are asked for
  50088. // Ensure readable listeners eventually get something
  50089. Readable.prototype.on = function (ev, fn) {
  50090. var res = Stream.prototype.on.call(this, ev, fn);
  50091. if (ev === 'data') {
  50092. // Start flowing on next tick if stream isn't explicitly paused
  50093. if (this._readableState.flowing !== false) this.resume();
  50094. } else if (ev === 'readable') {
  50095. var state = this._readableState;
  50096. if (!state.endEmitted && !state.readableListening) {
  50097. state.readableListening = state.needReadable = true;
  50098. state.emittedReadable = false;
  50099. if (!state.reading) {
  50100. pna.nextTick(nReadingNextTick, this);
  50101. } else if (state.length) {
  50102. emitReadable(this);
  50103. }
  50104. }
  50105. }
  50106. return res;
  50107. };
  50108. Readable.prototype.addListener = Readable.prototype.on;
  50109. function nReadingNextTick(self) {
  50110. debug('readable nexttick read 0');
  50111. self.read(0);
  50112. }
  50113. // pause() and resume() are remnants of the legacy readable stream API
  50114. // If the user uses them, then switch into old mode.
  50115. Readable.prototype.resume = function () {
  50116. var state = this._readableState;
  50117. if (!state.flowing) {
  50118. debug('resume');
  50119. state.flowing = true;
  50120. resume(this, state);
  50121. }
  50122. return this;
  50123. };
  50124. function resume(stream, state) {
  50125. if (!state.resumeScheduled) {
  50126. state.resumeScheduled = true;
  50127. pna.nextTick(resume_, stream, state);
  50128. }
  50129. }
  50130. function resume_(stream, state) {
  50131. if (!state.reading) {
  50132. debug('resume read 0');
  50133. stream.read(0);
  50134. }
  50135. state.resumeScheduled = false;
  50136. state.awaitDrain = 0;
  50137. stream.emit('resume');
  50138. flow(stream);
  50139. if (state.flowing && !state.reading) stream.read(0);
  50140. }
  50141. Readable.prototype.pause = function () {
  50142. debug('call pause flowing=%j', this._readableState.flowing);
  50143. if (false !== this._readableState.flowing) {
  50144. debug('pause');
  50145. this._readableState.flowing = false;
  50146. this.emit('pause');
  50147. }
  50148. return this;
  50149. };
  50150. function flow(stream) {
  50151. var state = stream._readableState;
  50152. debug('flow', state.flowing);
  50153. while (state.flowing && stream.read() !== null) {}
  50154. }
  50155. // wrap an old-style stream as the async data source.
  50156. // This is *not* part of the readable stream interface.
  50157. // It is an ugly unfortunate mess of history.
  50158. Readable.prototype.wrap = function (stream) {
  50159. var _this = this;
  50160. var state = this._readableState;
  50161. var paused = false;
  50162. stream.on('end', function () {
  50163. debug('wrapped end');
  50164. if (state.decoder && !state.ended) {
  50165. var chunk = state.decoder.end();
  50166. if (chunk && chunk.length) _this.push(chunk);
  50167. }
  50168. _this.push(null);
  50169. });
  50170. stream.on('data', function (chunk) {
  50171. debug('wrapped data');
  50172. if (state.decoder) chunk = state.decoder.write(chunk);
  50173. // don't skip over falsy values in objectMode
  50174. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  50175. var ret = _this.push(chunk);
  50176. if (!ret) {
  50177. paused = true;
  50178. stream.pause();
  50179. }
  50180. });
  50181. // proxy all the other methods.
  50182. // important when wrapping filters and duplexes.
  50183. for (var i in stream) {
  50184. if (this[i] === undefined && typeof stream[i] === 'function') {
  50185. this[i] = function (method) {
  50186. return function () {
  50187. return stream[method].apply(stream, arguments);
  50188. };
  50189. }(i);
  50190. }
  50191. }
  50192. // proxy certain important events.
  50193. for (var n = 0; n < kProxyEvents.length; n++) {
  50194. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  50195. }
  50196. // when we try to consume some more bytes, simply unpause the
  50197. // underlying stream.
  50198. this._read = function (n) {
  50199. debug('wrapped _read', n);
  50200. if (paused) {
  50201. paused = false;
  50202. stream.resume();
  50203. }
  50204. };
  50205. return this;
  50206. };
  50207. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  50208. // making it explicit this property is not enumerable
  50209. // because otherwise some prototype manipulation in
  50210. // userland will fail
  50211. enumerable: false,
  50212. get: function () {
  50213. return this._readableState.highWaterMark;
  50214. }
  50215. });
  50216. // exposed for testing purposes only.
  50217. Readable._fromList = fromList;
  50218. // Pluck off n bytes from an array of buffers.
  50219. // Length is the combined lengths of all the buffers in the list.
  50220. // This function is designed to be inlinable, so please take care when making
  50221. // changes to the function body.
  50222. function fromList(n, state) {
  50223. // nothing buffered
  50224. if (state.length === 0) return null;
  50225. var ret;
  50226. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  50227. // read it all, truncate the list
  50228. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  50229. state.buffer.clear();
  50230. } else {
  50231. // read part of list
  50232. ret = fromListPartial(n, state.buffer, state.decoder);
  50233. }
  50234. return ret;
  50235. }
  50236. // Extracts only enough buffered data to satisfy the amount requested.
  50237. // This function is designed to be inlinable, so please take care when making
  50238. // changes to the function body.
  50239. function fromListPartial(n, list, hasStrings) {
  50240. var ret;
  50241. if (n < list.head.data.length) {
  50242. // slice is the same for buffers and strings
  50243. ret = list.head.data.slice(0, n);
  50244. list.head.data = list.head.data.slice(n);
  50245. } else if (n === list.head.data.length) {
  50246. // first chunk is a perfect match
  50247. ret = list.shift();
  50248. } else {
  50249. // result spans more than one buffer
  50250. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  50251. }
  50252. return ret;
  50253. }
  50254. // Copies a specified amount of characters from the list of buffered data
  50255. // chunks.
  50256. // This function is designed to be inlinable, so please take care when making
  50257. // changes to the function body.
  50258. function copyFromBufferString(n, list) {
  50259. var p = list.head;
  50260. var c = 1;
  50261. var ret = p.data;
  50262. n -= ret.length;
  50263. while (p = p.next) {
  50264. var str = p.data;
  50265. var nb = n > str.length ? str.length : n;
  50266. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  50267. n -= nb;
  50268. if (n === 0) {
  50269. if (nb === str.length) {
  50270. ++c;
  50271. if (p.next) list.head = p.next;else list.head = list.tail = null;
  50272. } else {
  50273. list.head = p;
  50274. p.data = str.slice(nb);
  50275. }
  50276. break;
  50277. }
  50278. ++c;
  50279. }
  50280. list.length -= c;
  50281. return ret;
  50282. }
  50283. // Copies a specified amount of bytes from the list of buffered data chunks.
  50284. // This function is designed to be inlinable, so please take care when making
  50285. // changes to the function body.
  50286. function copyFromBuffer(n, list) {
  50287. var ret = Buffer.allocUnsafe(n);
  50288. var p = list.head;
  50289. var c = 1;
  50290. p.data.copy(ret);
  50291. n -= p.data.length;
  50292. while (p = p.next) {
  50293. var buf = p.data;
  50294. var nb = n > buf.length ? buf.length : n;
  50295. buf.copy(ret, ret.length - n, 0, nb);
  50296. n -= nb;
  50297. if (n === 0) {
  50298. if (nb === buf.length) {
  50299. ++c;
  50300. if (p.next) list.head = p.next;else list.head = list.tail = null;
  50301. } else {
  50302. list.head = p;
  50303. p.data = buf.slice(nb);
  50304. }
  50305. break;
  50306. }
  50307. ++c;
  50308. }
  50309. list.length -= c;
  50310. return ret;
  50311. }
  50312. function endReadable(stream) {
  50313. var state = stream._readableState;
  50314. // If we get here before consuming all the bytes, then that is a
  50315. // bug in node. Should never happen.
  50316. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  50317. if (!state.endEmitted) {
  50318. state.ended = true;
  50319. pna.nextTick(endReadableNT, state, stream);
  50320. }
  50321. }
  50322. function endReadableNT(state, stream) {
  50323. // Check that we didn't get one last unshift.
  50324. if (!state.endEmitted && state.length === 0) {
  50325. state.endEmitted = true;
  50326. stream.readable = false;
  50327. stream.emit('end');
  50328. }
  50329. }
  50330. function indexOf(xs, x) {
  50331. for (var i = 0, l = xs.length; i < l; i++) {
  50332. if (xs[i] === x) return i;
  50333. }
  50334. return -1;
  50335. }
  50336. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  50337. },{"./_stream_duplex":346,"./internal/streams/BufferList":351,"./internal/streams/destroy":352,"./internal/streams/stream":353,"_process":306,"core-util-is":222,"events":261,"inherits":279,"isarray":344,"process-nextick-args":305,"safe-buffer":358,"string_decoder/":359,"util":188}],349:[function(require,module,exports){
  50338. // Copyright Joyent, Inc. and other Node contributors.
  50339. //
  50340. // Permission is hereby granted, free of charge, to any person obtaining a
  50341. // copy of this software and associated documentation files (the
  50342. // "Software"), to deal in the Software without restriction, including
  50343. // without limitation the rights to use, copy, modify, merge, publish,
  50344. // distribute, sublicense, and/or sell copies of the Software, and to permit
  50345. // persons to whom the Software is furnished to do so, subject to the
  50346. // following conditions:
  50347. //
  50348. // The above copyright notice and this permission notice shall be included
  50349. // in all copies or substantial portions of the Software.
  50350. //
  50351. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  50352. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  50353. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  50354. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  50355. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  50356. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  50357. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  50358. // a transform stream is a readable/writable stream where you do
  50359. // something with the data. Sometimes it's called a "filter",
  50360. // but that's not a great name for it, since that implies a thing where
  50361. // some bits pass through, and others are simply ignored. (That would
  50362. // be a valid example of a transform, of course.)
  50363. //
  50364. // While the output is causally related to the input, it's not a
  50365. // necessarily symmetric or synchronous transformation. For example,
  50366. // a zlib stream might take multiple plain-text writes(), and then
  50367. // emit a single compressed chunk some time in the future.
  50368. //
  50369. // Here's how this works:
  50370. //
  50371. // The Transform stream has all the aspects of the readable and writable
  50372. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  50373. // internally, and returns false if there's a lot of pending writes
  50374. // buffered up. When you call read(), that calls _read(n) until
  50375. // there's enough pending readable data buffered up.
  50376. //
  50377. // In a transform stream, the written data is placed in a buffer. When
  50378. // _read(n) is called, it transforms the queued up data, calling the
  50379. // buffered _write cb's as it consumes chunks. If consuming a single
  50380. // written chunk would result in multiple output chunks, then the first
  50381. // outputted bit calls the readcb, and subsequent chunks just go into
  50382. // the read buffer, and will cause it to emit 'readable' if necessary.
  50383. //
  50384. // This way, back-pressure is actually determined by the reading side,
  50385. // since _read has to be called to start processing a new chunk. However,
  50386. // a pathological inflate type of transform can cause excessive buffering
  50387. // here. For example, imagine a stream where every byte of input is
  50388. // interpreted as an integer from 0-255, and then results in that many
  50389. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  50390. // 1kb of data being output. In this case, you could write a very small
  50391. // amount of input, and end up with a very large amount of output. In
  50392. // such a pathological inflating mechanism, there'd be no way to tell
  50393. // the system to stop doing the transform. A single 4MB write could
  50394. // cause the system to run out of memory.
  50395. //
  50396. // However, even in such a pathological case, only a single written chunk
  50397. // would be consumed, and then the rest would wait (un-transformed) until
  50398. // the results of the previous transformed chunk were consumed.
  50399. 'use strict';
  50400. module.exports = Transform;
  50401. var Duplex = require('./_stream_duplex');
  50402. /*<replacement>*/
  50403. var util = Object.create(require('core-util-is'));
  50404. util.inherits = require('inherits');
  50405. /*</replacement>*/
  50406. util.inherits(Transform, Duplex);
  50407. function afterTransform(er, data) {
  50408. var ts = this._transformState;
  50409. ts.transforming = false;
  50410. var cb = ts.writecb;
  50411. if (!cb) {
  50412. return this.emit('error', new Error('write callback called multiple times'));
  50413. }
  50414. ts.writechunk = null;
  50415. ts.writecb = null;
  50416. if (data != null)
  50417. // single equals check for both `null` and `undefined`
  50418. this.push(data);
  50419. cb(er);
  50420. var rs = this._readableState;
  50421. rs.reading = false;
  50422. if (rs.needReadable || rs.length < rs.highWaterMark) {
  50423. this._read(rs.highWaterMark);
  50424. }
  50425. }
  50426. function Transform(options) {
  50427. if (!(this instanceof Transform)) return new Transform(options);
  50428. Duplex.call(this, options);
  50429. this._transformState = {
  50430. afterTransform: afterTransform.bind(this),
  50431. needTransform: false,
  50432. transforming: false,
  50433. writecb: null,
  50434. writechunk: null,
  50435. writeencoding: null
  50436. };
  50437. // start out asking for a readable event once data is transformed.
  50438. this._readableState.needReadable = true;
  50439. // we have implemented the _read method, and done the other things
  50440. // that Readable wants before the first _read call, so unset the
  50441. // sync guard flag.
  50442. this._readableState.sync = false;
  50443. if (options) {
  50444. if (typeof options.transform === 'function') this._transform = options.transform;
  50445. if (typeof options.flush === 'function') this._flush = options.flush;
  50446. }
  50447. // When the writable side finishes, then flush out anything remaining.
  50448. this.on('prefinish', prefinish);
  50449. }
  50450. function prefinish() {
  50451. var _this = this;
  50452. if (typeof this._flush === 'function') {
  50453. this._flush(function (er, data) {
  50454. done(_this, er, data);
  50455. });
  50456. } else {
  50457. done(this, null, null);
  50458. }
  50459. }
  50460. Transform.prototype.push = function (chunk, encoding) {
  50461. this._transformState.needTransform = false;
  50462. return Duplex.prototype.push.call(this, chunk, encoding);
  50463. };
  50464. // This is the part where you do stuff!
  50465. // override this function in implementation classes.
  50466. // 'chunk' is an input chunk.
  50467. //
  50468. // Call `push(newChunk)` to pass along transformed output
  50469. // to the readable side. You may call 'push' zero or more times.
  50470. //
  50471. // Call `cb(err)` when you are done with this chunk. If you pass
  50472. // an error, then that'll put the hurt on the whole operation. If you
  50473. // never call cb(), then you'll never get another chunk.
  50474. Transform.prototype._transform = function (chunk, encoding, cb) {
  50475. throw new Error('_transform() is not implemented');
  50476. };
  50477. Transform.prototype._write = function (chunk, encoding, cb) {
  50478. var ts = this._transformState;
  50479. ts.writecb = cb;
  50480. ts.writechunk = chunk;
  50481. ts.writeencoding = encoding;
  50482. if (!ts.transforming) {
  50483. var rs = this._readableState;
  50484. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  50485. }
  50486. };
  50487. // Doesn't matter what the args are here.
  50488. // _transform does all the work.
  50489. // That we got here means that the readable side wants more data.
  50490. Transform.prototype._read = function (n) {
  50491. var ts = this._transformState;
  50492. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  50493. ts.transforming = true;
  50494. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  50495. } else {
  50496. // mark that we need a transform, so that any data that comes in
  50497. // will get processed, now that we've asked for it.
  50498. ts.needTransform = true;
  50499. }
  50500. };
  50501. Transform.prototype._destroy = function (err, cb) {
  50502. var _this2 = this;
  50503. Duplex.prototype._destroy.call(this, err, function (err2) {
  50504. cb(err2);
  50505. _this2.emit('close');
  50506. });
  50507. };
  50508. function done(stream, er, data) {
  50509. if (er) return stream.emit('error', er);
  50510. if (data != null)
  50511. // single equals check for both `null` and `undefined`
  50512. stream.push(data);
  50513. // if there's nothing in the write buffer, then that means
  50514. // that nothing more will ever be provided
  50515. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  50516. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  50517. return stream.push(null);
  50518. }
  50519. },{"./_stream_duplex":346,"core-util-is":222,"inherits":279}],350:[function(require,module,exports){
  50520. (function (process,global,setImmediate){(function (){
  50521. // Copyright Joyent, Inc. and other Node contributors.
  50522. //
  50523. // Permission is hereby granted, free of charge, to any person obtaining a
  50524. // copy of this software and associated documentation files (the
  50525. // "Software"), to deal in the Software without restriction, including
  50526. // without limitation the rights to use, copy, modify, merge, publish,
  50527. // distribute, sublicense, and/or sell copies of the Software, and to permit
  50528. // persons to whom the Software is furnished to do so, subject to the
  50529. // following conditions:
  50530. //
  50531. // The above copyright notice and this permission notice shall be included
  50532. // in all copies or substantial portions of the Software.
  50533. //
  50534. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  50535. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  50536. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  50537. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  50538. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  50539. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  50540. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  50541. // A bit simpler than readable streams.
  50542. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  50543. // the drain event emission and buffering.
  50544. 'use strict';
  50545. /*<replacement>*/
  50546. var pna = require('process-nextick-args');
  50547. /*</replacement>*/
  50548. module.exports = Writable;
  50549. /* <replacement> */
  50550. function WriteReq(chunk, encoding, cb) {
  50551. this.chunk = chunk;
  50552. this.encoding = encoding;
  50553. this.callback = cb;
  50554. this.next = null;
  50555. }
  50556. // It seems a linked list but it is not
  50557. // there will be only 2 of these for each stream
  50558. function CorkedRequest(state) {
  50559. var _this = this;
  50560. this.next = null;
  50561. this.entry = null;
  50562. this.finish = function () {
  50563. onCorkedFinish(_this, state);
  50564. };
  50565. }
  50566. /* </replacement> */
  50567. /*<replacement>*/
  50568. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  50569. /*</replacement>*/
  50570. /*<replacement>*/
  50571. var Duplex;
  50572. /*</replacement>*/
  50573. Writable.WritableState = WritableState;
  50574. /*<replacement>*/
  50575. var util = Object.create(require('core-util-is'));
  50576. util.inherits = require('inherits');
  50577. /*</replacement>*/
  50578. /*<replacement>*/
  50579. var internalUtil = {
  50580. deprecate: require('util-deprecate')
  50581. };
  50582. /*</replacement>*/
  50583. /*<replacement>*/
  50584. var Stream = require('./internal/streams/stream');
  50585. /*</replacement>*/
  50586. /*<replacement>*/
  50587. var Buffer = require('safe-buffer').Buffer;
  50588. var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
  50589. function _uint8ArrayToBuffer(chunk) {
  50590. return Buffer.from(chunk);
  50591. }
  50592. function _isUint8Array(obj) {
  50593. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  50594. }
  50595. /*</replacement>*/
  50596. var destroyImpl = require('./internal/streams/destroy');
  50597. util.inherits(Writable, Stream);
  50598. function nop() {}
  50599. function WritableState(options, stream) {
  50600. Duplex = Duplex || require('./_stream_duplex');
  50601. options = options || {};
  50602. // Duplex streams are both readable and writable, but share
  50603. // the same options object.
  50604. // However, some cases require setting options to different
  50605. // values for the readable and the writable sides of the duplex stream.
  50606. // These options can be provided separately as readableXXX and writableXXX.
  50607. var isDuplex = stream instanceof Duplex;
  50608. // object stream flag to indicate whether or not this stream
  50609. // contains buffers or objects.
  50610. this.objectMode = !!options.objectMode;
  50611. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  50612. // the point at which write() starts returning false
  50613. // Note: 0 is a valid value, means that we always return false if
  50614. // the entire buffer is not flushed immediately on write()
  50615. var hwm = options.highWaterMark;
  50616. var writableHwm = options.writableHighWaterMark;
  50617. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  50618. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  50619. // cast to ints.
  50620. this.highWaterMark = Math.floor(this.highWaterMark);
  50621. // if _final has been called
  50622. this.finalCalled = false;
  50623. // drain event flag.
  50624. this.needDrain = false;
  50625. // at the start of calling end()
  50626. this.ending = false;
  50627. // when end() has been called, and returned
  50628. this.ended = false;
  50629. // when 'finish' is emitted
  50630. this.finished = false;
  50631. // has it been destroyed
  50632. this.destroyed = false;
  50633. // should we decode strings into buffers before passing to _write?
  50634. // this is here so that some node-core streams can optimize string
  50635. // handling at a lower level.
  50636. var noDecode = options.decodeStrings === false;
  50637. this.decodeStrings = !noDecode;
  50638. // Crypto is kind of old and crusty. Historically, its default string
  50639. // encoding is 'binary' so we have to make this configurable.
  50640. // Everything else in the universe uses 'utf8', though.
  50641. this.defaultEncoding = options.defaultEncoding || 'utf8';
  50642. // not an actual buffer we keep track of, but a measurement
  50643. // of how much we're waiting to get pushed to some underlying
  50644. // socket or file.
  50645. this.length = 0;
  50646. // a flag to see when we're in the middle of a write.
  50647. this.writing = false;
  50648. // when true all writes will be buffered until .uncork() call
  50649. this.corked = 0;
  50650. // a flag to be able to tell if the onwrite cb is called immediately,
  50651. // or on a later tick. We set this to true at first, because any
  50652. // actions that shouldn't happen until "later" should generally also
  50653. // not happen before the first write call.
  50654. this.sync = true;
  50655. // a flag to know if we're processing previously buffered items, which
  50656. // may call the _write() callback in the same tick, so that we don't
  50657. // end up in an overlapped onwrite situation.
  50658. this.bufferProcessing = false;
  50659. // the callback that's passed to _write(chunk,cb)
  50660. this.onwrite = function (er) {
  50661. onwrite(stream, er);
  50662. };
  50663. // the callback that the user supplies to write(chunk,encoding,cb)
  50664. this.writecb = null;
  50665. // the amount that is being written when _write is called.
  50666. this.writelen = 0;
  50667. this.bufferedRequest = null;
  50668. this.lastBufferedRequest = null;
  50669. // number of pending user-supplied write callbacks
  50670. // this must be 0 before 'finish' can be emitted
  50671. this.pendingcb = 0;
  50672. // emit prefinish if the only thing we're waiting for is _write cbs
  50673. // This is relevant for synchronous Transform streams
  50674. this.prefinished = false;
  50675. // True if the error was already emitted and should not be thrown again
  50676. this.errorEmitted = false;
  50677. // count buffered requests
  50678. this.bufferedRequestCount = 0;
  50679. // allocate the first CorkedRequest, there is always
  50680. // one allocated and free to use, and we maintain at most two
  50681. this.corkedRequestsFree = new CorkedRequest(this);
  50682. }
  50683. WritableState.prototype.getBuffer = function getBuffer() {
  50684. var current = this.bufferedRequest;
  50685. var out = [];
  50686. while (current) {
  50687. out.push(current);
  50688. current = current.next;
  50689. }
  50690. return out;
  50691. };
  50692. (function () {
  50693. try {
  50694. Object.defineProperty(WritableState.prototype, 'buffer', {
  50695. get: internalUtil.deprecate(function () {
  50696. return this.getBuffer();
  50697. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  50698. });
  50699. } catch (_) {}
  50700. })();
  50701. // Test _writableState for inheritance to account for Duplex streams,
  50702. // whose prototype chain only points to Readable.
  50703. var realHasInstance;
  50704. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  50705. realHasInstance = Function.prototype[Symbol.hasInstance];
  50706. Object.defineProperty(Writable, Symbol.hasInstance, {
  50707. value: function (object) {
  50708. if (realHasInstance.call(this, object)) return true;
  50709. if (this !== Writable) return false;
  50710. return object && object._writableState instanceof WritableState;
  50711. }
  50712. });
  50713. } else {
  50714. realHasInstance = function (object) {
  50715. return object instanceof this;
  50716. };
  50717. }
  50718. function Writable(options) {
  50719. Duplex = Duplex || require('./_stream_duplex');
  50720. // Writable ctor is applied to Duplexes, too.
  50721. // `realHasInstance` is necessary because using plain `instanceof`
  50722. // would return false, as no `_writableState` property is attached.
  50723. // Trying to use the custom `instanceof` for Writable here will also break the
  50724. // Node.js LazyTransform implementation, which has a non-trivial getter for
  50725. // `_writableState` that would lead to infinite recursion.
  50726. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  50727. return new Writable(options);
  50728. }
  50729. this._writableState = new WritableState(options, this);
  50730. // legacy.
  50731. this.writable = true;
  50732. if (options) {
  50733. if (typeof options.write === 'function') this._write = options.write;
  50734. if (typeof options.writev === 'function') this._writev = options.writev;
  50735. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  50736. if (typeof options.final === 'function') this._final = options.final;
  50737. }
  50738. Stream.call(this);
  50739. }
  50740. // Otherwise people can pipe Writable streams, which is just wrong.
  50741. Writable.prototype.pipe = function () {
  50742. this.emit('error', new Error('Cannot pipe, not readable'));
  50743. };
  50744. function writeAfterEnd(stream, cb) {
  50745. var er = new Error('write after end');
  50746. // TODO: defer error events consistently everywhere, not just the cb
  50747. stream.emit('error', er);
  50748. pna.nextTick(cb, er);
  50749. }
  50750. // Checks that a user-supplied chunk is valid, especially for the particular
  50751. // mode the stream is in. Currently this means that `null` is never accepted
  50752. // and undefined/non-string values are only allowed in object mode.
  50753. function validChunk(stream, state, chunk, cb) {
  50754. var valid = true;
  50755. var er = false;
  50756. if (chunk === null) {
  50757. er = new TypeError('May not write null values to stream');
  50758. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  50759. er = new TypeError('Invalid non-string/buffer chunk');
  50760. }
  50761. if (er) {
  50762. stream.emit('error', er);
  50763. pna.nextTick(cb, er);
  50764. valid = false;
  50765. }
  50766. return valid;
  50767. }
  50768. Writable.prototype.write = function (chunk, encoding, cb) {
  50769. var state = this._writableState;
  50770. var ret = false;
  50771. var isBuf = !state.objectMode && _isUint8Array(chunk);
  50772. if (isBuf && !Buffer.isBuffer(chunk)) {
  50773. chunk = _uint8ArrayToBuffer(chunk);
  50774. }
  50775. if (typeof encoding === 'function') {
  50776. cb = encoding;
  50777. encoding = null;
  50778. }
  50779. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  50780. if (typeof cb !== 'function') cb = nop;
  50781. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  50782. state.pendingcb++;
  50783. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  50784. }
  50785. return ret;
  50786. };
  50787. Writable.prototype.cork = function () {
  50788. var state = this._writableState;
  50789. state.corked++;
  50790. };
  50791. Writable.prototype.uncork = function () {
  50792. var state = this._writableState;
  50793. if (state.corked) {
  50794. state.corked--;
  50795. if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  50796. }
  50797. };
  50798. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  50799. // node::ParseEncoding() requires lower case.
  50800. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  50801. 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);
  50802. this._writableState.defaultEncoding = encoding;
  50803. return this;
  50804. };
  50805. function decodeChunk(state, chunk, encoding) {
  50806. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  50807. chunk = Buffer.from(chunk, encoding);
  50808. }
  50809. return chunk;
  50810. }
  50811. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  50812. // making it explicit this property is not enumerable
  50813. // because otherwise some prototype manipulation in
  50814. // userland will fail
  50815. enumerable: false,
  50816. get: function () {
  50817. return this._writableState.highWaterMark;
  50818. }
  50819. });
  50820. // if we're already writing something, then just put this
  50821. // in the queue, and wait our turn. Otherwise, call _write
  50822. // If we return false, then we need a drain event, so set that flag.
  50823. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  50824. if (!isBuf) {
  50825. var newChunk = decodeChunk(state, chunk, encoding);
  50826. if (chunk !== newChunk) {
  50827. isBuf = true;
  50828. encoding = 'buffer';
  50829. chunk = newChunk;
  50830. }
  50831. }
  50832. var len = state.objectMode ? 1 : chunk.length;
  50833. state.length += len;
  50834. var ret = state.length < state.highWaterMark;
  50835. // we must ensure that previous needDrain will not be reset to false.
  50836. if (!ret) state.needDrain = true;
  50837. if (state.writing || state.corked) {
  50838. var last = state.lastBufferedRequest;
  50839. state.lastBufferedRequest = {
  50840. chunk: chunk,
  50841. encoding: encoding,
  50842. isBuf: isBuf,
  50843. callback: cb,
  50844. next: null
  50845. };
  50846. if (last) {
  50847. last.next = state.lastBufferedRequest;
  50848. } else {
  50849. state.bufferedRequest = state.lastBufferedRequest;
  50850. }
  50851. state.bufferedRequestCount += 1;
  50852. } else {
  50853. doWrite(stream, state, false, len, chunk, encoding, cb);
  50854. }
  50855. return ret;
  50856. }
  50857. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  50858. state.writelen = len;
  50859. state.writecb = cb;
  50860. state.writing = true;
  50861. state.sync = true;
  50862. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  50863. state.sync = false;
  50864. }
  50865. function onwriteError(stream, state, sync, er, cb) {
  50866. --state.pendingcb;
  50867. if (sync) {
  50868. // defer the callback if we are being called synchronously
  50869. // to avoid piling up things on the stack
  50870. pna.nextTick(cb, er);
  50871. // this can emit finish, and it will always happen
  50872. // after error
  50873. pna.nextTick(finishMaybe, stream, state);
  50874. stream._writableState.errorEmitted = true;
  50875. stream.emit('error', er);
  50876. } else {
  50877. // the caller expect this to happen before if
  50878. // it is async
  50879. cb(er);
  50880. stream._writableState.errorEmitted = true;
  50881. stream.emit('error', er);
  50882. // this can emit finish, but finish must
  50883. // always follow error
  50884. finishMaybe(stream, state);
  50885. }
  50886. }
  50887. function onwriteStateUpdate(state) {
  50888. state.writing = false;
  50889. state.writecb = null;
  50890. state.length -= state.writelen;
  50891. state.writelen = 0;
  50892. }
  50893. function onwrite(stream, er) {
  50894. var state = stream._writableState;
  50895. var sync = state.sync;
  50896. var cb = state.writecb;
  50897. onwriteStateUpdate(state);
  50898. if (er) onwriteError(stream, state, sync, er, cb);else {
  50899. // Check if we're actually ready to finish, but don't emit yet
  50900. var finished = needFinish(state);
  50901. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  50902. clearBuffer(stream, state);
  50903. }
  50904. if (sync) {
  50905. /*<replacement>*/
  50906. asyncWrite(afterWrite, stream, state, finished, cb);
  50907. /*</replacement>*/
  50908. } else {
  50909. afterWrite(stream, state, finished, cb);
  50910. }
  50911. }
  50912. }
  50913. function afterWrite(stream, state, finished, cb) {
  50914. if (!finished) onwriteDrain(stream, state);
  50915. state.pendingcb--;
  50916. cb();
  50917. finishMaybe(stream, state);
  50918. }
  50919. // Must force callback to be called on nextTick, so that we don't
  50920. // emit 'drain' before the write() consumer gets the 'false' return
  50921. // value, and has a chance to attach a 'drain' listener.
  50922. function onwriteDrain(stream, state) {
  50923. if (state.length === 0 && state.needDrain) {
  50924. state.needDrain = false;
  50925. stream.emit('drain');
  50926. }
  50927. }
  50928. // if there's something in the buffer waiting, then process it
  50929. function clearBuffer(stream, state) {
  50930. state.bufferProcessing = true;
  50931. var entry = state.bufferedRequest;
  50932. if (stream._writev && entry && entry.next) {
  50933. // Fast case, write everything using _writev()
  50934. var l = state.bufferedRequestCount;
  50935. var buffer = new Array(l);
  50936. var holder = state.corkedRequestsFree;
  50937. holder.entry = entry;
  50938. var count = 0;
  50939. var allBuffers = true;
  50940. while (entry) {
  50941. buffer[count] = entry;
  50942. if (!entry.isBuf) allBuffers = false;
  50943. entry = entry.next;
  50944. count += 1;
  50945. }
  50946. buffer.allBuffers = allBuffers;
  50947. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  50948. // doWrite is almost always async, defer these to save a bit of time
  50949. // as the hot path ends with doWrite
  50950. state.pendingcb++;
  50951. state.lastBufferedRequest = null;
  50952. if (holder.next) {
  50953. state.corkedRequestsFree = holder.next;
  50954. holder.next = null;
  50955. } else {
  50956. state.corkedRequestsFree = new CorkedRequest(state);
  50957. }
  50958. state.bufferedRequestCount = 0;
  50959. } else {
  50960. // Slow case, write chunks one-by-one
  50961. while (entry) {
  50962. var chunk = entry.chunk;
  50963. var encoding = entry.encoding;
  50964. var cb = entry.callback;
  50965. var len = state.objectMode ? 1 : chunk.length;
  50966. doWrite(stream, state, false, len, chunk, encoding, cb);
  50967. entry = entry.next;
  50968. state.bufferedRequestCount--;
  50969. // if we didn't call the onwrite immediately, then
  50970. // it means that we need to wait until it does.
  50971. // also, that means that the chunk and cb are currently
  50972. // being processed, so move the buffer counter past them.
  50973. if (state.writing) {
  50974. break;
  50975. }
  50976. }
  50977. if (entry === null) state.lastBufferedRequest = null;
  50978. }
  50979. state.bufferedRequest = entry;
  50980. state.bufferProcessing = false;
  50981. }
  50982. Writable.prototype._write = function (chunk, encoding, cb) {
  50983. cb(new Error('_write() is not implemented'));
  50984. };
  50985. Writable.prototype._writev = null;
  50986. Writable.prototype.end = function (chunk, encoding, cb) {
  50987. var state = this._writableState;
  50988. if (typeof chunk === 'function') {
  50989. cb = chunk;
  50990. chunk = null;
  50991. encoding = null;
  50992. } else if (typeof encoding === 'function') {
  50993. cb = encoding;
  50994. encoding = null;
  50995. }
  50996. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  50997. // .end() fully uncorks
  50998. if (state.corked) {
  50999. state.corked = 1;
  51000. this.uncork();
  51001. }
  51002. // ignore unnecessary end() calls.
  51003. if (!state.ending) endWritable(this, state, cb);
  51004. };
  51005. function needFinish(state) {
  51006. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  51007. }
  51008. function callFinal(stream, state) {
  51009. stream._final(function (err) {
  51010. state.pendingcb--;
  51011. if (err) {
  51012. stream.emit('error', err);
  51013. }
  51014. state.prefinished = true;
  51015. stream.emit('prefinish');
  51016. finishMaybe(stream, state);
  51017. });
  51018. }
  51019. function prefinish(stream, state) {
  51020. if (!state.prefinished && !state.finalCalled) {
  51021. if (typeof stream._final === 'function') {
  51022. state.pendingcb++;
  51023. state.finalCalled = true;
  51024. pna.nextTick(callFinal, stream, state);
  51025. } else {
  51026. state.prefinished = true;
  51027. stream.emit('prefinish');
  51028. }
  51029. }
  51030. }
  51031. function finishMaybe(stream, state) {
  51032. var need = needFinish(state);
  51033. if (need) {
  51034. prefinish(stream, state);
  51035. if (state.pendingcb === 0) {
  51036. state.finished = true;
  51037. stream.emit('finish');
  51038. }
  51039. }
  51040. return need;
  51041. }
  51042. function endWritable(stream, state, cb) {
  51043. state.ending = true;
  51044. finishMaybe(stream, state);
  51045. if (cb) {
  51046. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  51047. }
  51048. state.ended = true;
  51049. stream.writable = false;
  51050. }
  51051. function onCorkedFinish(corkReq, state, err) {
  51052. var entry = corkReq.entry;
  51053. corkReq.entry = null;
  51054. while (entry) {
  51055. var cb = entry.callback;
  51056. state.pendingcb--;
  51057. cb(err);
  51058. entry = entry.next;
  51059. }
  51060. // reuse the free corkReq.
  51061. state.corkedRequestsFree.next = corkReq;
  51062. }
  51063. Object.defineProperty(Writable.prototype, 'destroyed', {
  51064. get: function () {
  51065. if (this._writableState === undefined) {
  51066. return false;
  51067. }
  51068. return this._writableState.destroyed;
  51069. },
  51070. set: function (value) {
  51071. // we ignore the value if the stream
  51072. // has not been initialized yet
  51073. if (!this._writableState) {
  51074. return;
  51075. }
  51076. // backward compatibility, the user is explicitly
  51077. // managing destroyed
  51078. this._writableState.destroyed = value;
  51079. }
  51080. });
  51081. Writable.prototype.destroy = destroyImpl.destroy;
  51082. Writable.prototype._undestroy = destroyImpl.undestroy;
  51083. Writable.prototype._destroy = function (err, cb) {
  51084. this.end();
  51085. cb(err);
  51086. };
  51087. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  51088. },{"./_stream_duplex":346,"./internal/streams/destroy":352,"./internal/streams/stream":353,"_process":306,"core-util-is":222,"inherits":279,"process-nextick-args":305,"safe-buffer":358,"timers":361,"util-deprecate":362}],351:[function(require,module,exports){
  51089. 'use strict';
  51090. function _classCallCheck(instance, Constructor) {
  51091. if (!(instance instanceof Constructor)) {
  51092. throw new TypeError("Cannot call a class as a function");
  51093. }
  51094. }
  51095. var Buffer = require('safe-buffer').Buffer;
  51096. var util = require('util');
  51097. function copyBuffer(src, target, offset) {
  51098. src.copy(target, offset);
  51099. }
  51100. module.exports = function () {
  51101. function BufferList() {
  51102. _classCallCheck(this, BufferList);
  51103. this.head = null;
  51104. this.tail = null;
  51105. this.length = 0;
  51106. }
  51107. BufferList.prototype.push = function push(v) {
  51108. var entry = {
  51109. data: v,
  51110. next: null
  51111. };
  51112. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  51113. this.tail = entry;
  51114. ++this.length;
  51115. };
  51116. BufferList.prototype.unshift = function unshift(v) {
  51117. var entry = {
  51118. data: v,
  51119. next: this.head
  51120. };
  51121. if (this.length === 0) this.tail = entry;
  51122. this.head = entry;
  51123. ++this.length;
  51124. };
  51125. BufferList.prototype.shift = function shift() {
  51126. if (this.length === 0) return;
  51127. var ret = this.head.data;
  51128. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  51129. --this.length;
  51130. return ret;
  51131. };
  51132. BufferList.prototype.clear = function clear() {
  51133. this.head = this.tail = null;
  51134. this.length = 0;
  51135. };
  51136. BufferList.prototype.join = function join(s) {
  51137. if (this.length === 0) return '';
  51138. var p = this.head;
  51139. var ret = '' + p.data;
  51140. while (p = p.next) {
  51141. ret += s + p.data;
  51142. }
  51143. return ret;
  51144. };
  51145. BufferList.prototype.concat = function concat(n) {
  51146. if (this.length === 0) return Buffer.alloc(0);
  51147. var ret = Buffer.allocUnsafe(n >>> 0);
  51148. var p = this.head;
  51149. var i = 0;
  51150. while (p) {
  51151. copyBuffer(p.data, ret, i);
  51152. i += p.data.length;
  51153. p = p.next;
  51154. }
  51155. return ret;
  51156. };
  51157. return BufferList;
  51158. }();
  51159. if (util && util.inspect && util.inspect.custom) {
  51160. module.exports.prototype[util.inspect.custom] = function () {
  51161. var obj = util.inspect({
  51162. length: this.length
  51163. });
  51164. return this.constructor.name + ' ' + obj;
  51165. };
  51166. }
  51167. },{"safe-buffer":358,"util":188}],352:[function(require,module,exports){
  51168. 'use strict';
  51169. /*<replacement>*/
  51170. var pna = require('process-nextick-args');
  51171. /*</replacement>*/
  51172. // undocumented cb() API, needed for core, not for public API
  51173. function destroy(err, cb) {
  51174. var _this = this;
  51175. var readableDestroyed = this._readableState && this._readableState.destroyed;
  51176. var writableDestroyed = this._writableState && this._writableState.destroyed;
  51177. if (readableDestroyed || writableDestroyed) {
  51178. if (cb) {
  51179. cb(err);
  51180. } else if (err) {
  51181. if (!this._writableState) {
  51182. pna.nextTick(emitErrorNT, this, err);
  51183. } else if (!this._writableState.errorEmitted) {
  51184. this._writableState.errorEmitted = true;
  51185. pna.nextTick(emitErrorNT, this, err);
  51186. }
  51187. }
  51188. return this;
  51189. }
  51190. // we set destroyed to true before firing error callbacks in order
  51191. // to make it re-entrance safe in case destroy() is called within callbacks
  51192. if (this._readableState) {
  51193. this._readableState.destroyed = true;
  51194. }
  51195. // if this is a duplex stream mark the writable part as destroyed as well
  51196. if (this._writableState) {
  51197. this._writableState.destroyed = true;
  51198. }
  51199. this._destroy(err || null, function (err) {
  51200. if (!cb && err) {
  51201. if (!_this._writableState) {
  51202. pna.nextTick(emitErrorNT, _this, err);
  51203. } else if (!_this._writableState.errorEmitted) {
  51204. _this._writableState.errorEmitted = true;
  51205. pna.nextTick(emitErrorNT, _this, err);
  51206. }
  51207. } else if (cb) {
  51208. cb(err);
  51209. }
  51210. });
  51211. return this;
  51212. }
  51213. function undestroy() {
  51214. if (this._readableState) {
  51215. this._readableState.destroyed = false;
  51216. this._readableState.reading = false;
  51217. this._readableState.ended = false;
  51218. this._readableState.endEmitted = false;
  51219. }
  51220. if (this._writableState) {
  51221. this._writableState.destroyed = false;
  51222. this._writableState.ended = false;
  51223. this._writableState.ending = false;
  51224. this._writableState.finalCalled = false;
  51225. this._writableState.prefinished = false;
  51226. this._writableState.finished = false;
  51227. this._writableState.errorEmitted = false;
  51228. }
  51229. }
  51230. function emitErrorNT(self, err) {
  51231. self.emit('error', err);
  51232. }
  51233. module.exports = {
  51234. destroy: destroy,
  51235. undestroy: undestroy
  51236. };
  51237. },{"process-nextick-args":305}],353:[function(require,module,exports){
  51238. arguments[4][329][0].apply(exports,arguments)
  51239. },{"dup":329,"events":261}],354:[function(require,module,exports){
  51240. "use strict";
  51241. module.exports = require('./readable').PassThrough;
  51242. },{"./readable":355}],355:[function(require,module,exports){
  51243. "use strict";
  51244. exports = module.exports = require('./lib/_stream_readable.js');
  51245. exports.Stream = exports;
  51246. exports.Readable = exports;
  51247. exports.Writable = require('./lib/_stream_writable.js');
  51248. exports.Duplex = require('./lib/_stream_duplex.js');
  51249. exports.Transform = require('./lib/_stream_transform.js');
  51250. exports.PassThrough = require('./lib/_stream_passthrough.js');
  51251. },{"./lib/_stream_duplex.js":346,"./lib/_stream_passthrough.js":347,"./lib/_stream_readable.js":348,"./lib/_stream_transform.js":349,"./lib/_stream_writable.js":350}],356:[function(require,module,exports){
  51252. "use strict";
  51253. module.exports = require('./readable').Transform;
  51254. },{"./readable":355}],357:[function(require,module,exports){
  51255. "use strict";
  51256. module.exports = require('./lib/_stream_writable.js');
  51257. },{"./lib/_stream_writable.js":350}],358:[function(require,module,exports){
  51258. arguments[4][217][0].apply(exports,arguments)
  51259. },{"buffer":220,"dup":217}],359:[function(require,module,exports){
  51260. arguments[4][218][0].apply(exports,arguments)
  51261. },{"dup":218,"safe-buffer":358}],360:[function(require,module,exports){
  51262. arguments[4][218][0].apply(exports,arguments)
  51263. },{"dup":218,"safe-buffer":332}],361:[function(require,module,exports){
  51264. (function (setImmediate,clearImmediate){(function (){
  51265. "use strict";
  51266. var nextTick = require('process/browser.js').nextTick;
  51267. var apply = Function.prototype.apply;
  51268. var slice = Array.prototype.slice;
  51269. var immediateIds = {};
  51270. var nextImmediateId = 0;
  51271. // DOM APIs, for completeness
  51272. exports.setTimeout = function () {
  51273. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  51274. };
  51275. exports.setInterval = function () {
  51276. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  51277. };
  51278. exports.clearTimeout = exports.clearInterval = function (timeout) {
  51279. timeout.close();
  51280. };
  51281. function Timeout(id, clearFn) {
  51282. this._id = id;
  51283. this._clearFn = clearFn;
  51284. }
  51285. Timeout.prototype.unref = Timeout.prototype.ref = function () {};
  51286. Timeout.prototype.close = function () {
  51287. this._clearFn.call(window, this._id);
  51288. };
  51289. // Does not start the time, just sets up the members needed.
  51290. exports.enroll = function (item, msecs) {
  51291. clearTimeout(item._idleTimeoutId);
  51292. item._idleTimeout = msecs;
  51293. };
  51294. exports.unenroll = function (item) {
  51295. clearTimeout(item._idleTimeoutId);
  51296. item._idleTimeout = -1;
  51297. };
  51298. exports._unrefActive = exports.active = function (item) {
  51299. clearTimeout(item._idleTimeoutId);
  51300. var msecs = item._idleTimeout;
  51301. if (msecs >= 0) {
  51302. item._idleTimeoutId = setTimeout(function onTimeout() {
  51303. if (item._onTimeout) item._onTimeout();
  51304. }, msecs);
  51305. }
  51306. };
  51307. // That's not how node.js implements it but the exposed api is the same.
  51308. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function (fn) {
  51309. var id = nextImmediateId++;
  51310. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  51311. immediateIds[id] = true;
  51312. nextTick(function onNextTick() {
  51313. if (immediateIds[id]) {
  51314. // fn.call() is faster so we optimize for the common use-case
  51315. // @see http://jsperf.com/call-apply-segu
  51316. if (args) {
  51317. fn.apply(null, args);
  51318. } else {
  51319. fn.call(null);
  51320. }
  51321. // Prevent ids from leaking
  51322. exports.clearImmediate(id);
  51323. }
  51324. });
  51325. return id;
  51326. };
  51327. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function (id) {
  51328. delete immediateIds[id];
  51329. };
  51330. }).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  51331. },{"process/browser.js":306,"timers":361}],362:[function(require,module,exports){
  51332. (function (global){(function (){
  51333. "use strict";
  51334. /**
  51335. * Module exports.
  51336. */
  51337. module.exports = deprecate;
  51338. /**
  51339. * Mark that a method should not be used.
  51340. * Returns a modified function which warns once by default.
  51341. *
  51342. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  51343. *
  51344. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  51345. * will throw an Error when invoked.
  51346. *
  51347. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  51348. * will invoke `console.trace()` instead of `console.error()`.
  51349. *
  51350. * @param {Function} fn - the function to deprecate
  51351. * @param {String} msg - the string to print to the console when `fn` is invoked
  51352. * @returns {Function} a new "deprecated" version of `fn`
  51353. * @api public
  51354. */
  51355. function deprecate(fn, msg) {
  51356. if (config('noDeprecation')) {
  51357. return fn;
  51358. }
  51359. var warned = false;
  51360. function deprecated() {
  51361. if (!warned) {
  51362. if (config('throwDeprecation')) {
  51363. throw new Error(msg);
  51364. } else if (config('traceDeprecation')) {
  51365. console.trace(msg);
  51366. } else {
  51367. console.warn(msg);
  51368. }
  51369. warned = true;
  51370. }
  51371. return fn.apply(this, arguments);
  51372. }
  51373. return deprecated;
  51374. }
  51375. /**
  51376. * Checks `localStorage` for boolean values for the given `name`.
  51377. *
  51378. * @param {String} name
  51379. * @returns {Boolean}
  51380. * @api private
  51381. */
  51382. function config(name) {
  51383. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  51384. try {
  51385. if (!global.localStorage) return false;
  51386. } catch (_) {
  51387. return false;
  51388. }
  51389. var val = global.localStorage[name];
  51390. if (null == val) return false;
  51391. return String(val).toLowerCase() === 'true';
  51392. }
  51393. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  51394. },{}],363:[function(require,module,exports){
  51395. "use strict";
  51396. if (typeof Object.create === 'function') {
  51397. // implementation from standard node.js 'util' module
  51398. module.exports = function inherits(ctor, superCtor) {
  51399. ctor.super_ = superCtor;
  51400. ctor.prototype = Object.create(superCtor.prototype, {
  51401. constructor: {
  51402. value: ctor,
  51403. enumerable: false,
  51404. writable: true,
  51405. configurable: true
  51406. }
  51407. });
  51408. };
  51409. } else {
  51410. // old school shim for old browsers
  51411. module.exports = function inherits(ctor, superCtor) {
  51412. ctor.super_ = superCtor;
  51413. var TempCtor = function () {};
  51414. TempCtor.prototype = superCtor.prototype;
  51415. ctor.prototype = new TempCtor();
  51416. ctor.prototype.constructor = ctor;
  51417. };
  51418. }
  51419. },{}],364:[function(require,module,exports){
  51420. "use strict";
  51421. module.exports = function isBuffer(arg) {
  51422. return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function';
  51423. };
  51424. },{}],365:[function(require,module,exports){
  51425. (function (process,global){(function (){
  51426. "use strict";
  51427. // Copyright Joyent, Inc. and other Node contributors.
  51428. //
  51429. // Permission is hereby granted, free of charge, to any person obtaining a
  51430. // copy of this software and associated documentation files (the
  51431. // "Software"), to deal in the Software without restriction, including
  51432. // without limitation the rights to use, copy, modify, merge, publish,
  51433. // distribute, sublicense, and/or sell copies of the Software, and to permit
  51434. // persons to whom the Software is furnished to do so, subject to the
  51435. // following conditions:
  51436. //
  51437. // The above copyright notice and this permission notice shall be included
  51438. // in all copies or substantial portions of the Software.
  51439. //
  51440. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  51441. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  51442. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  51443. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  51444. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  51445. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  51446. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  51447. var formatRegExp = /%[sdj%]/g;
  51448. exports.format = function (f) {
  51449. if (!isString(f)) {
  51450. var objects = [];
  51451. for (var i = 0; i < arguments.length; i++) {
  51452. objects.push(inspect(arguments[i]));
  51453. }
  51454. return objects.join(' ');
  51455. }
  51456. var i = 1;
  51457. var args = arguments;
  51458. var len = args.length;
  51459. var str = String(f).replace(formatRegExp, function (x) {
  51460. if (x === '%%') return '%';
  51461. if (i >= len) return x;
  51462. switch (x) {
  51463. case '%s':
  51464. return String(args[i++]);
  51465. case '%d':
  51466. return Number(args[i++]);
  51467. case '%j':
  51468. try {
  51469. return JSON.stringify(args[i++]);
  51470. } catch (_) {
  51471. return '[Circular]';
  51472. }
  51473. default:
  51474. return x;
  51475. }
  51476. });
  51477. for (var x = args[i]; i < len; x = args[++i]) {
  51478. if (isNull(x) || !isObject(x)) {
  51479. str += ' ' + x;
  51480. } else {
  51481. str += ' ' + inspect(x);
  51482. }
  51483. }
  51484. return str;
  51485. };
  51486. // Mark that a method should not be used.
  51487. // Returns a modified function which warns once by default.
  51488. // If --no-deprecation is set, then it is a no-op.
  51489. exports.deprecate = function (fn, msg) {
  51490. // Allow for deprecating things in the process of starting up.
  51491. if (isUndefined(global.process)) {
  51492. return function () {
  51493. return exports.deprecate(fn, msg).apply(this, arguments);
  51494. };
  51495. }
  51496. if (process.noDeprecation === true) {
  51497. return fn;
  51498. }
  51499. var warned = false;
  51500. function deprecated() {
  51501. if (!warned) {
  51502. if (process.throwDeprecation) {
  51503. throw new Error(msg);
  51504. } else if (process.traceDeprecation) {
  51505. console.trace(msg);
  51506. } else {
  51507. console.error(msg);
  51508. }
  51509. warned = true;
  51510. }
  51511. return fn.apply(this, arguments);
  51512. }
  51513. return deprecated;
  51514. };
  51515. var debugs = {};
  51516. var debugEnviron;
  51517. exports.debuglog = function (set) {
  51518. if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || '';
  51519. set = set.toUpperCase();
  51520. if (!debugs[set]) {
  51521. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  51522. var pid = process.pid;
  51523. debugs[set] = function () {
  51524. var msg = exports.format.apply(exports, arguments);
  51525. console.error('%s %d: %s', set, pid, msg);
  51526. };
  51527. } else {
  51528. debugs[set] = function () {};
  51529. }
  51530. }
  51531. return debugs[set];
  51532. };
  51533. /**
  51534. * Echos the value of a value. Trys to print the value out
  51535. * in the best way possible given the different types.
  51536. *
  51537. * @param {Object} obj The object to print out.
  51538. * @param {Object} opts Optional options object that alters the output.
  51539. */
  51540. /* legacy: obj, showHidden, depth, colors*/
  51541. function inspect(obj, opts) {
  51542. // default options
  51543. var ctx = {
  51544. seen: [],
  51545. stylize: stylizeNoColor
  51546. };
  51547. // legacy...
  51548. if (arguments.length >= 3) ctx.depth = arguments[2];
  51549. if (arguments.length >= 4) ctx.colors = arguments[3];
  51550. if (isBoolean(opts)) {
  51551. // legacy...
  51552. ctx.showHidden = opts;
  51553. } else if (opts) {
  51554. // got an "options" object
  51555. exports._extend(ctx, opts);
  51556. }
  51557. // set default options
  51558. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  51559. if (isUndefined(ctx.depth)) ctx.depth = 2;
  51560. if (isUndefined(ctx.colors)) ctx.colors = false;
  51561. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  51562. if (ctx.colors) ctx.stylize = stylizeWithColor;
  51563. return formatValue(ctx, obj, ctx.depth);
  51564. }
  51565. exports.inspect = inspect;
  51566. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  51567. inspect.colors = {
  51568. 'bold': [1, 22],
  51569. 'italic': [3, 23],
  51570. 'underline': [4, 24],
  51571. 'inverse': [7, 27],
  51572. 'white': [37, 39],
  51573. 'grey': [90, 39],
  51574. 'black': [30, 39],
  51575. 'blue': [34, 39],
  51576. 'cyan': [36, 39],
  51577. 'green': [32, 39],
  51578. 'magenta': [35, 39],
  51579. 'red': [31, 39],
  51580. 'yellow': [33, 39]
  51581. };
  51582. // Don't use 'blue' not visible on cmd.exe
  51583. inspect.styles = {
  51584. 'special': 'cyan',
  51585. 'number': 'yellow',
  51586. 'boolean': 'yellow',
  51587. 'undefined': 'grey',
  51588. 'null': 'bold',
  51589. 'string': 'green',
  51590. 'date': 'magenta',
  51591. // "name": intentionally not styling
  51592. 'regexp': 'red'
  51593. };
  51594. function stylizeWithColor(str, styleType) {
  51595. var style = inspect.styles[styleType];
  51596. if (style) {
  51597. return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm';
  51598. } else {
  51599. return str;
  51600. }
  51601. }
  51602. function stylizeNoColor(str, styleType) {
  51603. return str;
  51604. }
  51605. function arrayToHash(array) {
  51606. var hash = {};
  51607. array.forEach(function (val, idx) {
  51608. hash[val] = true;
  51609. });
  51610. return hash;
  51611. }
  51612. function formatValue(ctx, value, recurseTimes) {
  51613. // Provide a hook for user-specified inspect functions.
  51614. // Check that value is an object with an inspect function on it
  51615. if (ctx.customInspect && value && isFunction(value.inspect) &&
  51616. // Filter out the util module, it's inspect function is special
  51617. value.inspect !== exports.inspect &&
  51618. // Also filter out any prototype objects using the circular check.
  51619. !(value.constructor && value.constructor.prototype === value)) {
  51620. var ret = value.inspect(recurseTimes, ctx);
  51621. if (!isString(ret)) {
  51622. ret = formatValue(ctx, ret, recurseTimes);
  51623. }
  51624. return ret;
  51625. }
  51626. // Primitive types cannot have properties
  51627. var primitive = formatPrimitive(ctx, value);
  51628. if (primitive) {
  51629. return primitive;
  51630. }
  51631. // Look up the keys of the object.
  51632. var keys = Object.keys(value);
  51633. var visibleKeys = arrayToHash(keys);
  51634. if (ctx.showHidden) {
  51635. keys = Object.getOwnPropertyNames(value);
  51636. }
  51637. // IE doesn't make error fields non-enumerable
  51638. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  51639. if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  51640. return formatError(value);
  51641. }
  51642. // Some type of object without properties can be shortcutted.
  51643. if (keys.length === 0) {
  51644. if (isFunction(value)) {
  51645. var name = value.name ? ': ' + value.name : '';
  51646. return ctx.stylize('[Function' + name + ']', 'special');
  51647. }
  51648. if (isRegExp(value)) {
  51649. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  51650. }
  51651. if (isDate(value)) {
  51652. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  51653. }
  51654. if (isError(value)) {
  51655. return formatError(value);
  51656. }
  51657. }
  51658. var base = '',
  51659. array = false,
  51660. braces = ['{', '}'];
  51661. // Make Array say that they are Array
  51662. if (isArray(value)) {
  51663. array = true;
  51664. braces = ['[', ']'];
  51665. }
  51666. // Make functions say that they are functions
  51667. if (isFunction(value)) {
  51668. var n = value.name ? ': ' + value.name : '';
  51669. base = ' [Function' + n + ']';
  51670. }
  51671. // Make RegExps say that they are RegExps
  51672. if (isRegExp(value)) {
  51673. base = ' ' + RegExp.prototype.toString.call(value);
  51674. }
  51675. // Make dates with properties first say the date
  51676. if (isDate(value)) {
  51677. base = ' ' + Date.prototype.toUTCString.call(value);
  51678. }
  51679. // Make error with message first say the error
  51680. if (isError(value)) {
  51681. base = ' ' + formatError(value);
  51682. }
  51683. if (keys.length === 0 && (!array || value.length == 0)) {
  51684. return braces[0] + base + braces[1];
  51685. }
  51686. if (recurseTimes < 0) {
  51687. if (isRegExp(value)) {
  51688. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  51689. } else {
  51690. return ctx.stylize('[Object]', 'special');
  51691. }
  51692. }
  51693. ctx.seen.push(value);
  51694. var output;
  51695. if (array) {
  51696. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  51697. } else {
  51698. output = keys.map(function (key) {
  51699. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  51700. });
  51701. }
  51702. ctx.seen.pop();
  51703. return reduceToSingleString(output, base, braces);
  51704. }
  51705. function formatPrimitive(ctx, value) {
  51706. if (isUndefined(value)) return ctx.stylize('undefined', 'undefined');
  51707. if (isString(value)) {
  51708. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\'';
  51709. return ctx.stylize(simple, 'string');
  51710. }
  51711. if (isNumber(value)) return ctx.stylize('' + value, 'number');
  51712. if (isBoolean(value)) return ctx.stylize('' + value, 'boolean');
  51713. // For some reason typeof null is "object", so special case here.
  51714. if (isNull(value)) return ctx.stylize('null', 'null');
  51715. }
  51716. function formatError(value) {
  51717. return '[' + Error.prototype.toString.call(value) + ']';
  51718. }
  51719. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  51720. var output = [];
  51721. for (var i = 0, l = value.length; i < l; ++i) {
  51722. if (hasOwnProperty(value, String(i))) {
  51723. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
  51724. } else {
  51725. output.push('');
  51726. }
  51727. }
  51728. keys.forEach(function (key) {
  51729. if (!key.match(/^\d+$/)) {
  51730. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
  51731. }
  51732. });
  51733. return output;
  51734. }
  51735. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  51736. var name, str, desc;
  51737. desc = Object.getOwnPropertyDescriptor(value, key) || {
  51738. value: value[key]
  51739. };
  51740. if (desc.get) {
  51741. if (desc.set) {
  51742. str = ctx.stylize('[Getter/Setter]', 'special');
  51743. } else {
  51744. str = ctx.stylize('[Getter]', 'special');
  51745. }
  51746. } else {
  51747. if (desc.set) {
  51748. str = ctx.stylize('[Setter]', 'special');
  51749. }
  51750. }
  51751. if (!hasOwnProperty(visibleKeys, key)) {
  51752. name = '[' + key + ']';
  51753. }
  51754. if (!str) {
  51755. if (ctx.seen.indexOf(desc.value) < 0) {
  51756. if (isNull(recurseTimes)) {
  51757. str = formatValue(ctx, desc.value, null);
  51758. } else {
  51759. str = formatValue(ctx, desc.value, recurseTimes - 1);
  51760. }
  51761. if (str.indexOf('\n') > -1) {
  51762. if (array) {
  51763. str = str.split('\n').map(function (line) {
  51764. return ' ' + line;
  51765. }).join('\n').substr(2);
  51766. } else {
  51767. str = '\n' + str.split('\n').map(function (line) {
  51768. return ' ' + line;
  51769. }).join('\n');
  51770. }
  51771. }
  51772. } else {
  51773. str = ctx.stylize('[Circular]', 'special');
  51774. }
  51775. }
  51776. if (isUndefined(name)) {
  51777. if (array && key.match(/^\d+$/)) {
  51778. return str;
  51779. }
  51780. name = JSON.stringify('' + key);
  51781. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  51782. name = name.substr(1, name.length - 2);
  51783. name = ctx.stylize(name, 'name');
  51784. } else {
  51785. name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
  51786. name = ctx.stylize(name, 'string');
  51787. }
  51788. }
  51789. return name + ': ' + str;
  51790. }
  51791. function reduceToSingleString(output, base, braces) {
  51792. var numLinesEst = 0;
  51793. var length = output.reduce(function (prev, cur) {
  51794. numLinesEst++;
  51795. if (cur.indexOf('\n') >= 0) numLinesEst++;
  51796. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  51797. }, 0);
  51798. if (length > 60) {
  51799. return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1];
  51800. }
  51801. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  51802. }
  51803. // NOTE: These type checking functions intentionally don't use `instanceof`
  51804. // because it is fragile and can be easily faked with `Object.create()`.
  51805. function isArray(ar) {
  51806. return Array.isArray(ar);
  51807. }
  51808. exports.isArray = isArray;
  51809. function isBoolean(arg) {
  51810. return typeof arg === 'boolean';
  51811. }
  51812. exports.isBoolean = isBoolean;
  51813. function isNull(arg) {
  51814. return arg === null;
  51815. }
  51816. exports.isNull = isNull;
  51817. function isNullOrUndefined(arg) {
  51818. return arg == null;
  51819. }
  51820. exports.isNullOrUndefined = isNullOrUndefined;
  51821. function isNumber(arg) {
  51822. return typeof arg === 'number';
  51823. }
  51824. exports.isNumber = isNumber;
  51825. function isString(arg) {
  51826. return typeof arg === 'string';
  51827. }
  51828. exports.isString = isString;
  51829. function isSymbol(arg) {
  51830. return typeof arg === 'symbol';
  51831. }
  51832. exports.isSymbol = isSymbol;
  51833. function isUndefined(arg) {
  51834. return arg === void 0;
  51835. }
  51836. exports.isUndefined = isUndefined;
  51837. function isRegExp(re) {
  51838. return isObject(re) && objectToString(re) === '[object RegExp]';
  51839. }
  51840. exports.isRegExp = isRegExp;
  51841. function isObject(arg) {
  51842. return typeof arg === 'object' && arg !== null;
  51843. }
  51844. exports.isObject = isObject;
  51845. function isDate(d) {
  51846. return isObject(d) && objectToString(d) === '[object Date]';
  51847. }
  51848. exports.isDate = isDate;
  51849. function isError(e) {
  51850. return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error);
  51851. }
  51852. exports.isError = isError;
  51853. function isFunction(arg) {
  51854. return typeof arg === 'function';
  51855. }
  51856. exports.isFunction = isFunction;
  51857. function isPrimitive(arg) {
  51858. return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' ||
  51859. // ES6 symbol
  51860. typeof arg === 'undefined';
  51861. }
  51862. exports.isPrimitive = isPrimitive;
  51863. exports.isBuffer = require('./support/isBuffer');
  51864. function objectToString(o) {
  51865. return Object.prototype.toString.call(o);
  51866. }
  51867. function pad(n) {
  51868. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  51869. }
  51870. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  51871. // 26 Feb 16:19:34
  51872. function timestamp() {
  51873. var d = new Date();
  51874. var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':');
  51875. return [d.getDate(), months[d.getMonth()], time].join(' ');
  51876. }
  51877. // log is just a thin wrapper to console.log that prepends a timestamp
  51878. exports.log = function () {
  51879. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  51880. };
  51881. /**
  51882. * Inherit the prototype methods from one constructor into another.
  51883. *
  51884. * The Function.prototype.inherits from lang.js rewritten as a standalone
  51885. * function (not on Function.prototype). NOTE: If this file is to be loaded
  51886. * during bootstrapping this function needs to be rewritten using some native
  51887. * functions as prototype setup using normal JavaScript does not work as
  51888. * expected during bootstrapping (see mirror.js in r114903).
  51889. *
  51890. * @param {function} ctor Constructor function which needs to inherit the
  51891. * prototype.
  51892. * @param {function} superCtor Constructor function to inherit prototype from.
  51893. */
  51894. exports.inherits = require('inherits');
  51895. exports._extend = function (origin, add) {
  51896. // Don't do anything if add isn't an object
  51897. if (!add || !isObject(add)) return origin;
  51898. var keys = Object.keys(add);
  51899. var i = keys.length;
  51900. while (i--) {
  51901. origin[keys[i]] = add[keys[i]];
  51902. }
  51903. return origin;
  51904. };
  51905. function hasOwnProperty(obj, prop) {
  51906. return Object.prototype.hasOwnProperty.call(obj, prop);
  51907. }
  51908. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  51909. },{"./support/isBuffer":364,"_process":306,"inherits":363}],366:[function(require,module,exports){
  51910. "use strict";
  51911. Object.defineProperty(exports, "__esModule", {
  51912. value: true
  51913. });
  51914. Object.defineProperty(exports, "v1", {
  51915. enumerable: true,
  51916. get: function () {
  51917. return _v.default;
  51918. }
  51919. });
  51920. Object.defineProperty(exports, "v3", {
  51921. enumerable: true,
  51922. get: function () {
  51923. return _v2.default;
  51924. }
  51925. });
  51926. Object.defineProperty(exports, "v4", {
  51927. enumerable: true,
  51928. get: function () {
  51929. return _v3.default;
  51930. }
  51931. });
  51932. Object.defineProperty(exports, "v5", {
  51933. enumerable: true,
  51934. get: function () {
  51935. return _v4.default;
  51936. }
  51937. });
  51938. Object.defineProperty(exports, "NIL", {
  51939. enumerable: true,
  51940. get: function () {
  51941. return _nil.default;
  51942. }
  51943. });
  51944. Object.defineProperty(exports, "version", {
  51945. enumerable: true,
  51946. get: function () {
  51947. return _version.default;
  51948. }
  51949. });
  51950. Object.defineProperty(exports, "validate", {
  51951. enumerable: true,
  51952. get: function () {
  51953. return _validate.default;
  51954. }
  51955. });
  51956. Object.defineProperty(exports, "stringify", {
  51957. enumerable: true,
  51958. get: function () {
  51959. return _stringify.default;
  51960. }
  51961. });
  51962. Object.defineProperty(exports, "parse", {
  51963. enumerable: true,
  51964. get: function () {
  51965. return _parse.default;
  51966. }
  51967. });
  51968. var _v = _interopRequireDefault(require("./v1.js"));
  51969. var _v2 = _interopRequireDefault(require("./v3.js"));
  51970. var _v3 = _interopRequireDefault(require("./v4.js"));
  51971. var _v4 = _interopRequireDefault(require("./v5.js"));
  51972. var _nil = _interopRequireDefault(require("./nil.js"));
  51973. var _version = _interopRequireDefault(require("./version.js"));
  51974. var _validate = _interopRequireDefault(require("./validate.js"));
  51975. var _stringify = _interopRequireDefault(require("./stringify.js"));
  51976. var _parse = _interopRequireDefault(require("./parse.js"));
  51977. function _interopRequireDefault(obj) {
  51978. return obj && obj.__esModule ? obj : {
  51979. default: obj
  51980. };
  51981. }
  51982. },{"./nil.js":368,"./parse.js":369,"./stringify.js":373,"./v1.js":374,"./v3.js":375,"./v4.js":377,"./v5.js":378,"./validate.js":379,"./version.js":380}],367:[function(require,module,exports){
  51983. "use strict";
  51984. Object.defineProperty(exports, "__esModule", {
  51985. value: true
  51986. });
  51987. exports.default = void 0;
  51988. /*
  51989. * Browser-compatible JavaScript MD5
  51990. *
  51991. * Modification of JavaScript MD5
  51992. * https://github.com/blueimp/JavaScript-MD5
  51993. *
  51994. * Copyright 2011, Sebastian Tschan
  51995. * https://blueimp.net
  51996. *
  51997. * Licensed under the MIT license:
  51998. * https://opensource.org/licenses/MIT
  51999. *
  52000. * Based on
  52001. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  52002. * Digest Algorithm, as defined in RFC 1321.
  52003. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
  52004. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  52005. * Distributed under the BSD License
  52006. * See http://pajhome.org.uk/crypt/md5 for more info.
  52007. */
  52008. function md5(bytes) {
  52009. if (typeof bytes === 'string') {
  52010. const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  52011. bytes = new Uint8Array(msg.length);
  52012. for (let i = 0; i < msg.length; ++i) {
  52013. bytes[i] = msg.charCodeAt(i);
  52014. }
  52015. }
  52016. return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
  52017. }
  52018. /*
  52019. * Convert an array of little-endian words to an array of bytes
  52020. */
  52021. function md5ToHexEncodedArray(input) {
  52022. const output = [];
  52023. const length32 = input.length * 32;
  52024. const hexTab = '0123456789abcdef';
  52025. for (let i = 0; i < length32; i += 8) {
  52026. const x = input[i >> 5] >>> i % 32 & 0xff;
  52027. const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
  52028. output.push(hex);
  52029. }
  52030. return output;
  52031. }
  52032. /**
  52033. * Calculate output length with padding and bit length
  52034. */
  52035. function getOutputLength(inputLength8) {
  52036. return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
  52037. }
  52038. /*
  52039. * Calculate the MD5 of an array of little-endian words, and a bit length.
  52040. */
  52041. function wordsToMd5(x, len) {
  52042. /* append padding */
  52043. x[len >> 5] |= 0x80 << len % 32;
  52044. x[getOutputLength(len) - 1] = len;
  52045. let a = 1732584193;
  52046. let b = -271733879;
  52047. let c = -1732584194;
  52048. let d = 271733878;
  52049. for (let i = 0; i < x.length; i += 16) {
  52050. const olda = a;
  52051. const oldb = b;
  52052. const oldc = c;
  52053. const oldd = d;
  52054. a = md5ff(a, b, c, d, x[i], 7, -680876936);
  52055. d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
  52056. c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
  52057. b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
  52058. a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
  52059. d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
  52060. c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
  52061. b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
  52062. a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
  52063. d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
  52064. c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
  52065. b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
  52066. a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
  52067. d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
  52068. c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
  52069. b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
  52070. a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
  52071. d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
  52072. c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
  52073. b = md5gg(b, c, d, a, x[i], 20, -373897302);
  52074. a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
  52075. d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
  52076. c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
  52077. b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
  52078. a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
  52079. d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
  52080. c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
  52081. b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
  52082. a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
  52083. d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
  52084. c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
  52085. b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
  52086. a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
  52087. d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
  52088. c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
  52089. b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
  52090. a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
  52091. d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
  52092. c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
  52093. b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
  52094. a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
  52095. d = md5hh(d, a, b, c, x[i], 11, -358537222);
  52096. c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
  52097. b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
  52098. a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
  52099. d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
  52100. c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
  52101. b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
  52102. a = md5ii(a, b, c, d, x[i], 6, -198630844);
  52103. d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
  52104. c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
  52105. b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
  52106. a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
  52107. d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
  52108. c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
  52109. b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
  52110. a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
  52111. d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
  52112. c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
  52113. b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
  52114. a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
  52115. d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
  52116. c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
  52117. b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
  52118. a = safeAdd(a, olda);
  52119. b = safeAdd(b, oldb);
  52120. c = safeAdd(c, oldc);
  52121. d = safeAdd(d, oldd);
  52122. }
  52123. return [a, b, c, d];
  52124. }
  52125. /*
  52126. * Convert an array bytes to an array of little-endian words
  52127. * Characters >255 have their high-byte silently ignored.
  52128. */
  52129. function bytesToWords(input) {
  52130. if (input.length === 0) {
  52131. return [];
  52132. }
  52133. const length8 = input.length * 8;
  52134. const output = new Uint32Array(getOutputLength(length8));
  52135. for (let i = 0; i < length8; i += 8) {
  52136. output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
  52137. }
  52138. return output;
  52139. }
  52140. /*
  52141. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  52142. * to work around bugs in some JS interpreters.
  52143. */
  52144. function safeAdd(x, y) {
  52145. const lsw = (x & 0xffff) + (y & 0xffff);
  52146. const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  52147. return msw << 16 | lsw & 0xffff;
  52148. }
  52149. /*
  52150. * Bitwise rotate a 32-bit number to the left.
  52151. */
  52152. function bitRotateLeft(num, cnt) {
  52153. return num << cnt | num >>> 32 - cnt;
  52154. }
  52155. /*
  52156. * These functions implement the four basic operations the algorithm uses.
  52157. */
  52158. function md5cmn(q, a, b, x, s, t) {
  52159. return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
  52160. }
  52161. function md5ff(a, b, c, d, x, s, t) {
  52162. return md5cmn(b & c | ~b & d, a, b, x, s, t);
  52163. }
  52164. function md5gg(a, b, c, d, x, s, t) {
  52165. return md5cmn(b & d | c & ~d, a, b, x, s, t);
  52166. }
  52167. function md5hh(a, b, c, d, x, s, t) {
  52168. return md5cmn(b ^ c ^ d, a, b, x, s, t);
  52169. }
  52170. function md5ii(a, b, c, d, x, s, t) {
  52171. return md5cmn(c ^ (b | ~d), a, b, x, s, t);
  52172. }
  52173. var _default = md5;
  52174. exports.default = _default;
  52175. },{}],368:[function(require,module,exports){
  52176. "use strict";
  52177. Object.defineProperty(exports, "__esModule", {
  52178. value: true
  52179. });
  52180. exports.default = void 0;
  52181. var _default = '00000000-0000-0000-0000-000000000000';
  52182. exports.default = _default;
  52183. },{}],369:[function(require,module,exports){
  52184. "use strict";
  52185. Object.defineProperty(exports, "__esModule", {
  52186. value: true
  52187. });
  52188. exports.default = void 0;
  52189. var _validate = _interopRequireDefault(require("./validate.js"));
  52190. function _interopRequireDefault(obj) {
  52191. return obj && obj.__esModule ? obj : {
  52192. default: obj
  52193. };
  52194. }
  52195. function parse(uuid) {
  52196. if (!(0, _validate.default)(uuid)) {
  52197. throw TypeError('Invalid UUID');
  52198. }
  52199. let v;
  52200. const arr = new Uint8Array(16); // Parse ########-....-....-....-............
  52201. arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  52202. arr[1] = v >>> 16 & 0xff;
  52203. arr[2] = v >>> 8 & 0xff;
  52204. arr[3] = v & 0xff; // Parse ........-####-....-....-............
  52205. arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  52206. arr[5] = v & 0xff; // Parse ........-....-####-....-............
  52207. arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  52208. arr[7] = v & 0xff; // Parse ........-....-....-####-............
  52209. arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  52210. arr[9] = v & 0xff; // Parse ........-....-....-....-############
  52211. // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
  52212. arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
  52213. arr[11] = v / 0x100000000 & 0xff;
  52214. arr[12] = v >>> 24 & 0xff;
  52215. arr[13] = v >>> 16 & 0xff;
  52216. arr[14] = v >>> 8 & 0xff;
  52217. arr[15] = v & 0xff;
  52218. return arr;
  52219. }
  52220. var _default = parse;
  52221. exports.default = _default;
  52222. },{"./validate.js":379}],370:[function(require,module,exports){
  52223. "use strict";
  52224. Object.defineProperty(exports, "__esModule", {
  52225. value: true
  52226. });
  52227. exports.default = void 0;
  52228. var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
  52229. exports.default = _default;
  52230. },{}],371:[function(require,module,exports){
  52231. "use strict";
  52232. Object.defineProperty(exports, "__esModule", {
  52233. value: true
  52234. });
  52235. exports.default = rng;
  52236. // Unique ID creation requires a high quality random # generator. In the browser we therefore
  52237. // require the crypto API and do not support built-in fallback to lower quality random number
  52238. // generators (like Math.random()).
  52239. let getRandomValues;
  52240. const rnds8 = new Uint8Array(16);
  52241. function rng() {
  52242. // lazy load so that environments that need to polyfill have a chance to do so
  52243. if (!getRandomValues) {
  52244. // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
  52245. // find the complete implementation of crypto (msCrypto) on IE11.
  52246. getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
  52247. if (!getRandomValues) {
  52248. throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
  52249. }
  52250. }
  52251. return getRandomValues(rnds8);
  52252. }
  52253. },{}],372:[function(require,module,exports){
  52254. "use strict";
  52255. Object.defineProperty(exports, "__esModule", {
  52256. value: true
  52257. });
  52258. exports.default = void 0;
  52259. // Adapted from Chris Veness' SHA1 code at
  52260. // http://www.movable-type.co.uk/scripts/sha1.html
  52261. function f(s, x, y, z) {
  52262. switch (s) {
  52263. case 0:
  52264. return x & y ^ ~x & z;
  52265. case 1:
  52266. return x ^ y ^ z;
  52267. case 2:
  52268. return x & y ^ x & z ^ y & z;
  52269. case 3:
  52270. return x ^ y ^ z;
  52271. }
  52272. }
  52273. function ROTL(x, n) {
  52274. return x << n | x >>> 32 - n;
  52275. }
  52276. function sha1(bytes) {
  52277. const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
  52278. const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
  52279. if (typeof bytes === 'string') {
  52280. const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  52281. bytes = [];
  52282. for (let i = 0; i < msg.length; ++i) {
  52283. bytes.push(msg.charCodeAt(i));
  52284. }
  52285. } else if (!Array.isArray(bytes)) {
  52286. // Convert Array-like to Array
  52287. bytes = Array.prototype.slice.call(bytes);
  52288. }
  52289. bytes.push(0x80);
  52290. const l = bytes.length / 4 + 2;
  52291. const N = Math.ceil(l / 16);
  52292. const M = new Array(N);
  52293. for (let i = 0; i < N; ++i) {
  52294. const arr = new Uint32Array(16);
  52295. for (let j = 0; j < 16; ++j) {
  52296. arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];
  52297. }
  52298. M[i] = arr;
  52299. }
  52300. M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
  52301. M[N - 1][14] = Math.floor(M[N - 1][14]);
  52302. M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
  52303. for (let i = 0; i < N; ++i) {
  52304. const W = new Uint32Array(80);
  52305. for (let t = 0; t < 16; ++t) {
  52306. W[t] = M[i][t];
  52307. }
  52308. for (let t = 16; t < 80; ++t) {
  52309. W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
  52310. }
  52311. let a = H[0];
  52312. let b = H[1];
  52313. let c = H[2];
  52314. let d = H[3];
  52315. let e = H[4];
  52316. for (let t = 0; t < 80; ++t) {
  52317. const s = Math.floor(t / 20);
  52318. const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
  52319. e = d;
  52320. d = c;
  52321. c = ROTL(b, 30) >>> 0;
  52322. b = a;
  52323. a = T;
  52324. }
  52325. H[0] = H[0] + a >>> 0;
  52326. H[1] = H[1] + b >>> 0;
  52327. H[2] = H[2] + c >>> 0;
  52328. H[3] = H[3] + d >>> 0;
  52329. H[4] = H[4] + e >>> 0;
  52330. }
  52331. return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
  52332. }
  52333. var _default = sha1;
  52334. exports.default = _default;
  52335. },{}],373:[function(require,module,exports){
  52336. "use strict";
  52337. Object.defineProperty(exports, "__esModule", {
  52338. value: true
  52339. });
  52340. exports.default = void 0;
  52341. var _validate = _interopRequireDefault(require("./validate.js"));
  52342. function _interopRequireDefault(obj) {
  52343. return obj && obj.__esModule ? obj : {
  52344. default: obj
  52345. };
  52346. }
  52347. /**
  52348. * Convert array of 16 byte values to UUID string format of the form:
  52349. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  52350. */
  52351. const byteToHex = [];
  52352. for (let i = 0; i < 256; ++i) {
  52353. byteToHex.push((i + 0x100).toString(16).substr(1));
  52354. }
  52355. function stringify(arr) {
  52356. let offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  52357. // Note: Be careful editing this code! It's been tuned for performance
  52358. // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  52359. const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
  52360. // of the following:
  52361. // - One or more input array values don't map to a hex octet (leading to
  52362. // "undefined" in the uuid)
  52363. // - Invalid input values for the RFC `version` or `variant` fields
  52364. if (!(0, _validate.default)(uuid)) {
  52365. throw TypeError('Stringified UUID is invalid');
  52366. }
  52367. return uuid;
  52368. }
  52369. var _default = stringify;
  52370. exports.default = _default;
  52371. },{"./validate.js":379}],374:[function(require,module,exports){
  52372. "use strict";
  52373. Object.defineProperty(exports, "__esModule", {
  52374. value: true
  52375. });
  52376. exports.default = void 0;
  52377. var _rng = _interopRequireDefault(require("./rng.js"));
  52378. var _stringify = _interopRequireDefault(require("./stringify.js"));
  52379. function _interopRequireDefault(obj) {
  52380. return obj && obj.__esModule ? obj : {
  52381. default: obj
  52382. };
  52383. }
  52384. // **`v1()` - Generate time-based UUID**
  52385. //
  52386. // Inspired by https://github.com/LiosK/UUID.js
  52387. // and http://docs.python.org/library/uuid.html
  52388. let _nodeId;
  52389. let _clockseq; // Previous uuid creation time
  52390. let _lastMSecs = 0;
  52391. let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
  52392. function v1(options, buf, offset) {
  52393. let i = buf && offset || 0;
  52394. const b = buf || new Array(16);
  52395. options = options || {};
  52396. let node = options.node || _nodeId;
  52397. let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
  52398. // specified. We do this lazily to minimize issues related to insufficient
  52399. // system entropy. See #189
  52400. if (node == null || clockseq == null) {
  52401. const seedBytes = options.random || (options.rng || _rng.default)();
  52402. if (node == null) {
  52403. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  52404. node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
  52405. }
  52406. if (clockseq == null) {
  52407. // Per 4.2.2, randomize (14 bit) clockseq
  52408. clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
  52409. }
  52410. } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  52411. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  52412. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  52413. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  52414. let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
  52415. // cycle to simulate higher resolution clock
  52416. let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
  52417. const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
  52418. if (dt < 0 && options.clockseq === undefined) {
  52419. clockseq = clockseq + 1 & 0x3fff;
  52420. } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  52421. // time interval
  52422. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  52423. nsecs = 0;
  52424. } // Per 4.2.1.2 Throw error if too many uuids are requested
  52425. if (nsecs >= 10000) {
  52426. throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
  52427. }
  52428. _lastMSecs = msecs;
  52429. _lastNSecs = nsecs;
  52430. _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  52431. msecs += 12219292800000; // `time_low`
  52432. const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  52433. b[i++] = tl >>> 24 & 0xff;
  52434. b[i++] = tl >>> 16 & 0xff;
  52435. b[i++] = tl >>> 8 & 0xff;
  52436. b[i++] = tl & 0xff; // `time_mid`
  52437. const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
  52438. b[i++] = tmh >>> 8 & 0xff;
  52439. b[i++] = tmh & 0xff; // `time_high_and_version`
  52440. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  52441. b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  52442. b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
  52443. b[i++] = clockseq & 0xff; // `node`
  52444. for (let n = 0; n < 6; ++n) {
  52445. b[i + n] = node[n];
  52446. }
  52447. return buf || (0, _stringify.default)(b);
  52448. }
  52449. var _default = v1;
  52450. exports.default = _default;
  52451. },{"./rng.js":371,"./stringify.js":373}],375:[function(require,module,exports){
  52452. "use strict";
  52453. Object.defineProperty(exports, "__esModule", {
  52454. value: true
  52455. });
  52456. exports.default = void 0;
  52457. var _v = _interopRequireDefault(require("./v35.js"));
  52458. var _md = _interopRequireDefault(require("./md5.js"));
  52459. function _interopRequireDefault(obj) {
  52460. return obj && obj.__esModule ? obj : {
  52461. default: obj
  52462. };
  52463. }
  52464. const v3 = (0, _v.default)('v3', 0x30, _md.default);
  52465. var _default = v3;
  52466. exports.default = _default;
  52467. },{"./md5.js":367,"./v35.js":376}],376:[function(require,module,exports){
  52468. "use strict";
  52469. Object.defineProperty(exports, "__esModule", {
  52470. value: true
  52471. });
  52472. exports.default = _default;
  52473. exports.URL = exports.DNS = void 0;
  52474. var _stringify = _interopRequireDefault(require("./stringify.js"));
  52475. var _parse = _interopRequireDefault(require("./parse.js"));
  52476. function _interopRequireDefault(obj) {
  52477. return obj && obj.__esModule ? obj : {
  52478. default: obj
  52479. };
  52480. }
  52481. function stringToBytes(str) {
  52482. str = unescape(encodeURIComponent(str)); // UTF8 escape
  52483. const bytes = [];
  52484. for (let i = 0; i < str.length; ++i) {
  52485. bytes.push(str.charCodeAt(i));
  52486. }
  52487. return bytes;
  52488. }
  52489. const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  52490. exports.DNS = DNS;
  52491. const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
  52492. exports.URL = URL;
  52493. function _default(name, version, hashfunc) {
  52494. function generateUUID(value, namespace, buf, offset) {
  52495. if (typeof value === 'string') {
  52496. value = stringToBytes(value);
  52497. }
  52498. if (typeof namespace === 'string') {
  52499. namespace = (0, _parse.default)(namespace);
  52500. }
  52501. if (namespace.length !== 16) {
  52502. throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
  52503. } // Compute hash of namespace and value, Per 4.3
  52504. // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
  52505. // hashfunc([...namespace, ... value])`
  52506. let bytes = new Uint8Array(16 + value.length);
  52507. bytes.set(namespace);
  52508. bytes.set(value, namespace.length);
  52509. bytes = hashfunc(bytes);
  52510. bytes[6] = bytes[6] & 0x0f | version;
  52511. bytes[8] = bytes[8] & 0x3f | 0x80;
  52512. if (buf) {
  52513. offset = offset || 0;
  52514. for (let i = 0; i < 16; ++i) {
  52515. buf[offset + i] = bytes[i];
  52516. }
  52517. return buf;
  52518. }
  52519. return (0, _stringify.default)(bytes);
  52520. } // Function#name is not settable on some platforms (#270)
  52521. try {
  52522. generateUUID.name = name; // eslint-disable-next-line no-empty
  52523. } catch (err) {} // For CommonJS default export support
  52524. generateUUID.DNS = DNS;
  52525. generateUUID.URL = URL;
  52526. return generateUUID;
  52527. }
  52528. },{"./parse.js":369,"./stringify.js":373}],377:[function(require,module,exports){
  52529. "use strict";
  52530. Object.defineProperty(exports, "__esModule", {
  52531. value: true
  52532. });
  52533. exports.default = void 0;
  52534. var _rng = _interopRequireDefault(require("./rng.js"));
  52535. var _stringify = _interopRequireDefault(require("./stringify.js"));
  52536. function _interopRequireDefault(obj) {
  52537. return obj && obj.__esModule ? obj : {
  52538. default: obj
  52539. };
  52540. }
  52541. function v4(options, buf, offset) {
  52542. options = options || {};
  52543. const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  52544. rnds[6] = rnds[6] & 0x0f | 0x40;
  52545. rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
  52546. if (buf) {
  52547. offset = offset || 0;
  52548. for (let i = 0; i < 16; ++i) {
  52549. buf[offset + i] = rnds[i];
  52550. }
  52551. return buf;
  52552. }
  52553. return (0, _stringify.default)(rnds);
  52554. }
  52555. var _default = v4;
  52556. exports.default = _default;
  52557. },{"./rng.js":371,"./stringify.js":373}],378:[function(require,module,exports){
  52558. "use strict";
  52559. Object.defineProperty(exports, "__esModule", {
  52560. value: true
  52561. });
  52562. exports.default = void 0;
  52563. var _v = _interopRequireDefault(require("./v35.js"));
  52564. var _sha = _interopRequireDefault(require("./sha1.js"));
  52565. function _interopRequireDefault(obj) {
  52566. return obj && obj.__esModule ? obj : {
  52567. default: obj
  52568. };
  52569. }
  52570. const v5 = (0, _v.default)('v5', 0x50, _sha.default);
  52571. var _default = v5;
  52572. exports.default = _default;
  52573. },{"./sha1.js":372,"./v35.js":376}],379:[function(require,module,exports){
  52574. "use strict";
  52575. Object.defineProperty(exports, "__esModule", {
  52576. value: true
  52577. });
  52578. exports.default = void 0;
  52579. var _regex = _interopRequireDefault(require("./regex.js"));
  52580. function _interopRequireDefault(obj) {
  52581. return obj && obj.__esModule ? obj : {
  52582. default: obj
  52583. };
  52584. }
  52585. function validate(uuid) {
  52586. return typeof uuid === 'string' && _regex.default.test(uuid);
  52587. }
  52588. var _default = validate;
  52589. exports.default = _default;
  52590. },{"./regex.js":370}],380:[function(require,module,exports){
  52591. "use strict";
  52592. Object.defineProperty(exports, "__esModule", {
  52593. value: true
  52594. });
  52595. exports.default = void 0;
  52596. var _validate = _interopRequireDefault(require("./validate.js"));
  52597. function _interopRequireDefault(obj) {
  52598. return obj && obj.__esModule ? obj : {
  52599. default: obj
  52600. };
  52601. }
  52602. function version(uuid) {
  52603. if (!(0, _validate.default)(uuid)) {
  52604. throw TypeError('Invalid UUID');
  52605. }
  52606. return parseInt(uuid.substr(14, 1), 16);
  52607. }
  52608. var _default = version;
  52609. exports.default = _default;
  52610. },{"./validate.js":379}],381:[function(require,module,exports){
  52611. "use strict";
  52612. /**
  52613. * Character classes and associated utilities for the 5th edition of XML 1.0.
  52614. *
  52615. * @author Louis-Dominique Dubeau
  52616. * @license MIT
  52617. * @copyright Louis-Dominique Dubeau
  52618. */
  52619. Object.defineProperty(exports, "__esModule", {
  52620. value: true
  52621. });
  52622. //
  52623. // Fragments.
  52624. //
  52625. exports.CHAR = "\t\n\r -\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF";
  52626. exports.S = " \t\r\n";
  52627. // tslint:disable-next-line:max-line-length
  52628. exports.NAME_START_CHAR = ":A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF";
  52629. exports.NAME_CHAR = "-" + exports.NAME_START_CHAR + ".0-9\u00B7\u0300-\u036F\u203F-\u2040";
  52630. //
  52631. // Regular expressions.
  52632. //
  52633. exports.CHAR_RE = new RegExp("^[" + exports.CHAR + "]$", "u");
  52634. exports.S_RE = new RegExp("^[" + exports.S + "]+$", "u");
  52635. exports.NAME_START_CHAR_RE = new RegExp("^[" + exports.NAME_START_CHAR + "]$", "u");
  52636. exports.NAME_CHAR_RE = new RegExp("^[" + exports.NAME_CHAR + "]$", "u");
  52637. exports.NAME_RE = new RegExp("^[" + exports.NAME_START_CHAR + "][" + exports.NAME_CHAR + "]*$", "u");
  52638. exports.NMTOKEN_RE = new RegExp("^[" + exports.NAME_CHAR + "]+$", "u");
  52639. var TAB = 9;
  52640. var NL = 0xA;
  52641. var CR = 0xD;
  52642. var SPACE = 0x20;
  52643. //
  52644. // Lists.
  52645. //
  52646. /** All characters in the ``S`` production. */
  52647. exports.S_LIST = [SPACE, NL, CR, TAB];
  52648. /**
  52649. * Determines whether a codepoint matches the ``CHAR`` production.
  52650. *
  52651. * @param c The code point.
  52652. *
  52653. * @returns ``true`` if the codepoint matches ``CHAR``.
  52654. */
  52655. function isChar(c) {
  52656. return c >= SPACE && c <= 0xD7FF || c === NL || c === CR || c === TAB || c >= 0xE000 && c <= 0xFFFD || c >= 0x10000 && c <= 0x10FFFF;
  52657. }
  52658. exports.isChar = isChar;
  52659. /**
  52660. * Determines whether a codepoint matches the ``S`` (space) production.
  52661. *
  52662. * @param c The code point.
  52663. *
  52664. * @returns ``true`` if the codepoint matches ``S``.
  52665. */
  52666. function isS(c) {
  52667. return c === SPACE || c === NL || c === CR || c === TAB;
  52668. }
  52669. exports.isS = isS;
  52670. /**
  52671. * Determines whether a codepoint matches the ``NAME_START_CHAR`` production.
  52672. *
  52673. * @param c The code point.
  52674. *
  52675. * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``.
  52676. */
  52677. function isNameStartChar(c) {
  52678. return c >= 0x41 && c <= 0x5A || c >= 0x61 && c <= 0x7A || c === 0x3A || c === 0x5F || c === 0x200C || c === 0x200D || c >= 0xC0 && c <= 0xD6 || c >= 0xD8 && c <= 0xF6 || c >= 0x00F8 && c <= 0x02FF || c >= 0x0370 && c <= 0x037D || c >= 0x037F && c <= 0x1FFF || c >= 0x2070 && c <= 0x218F || c >= 0x2C00 && c <= 0x2FEF || c >= 0x3001 && c <= 0xD7FF || c >= 0xF900 && c <= 0xFDCF || c >= 0xFDF0 && c <= 0xFFFD || c >= 0x10000 && c <= 0xEFFFF;
  52679. }
  52680. exports.isNameStartChar = isNameStartChar;
  52681. /**
  52682. * Determines whether a codepoint matches the ``NAME_CHAR`` production.
  52683. *
  52684. * @param c The code point.
  52685. *
  52686. * @returns ``true`` if the codepoint matches ``NAME_CHAR``.
  52687. */
  52688. function isNameChar(c) {
  52689. return isNameStartChar(c) || c >= 0x30 && c <= 0x39 || c === 0x2D || c === 0x2E || c === 0xB7 || c >= 0x0300 && c <= 0x036F || c >= 0x203F && c <= 0x2040;
  52690. }
  52691. exports.isNameChar = isNameChar;
  52692. },{}],382:[function(require,module,exports){
  52693. "use strict";
  52694. /**
  52695. * Character classes and associated utilities for the 2nd edition of XML 1.1.
  52696. *
  52697. * @author Louis-Dominique Dubeau
  52698. * @license MIT
  52699. * @copyright Louis-Dominique Dubeau
  52700. */
  52701. Object.defineProperty(exports, "__esModule", {
  52702. value: true
  52703. });
  52704. //
  52705. // Fragments.
  52706. //
  52707. exports.CHAR = "\u0001-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF";
  52708. exports.RESTRICTED_CHAR = "\u0001-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F";
  52709. exports.S = " \t\r\n";
  52710. // tslint:disable-next-line:max-line-length
  52711. exports.NAME_START_CHAR = ":A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF";
  52712. exports.NAME_CHAR = "-" + exports.NAME_START_CHAR + ".0-9\u00B7\u0300-\u036F\u203F-\u2040";
  52713. //
  52714. // Regular expressions.
  52715. //
  52716. exports.CHAR_RE = new RegExp("^[" + exports.CHAR + "]$", "u");
  52717. exports.RESTRICTED_CHAR_RE = new RegExp("^[" + exports.RESTRICTED_CHAR + "]$", "u");
  52718. exports.S_RE = new RegExp("^[" + exports.S + "]+$", "u");
  52719. exports.NAME_START_CHAR_RE = new RegExp("^[" + exports.NAME_START_CHAR + "]$", "u");
  52720. exports.NAME_CHAR_RE = new RegExp("^[" + exports.NAME_CHAR + "]$", "u");
  52721. exports.NAME_RE = new RegExp("^[" + exports.NAME_START_CHAR + "][" + exports.NAME_CHAR + "]*$", "u");
  52722. exports.NMTOKEN_RE = new RegExp("^[" + exports.NAME_CHAR + "]+$", "u");
  52723. var TAB = 9;
  52724. var NL = 0xA;
  52725. var CR = 0xD;
  52726. var SPACE = 0x20;
  52727. //
  52728. // Lists.
  52729. //
  52730. /** All characters in the ``S`` production. */
  52731. exports.S_LIST = [SPACE, NL, CR, TAB];
  52732. /**
  52733. * Determines whether a codepoint matches the ``CHAR`` production.
  52734. *
  52735. * @param c The code point.
  52736. *
  52737. * @returns ``true`` if the codepoint matches ``CHAR``.
  52738. */
  52739. function isChar(c) {
  52740. return c >= 0x0001 && c <= 0xD7FF || c >= 0xE000 && c <= 0xFFFD || c >= 0x10000 && c <= 0x10FFFF;
  52741. }
  52742. exports.isChar = isChar;
  52743. /**
  52744. * Determines whether a codepoint matches the ``RESTRICTED_CHAR`` production.
  52745. *
  52746. * @param c The code point.
  52747. *
  52748. * @returns ``true`` if the codepoint matches ``RESTRICTED_CHAR``.
  52749. */
  52750. function isRestrictedChar(c) {
  52751. return c >= 0x1 && c <= 0x8 || c === 0xB || c === 0xC || c >= 0xE && c <= 0x1F || c >= 0x7F && c <= 0x84 || c >= 0x86 && c <= 0x9F;
  52752. }
  52753. exports.isRestrictedChar = isRestrictedChar;
  52754. /**
  52755. * Determines whether a codepoint matches the ``CHAR`` production and does not
  52756. * match the ``RESTRICTED_CHAR`` production. ``isCharAndNotRestricted(x)`` is
  52757. * equivalent to ``isChar(x) && !isRestrictedChar(x)``. This function is faster
  52758. * than running the two-call equivalent.
  52759. *
  52760. * @param c The code point.
  52761. *
  52762. * @returns ``true`` if the codepoint matches ``CHAR`` and does not match
  52763. * ``RESTRICTED_CHAR``.
  52764. */
  52765. function isCharAndNotRestricted(c) {
  52766. return c === 0x9 || c === 0xA || c === 0xD || c > 0x1F && c < 0x7F || c === 0x85 || c > 0x9F && c <= 0xD7FF || c >= 0xE000 && c <= 0xFFFD || c >= 0x10000 && c <= 0x10FFFF;
  52767. }
  52768. exports.isCharAndNotRestricted = isCharAndNotRestricted;
  52769. /**
  52770. * Determines whether a codepoint matches the ``S`` (space) production.
  52771. *
  52772. * @param c The code point.
  52773. *
  52774. * @returns ``true`` if the codepoint matches ``S``.
  52775. */
  52776. function isS(c) {
  52777. return c === SPACE || c === NL || c === CR || c === TAB;
  52778. }
  52779. exports.isS = isS;
  52780. /**
  52781. * Determines whether a codepoint matches the ``NAME_START_CHAR`` production.
  52782. *
  52783. * @param c The code point.
  52784. *
  52785. * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``.
  52786. */
  52787. // tslint:disable-next-line:cyclomatic-complexity
  52788. function isNameStartChar(c) {
  52789. return c >= 0x41 && c <= 0x5A || c >= 0x61 && c <= 0x7A || c === 0x3A || c === 0x5F || c === 0x200C || c === 0x200D || c >= 0xC0 && c <= 0xD6 || c >= 0xD8 && c <= 0xF6 || c >= 0x00F8 && c <= 0x02FF || c >= 0x0370 && c <= 0x037D || c >= 0x037F && c <= 0x1FFF || c >= 0x2070 && c <= 0x218F || c >= 0x2C00 && c <= 0x2FEF || c >= 0x3001 && c <= 0xD7FF || c >= 0xF900 && c <= 0xFDCF || c >= 0xFDF0 && c <= 0xFFFD || c >= 0x10000 && c <= 0xEFFFF;
  52790. }
  52791. exports.isNameStartChar = isNameStartChar;
  52792. /**
  52793. * Determines whether a codepoint matches the ``NAME_CHAR`` production.
  52794. *
  52795. * @param c The code point.
  52796. *
  52797. * @returns ``true`` if the codepoint matches ``NAME_CHAR``.
  52798. */
  52799. function isNameChar(c) {
  52800. return isNameStartChar(c) || c >= 0x30 && c <= 0x39 || c === 0x2D || c === 0x2E || c === 0xB7 || c >= 0x0300 && c <= 0x036F || c >= 0x203F && c <= 0x2040;
  52801. }
  52802. exports.isNameChar = isNameChar;
  52803. },{}],383:[function(require,module,exports){
  52804. "use strict";
  52805. /**
  52806. * Character class utilities for XML NS 1.0 edition 3.
  52807. *
  52808. * @author Louis-Dominique Dubeau
  52809. * @license MIT
  52810. * @copyright Louis-Dominique Dubeau
  52811. */
  52812. Object.defineProperty(exports, "__esModule", {
  52813. value: true
  52814. });
  52815. //
  52816. // Fragments.
  52817. //
  52818. // tslint:disable-next-line:max-line-length
  52819. exports.NC_NAME_START_CHAR = "A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\uD800\uDC00-\uDB7F\uDFFF";
  52820. exports.NC_NAME_CHAR = "-" + exports.NC_NAME_START_CHAR + ".0-9\u00B7\u0300-\u036F\u203F-\u2040";
  52821. //
  52822. // Regular expressions.
  52823. //
  52824. exports.NC_NAME_START_CHAR_RE = new RegExp("^[" + exports.NC_NAME_START_CHAR + "]$", "u");
  52825. exports.NC_NAME_CHAR_RE = new RegExp("^[" + exports.NC_NAME_CHAR + "]$", "u");
  52826. exports.NC_NAME_RE = new RegExp("^[" + exports.NC_NAME_START_CHAR + "][" + exports.NC_NAME_CHAR + "]*$", "u");
  52827. /**
  52828. * Determines whether a codepoint matches [[NC_NAME_START_CHAR]].
  52829. *
  52830. * @param c The code point.
  52831. *
  52832. * @returns ``true`` if the codepoint matches.
  52833. */
  52834. // tslint:disable-next-line:cyclomatic-complexity
  52835. function isNCNameStartChar(c) {
  52836. return c >= 0x41 && c <= 0x5A || c === 0x5F || c >= 0x61 && c <= 0x7A || c >= 0xC0 && c <= 0xD6 || c >= 0xD8 && c <= 0xF6 || c >= 0x00F8 && c <= 0x02FF || c >= 0x0370 && c <= 0x037D || c >= 0x037F && c <= 0x1FFF || c >= 0x200C && c <= 0x200D || c >= 0x2070 && c <= 0x218F || c >= 0x2C00 && c <= 0x2FEF || c >= 0x3001 && c <= 0xD7FF || c >= 0xF900 && c <= 0xFDCF || c >= 0xFDF0 && c <= 0xFFFD || c >= 0x10000 && c <= 0xEFFFF;
  52837. }
  52838. exports.isNCNameStartChar = isNCNameStartChar;
  52839. /**
  52840. * Determines whether a codepoint matches [[NC_NAME_CHAR]].
  52841. *
  52842. * @param c The code point.
  52843. *
  52844. * @returns ``true`` if the codepoint matches.
  52845. */
  52846. function isNCNameChar(c) {
  52847. return isNCNameStartChar(c) || c === 0x2D || c === 0x2E || c >= 0x30 && c <= 0x39 || c === 0x00B7 || c >= 0x0300 && c <= 0x036F || c >= 0x203F && c <= 0x2040;
  52848. }
  52849. exports.isNCNameChar = isNCNameChar;
  52850. },{}]},{},[15])(15)
  52851. });
  52852. //# sourceMappingURL=exceljs.bare.js.map