xlsx.extendscript.js 1004 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868
  1. /*! xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
  2. /*! shim.js (C) 2013-present SheetJS -- http://sheetjs.com */
  3. /* ES3/5 Compatibility shims and other utilities for older browsers. */
  4. // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
  5. if(!Object.keys) Object.keys = (function() {
  6. var hasOwnProperty = Object.prototype.hasOwnProperty,
  7. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  8. dontEnums = [
  9. 'toString',
  10. 'toLocaleString',
  11. 'valueOf',
  12. 'hasOwnProperty',
  13. 'isPrototypeOf',
  14. 'propertyIsEnumerable',
  15. 'constructor'
  16. ],
  17. dontEnumsLength = dontEnums.length;
  18. return function(obj) {
  19. if(typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
  20. var result = [];
  21. for(var prop in obj) if(hasOwnProperty.call(obj, prop)) result.push(prop);
  22. if(hasDontEnumBug)
  23. for(var i=0; i < dontEnumsLength; ++i)
  24. if(hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  25. return result;
  26. };
  27. })();
  28. if(!String.prototype.trim) String.prototype.trim = function() {
  29. var s = this.replace(/^\s+/, '');
  30. for(var i = s.length - 1; i >=0 ; --i) if(!s.charAt(i).match(/^\s/)) return s.slice(0,i+1);
  31. return "";
  32. };
  33. if(!Array.prototype.forEach) Array.prototype.forEach = function(cb) {
  34. var len = (this.length>>>0), self = (arguments[1]||void 0);
  35. for(var i=0; i<len; ++i) if(i in this) self ? cb.call(self, this[i], i, this) : cb(this[i], i, this);
  36. };
  37. if(!Array.prototype.map) Array.prototype.map = function(cb) {
  38. var len = (this.length>>>0), self = (arguments[1]||void 0), A = new Array(len);
  39. for(var i=0; i<len; ++i) if(i in this) A[i] = self ? cb.call(self, this[i], i, this) : cb(this[i], i, this);
  40. return A;
  41. };
  42. if(!Array.prototype.indexOf) Array.prototype.indexOf = function(needle) {
  43. var len = (this.length>>>0), i = ((arguments[1]|0)||0);
  44. for(i<0 && (i+=len)<0 && (i=0); i<len; ++i) if(this[i] === needle) return i;
  45. return -1;
  46. };
  47. if(!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(needle) {
  48. var len = (this.length>>>0), i = len - 1;
  49. for(; i>=0; --i) if(this[i] === needle) return i;
  50. return -1;
  51. };
  52. if(!Array.isArray) Array.isArray = function(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; };
  53. if(!Date.prototype.toISOString) Date.prototype.toISOString = (function() {
  54. function p(n,i) { return ('0000000' + n).slice(-(i||2)); }
  55. return function _toISOString() {
  56. var y = this.getUTCFullYear(), yr = "";
  57. if(y>9999) yr = '+' + p( y, 6);
  58. else if(y<0) yr = '-' + p(-y, 6);
  59. else yr = p( y, 4);
  60. return [
  61. yr, p(this.getUTCMonth()+1), p(this.getUTCDate())
  62. ].join('-') + 'T' + [
  63. p(this.getUTCHours()), p(this.getUTCMinutes()), p(this.getUTCSeconds())
  64. ].join(':') + '.' + p(this.getUTCMilliseconds(),3) + 'Z';
  65. };
  66. }());
  67. if(typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) ArrayBuffer.prototype.slice = function(start, end) {
  68. if(start == null) start = 0;
  69. if(start < 0) { start += this.byteLength; if(start < 0) start = 0; }
  70. if(start >= this.byteLength) return new Uint8Array(0);
  71. if(end == null) end = this.byteLength;
  72. if(end < 0) { end += this.byteLength; if(end < 0) end = 0; }
  73. if(end > this.byteLength) end = this.byteLength;
  74. if(start > end) return new Uint8Array(0);
  75. var out = new ArrayBuffer(end - start);
  76. var view = new Uint8Array(out);
  77. var data = new Uint8Array(this, start, end - start)
  78. /* IE10 should have Uint8Array#set */
  79. if(view.set) view.set(data); else while(start <= --end) view[end - start] = data[end];
  80. return out;
  81. };
  82. if(typeof Uint8Array !== 'undefined' && !Uint8Array.prototype.slice) Uint8Array.prototype.slice = function(start, end) {
  83. if(start == null) start = 0;
  84. if(start < 0) { start += this.length; if(start < 0) start = 0; }
  85. if(start >= this.length) return new Uint8Array(0);
  86. if(end == null) end = this.length;
  87. if(end < 0) { end += this.length; if(end < 0) end = 0; }
  88. if(end > this.length) end = this.length;
  89. if(start > end) return new Uint8Array(0);
  90. var out = new Uint8Array(end - start);
  91. while(start <= --end) out[end - start] = this[end];
  92. return out;
  93. };
  94. // VBScript + ActiveX fallback for IE5+
  95. var IE_SaveFile = (function() { try {
  96. if(typeof IE_SaveFile_Impl == "undefined") document.write([
  97. '<script type="text/vbscript" language="vbscript">',
  98. 'IE_GetProfileAndPath_Key = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\"',
  99. 'Function IE_GetProfileAndPath(key): Set wshell = CreateObject("WScript.Shell"): IE_GetProfileAndPath = wshell.RegRead(IE_GetProfileAndPath_Key & key): IE_GetProfileAndPath = wshell.ExpandEnvironmentStrings("%USERPROFILE%") & "!" & IE_GetProfileAndPath: End Function',
  100. 'Function IE_SaveFile_Impl(FileName, payload): Dim data, plen, i, bit: data = CStr(payload): plen = Len(data): Set fso = CreateObject("Scripting.FileSystemObject"): fso.CreateTextFile FileName, True: Set f = fso.GetFile(FileName): Set stream = f.OpenAsTextStream(2, 0): For i = 1 To plen Step 3: bit = Mid(data, i, 2): stream.write Chr(CLng("&h" & bit)): Next: stream.Close: IE_SaveFile_Impl = True: End Function',
  101. '|/script>'.replace("|","<")
  102. ].join("\r\n"));
  103. if(typeof IE_SaveFile_Impl == "undefined") return void 0;
  104. var IE_GetPath = (function() {
  105. var DDP1 = "";
  106. try { DDP1 = IE_GetProfileAndPath("{374DE290-123F-4565-9164-39C4925E467B}"); } catch(e) { try { DDP1 = IE_GetProfileAndPath("Personal"); } catch(e) { try { DDP1 = IE_GetProfileAndPath("Desktop"); } catch(e) { throw e; }}}
  107. var o = DDP1.split("!");
  108. DDP = o[1].replace("%USERPROFILE%", o[0]);
  109. return function(path) { return DDP + "\\" + path; };
  110. })();
  111. function fix_data(data) {
  112. var out = [];
  113. var T = typeof data == "string";
  114. for(var i = 0; i < data.length; ++i) out.push(("00"+(T ? data.charCodeAt(i) : data[i]).toString(16)).slice(-2));
  115. var o = out.join("|");
  116. return o;
  117. }
  118. return function(data, filename) { return IE_SaveFile_Impl(IE_GetPath(filename), fix_data(data)); };
  119. } catch(e) { return void 0; }})();
  120. var IE_LoadFile = (function() { try {
  121. if(typeof IE_LoadFile_Impl == "undefined") document.write([
  122. '<script type="text/vbscript" language="vbscript">',
  123. 'Function IE_LoadFile_Impl(FileName): Dim out(), plen, i, cc: Set fso = CreateObject("Scripting.FileSystemObject"): Set f = fso.GetFile(FileName): Set stream = f.OpenAsTextStream(1, 0): plen = f.Size: ReDim out(plen): For i = 1 To plen Step 1: cc = Hex(Asc(stream.read(1))): If Len(cc) < 2 Then: cc = "0" & cc: End If: out(i) = cc: Next: IE_LoadFile_Impl = Join(out,""): End Function',
  124. '|/script>'.replace("|","<")
  125. ].join("\r\n"));
  126. if(typeof IE_LoadFile_Impl == "undefined") return void 0;
  127. function fix_data(data) {
  128. var out = [];
  129. for(var i = 0; i < data.length; i+=2) out.push(String.fromCharCode(parseInt(data.slice(i, i+2), 16)));
  130. var o = out.join("");
  131. return o;
  132. }
  133. return function(filename) { return fix_data(IE_LoadFile_Impl(filename)); };
  134. } catch(e) { return void 0; }})();
  135. // getComputedStyle polyfill from https://gist.github.com/8HNHoFtE/5891086
  136. if(typeof window !== 'undefined' && typeof window.getComputedStyle !== 'function') {
  137. window.getComputedStyle = function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this}
  138. }
  139. var DO_NOT_EXPORT_CODEPAGE = true;
  140. var DO_NOT_EXPORT_JSZIP = true;
  141. /*
  142. JSZip - A Javascript class for generating and reading zip files
  143. <http://stuartk.com/jszip>
  144. (c) 2009-2014 Stuart Knightley <stuart [at] stuartk.com>
  145. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
  146. JSZip uses the library pako released under the MIT license :
  147. https://github.com/nodeca/pako/blob/master/LICENSE
  148. Note: since JSZip 3 removed critical functionality, this version assigns to the
  149. `JSZipSync` variable. Another JSZip version can be loaded in parallel.
  150. */
  151. (function(e){
  152. if("object"==typeof exports&&"undefined"!=typeof module&&"undefined"==typeof DO_NOT_EXPORT_JSZIP)module.exports=e();
  153. else if("function"==typeof define&&define.amd&&"undefined"==typeof DO_NOT_EXPORT_JSZIP){JSZipSync=e();define([],e);}
  154. else{
  155. var f;
  156. "undefined"!=typeof globalThis?f=globalThis:
  157. "undefined"!=typeof window?f=window:
  158. "undefined"!=typeof global?f=global:
  159. "undefined"!=typeof $ && $.global?f=$.global:
  160. "undefined"!=typeof self&&(f=self),f.JSZipSync=e()
  161. }
  162. }(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  163. 'use strict';
  164. // private property
  165. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  166. // public method for encoding
  167. exports.encode = function(input, utf8) {
  168. var output = "";
  169. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  170. var i = 0;
  171. while (i < input.length) {
  172. chr1 = input.charCodeAt(i++);
  173. chr2 = input.charCodeAt(i++);
  174. chr3 = input.charCodeAt(i++);
  175. enc1 = chr1 >> 2;
  176. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  177. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  178. enc4 = chr3 & 63;
  179. if (isNaN(chr2)) {
  180. enc3 = enc4 = 64;
  181. }
  182. else if (isNaN(chr3)) {
  183. enc4 = 64;
  184. }
  185. output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  186. }
  187. return output;
  188. };
  189. // public method for decoding
  190. exports.decode = function(input, utf8) {
  191. var output = "";
  192. var chr1, chr2, chr3;
  193. var enc1, enc2, enc3, enc4;
  194. var i = 0;
  195. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  196. while (i < input.length) {
  197. enc1 = _keyStr.indexOf(input.charAt(i++));
  198. enc2 = _keyStr.indexOf(input.charAt(i++));
  199. enc3 = _keyStr.indexOf(input.charAt(i++));
  200. enc4 = _keyStr.indexOf(input.charAt(i++));
  201. chr1 = (enc1 << 2) | (enc2 >> 4);
  202. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  203. chr3 = ((enc3 & 3) << 6) | enc4;
  204. output = output + String.fromCharCode(chr1);
  205. if (enc3 != 64) {
  206. output = output + String.fromCharCode(chr2);
  207. }
  208. if (enc4 != 64) {
  209. output = output + String.fromCharCode(chr3);
  210. }
  211. }
  212. return output;
  213. };
  214. },{}],2:[function(_dereq_,module,exports){
  215. 'use strict';
  216. function CompressedObject() {
  217. this.compressedSize = 0;
  218. this.uncompressedSize = 0;
  219. this.crc32 = 0;
  220. this.compressionMethod = null;
  221. this.compressedContent = null;
  222. }
  223. CompressedObject.prototype = {
  224. /**
  225. * Return the decompressed content in an unspecified format.
  226. * The format will depend on the decompressor.
  227. * @return {Object} the decompressed content.
  228. */
  229. getContent: function() {
  230. return null; // see implementation
  231. },
  232. /**
  233. * Return the compressed content in an unspecified format.
  234. * The format will depend on the compressed conten source.
  235. * @return {Object} the compressed content.
  236. */
  237. getCompressedContent: function() {
  238. return null; // see implementation
  239. }
  240. };
  241. module.exports = CompressedObject;
  242. },{}],3:[function(_dereq_,module,exports){
  243. 'use strict';
  244. exports.STORE = {
  245. magic: "\x00\x00",
  246. compress: function(content) {
  247. return content; // no compression
  248. },
  249. uncompress: function(content) {
  250. return content; // no compression
  251. },
  252. compressInputType: null,
  253. uncompressInputType: null
  254. };
  255. exports.DEFLATE = _dereq_('./flate');
  256. },{"./flate":8}],4:[function(_dereq_,module,exports){
  257. 'use strict';
  258. var utils = _dereq_('./utils');
  259. var table = [
  260. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
  261. 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  262. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
  263. 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  264. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
  265. 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  266. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
  267. 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  268. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
  269. 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  270. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
  271. 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  272. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
  273. 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  274. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
  275. 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  276. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
  277. 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  278. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
  279. 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  280. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
  281. 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  282. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
  283. 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  284. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
  285. 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  286. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
  287. 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  288. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
  289. 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  290. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
  291. 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  292. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
  293. 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  294. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
  295. 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  296. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
  297. 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  298. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
  299. 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  300. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
  301. 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  302. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
  303. 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  304. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
  305. 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  306. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
  307. 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  308. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
  309. 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  310. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
  311. 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  312. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
  313. 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  314. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
  315. 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  316. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
  317. 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  318. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
  319. 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  320. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
  321. 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  322. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
  323. 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  324. ];
  325. /**
  326. *
  327. * Javascript crc32
  328. * http://www.webtoolkit.info/
  329. *
  330. */
  331. module.exports = function crc32(input, crc) {
  332. if (typeof input === "undefined" || !input.length) {
  333. return 0;
  334. }
  335. var isArray = utils.getTypeOf(input) !== "string";
  336. if (typeof(crc) == "undefined") {
  337. crc = 0;
  338. }
  339. var x = 0;
  340. var y = 0;
  341. var b = 0;
  342. crc = crc ^ (-1);
  343. for (var i = 0, iTop = input.length; i < iTop; i++) {
  344. b = isArray ? input[i] : input.charCodeAt(i);
  345. y = (crc ^ b) & 0xFF;
  346. x = table[y];
  347. crc = (crc >>> 8) ^ x;
  348. }
  349. return crc ^ (-1);
  350. };
  351. // vim: set shiftwidth=4 softtabstop=4:
  352. },{"./utils":21}],5:[function(_dereq_,module,exports){
  353. 'use strict';
  354. var utils = _dereq_('./utils');
  355. function DataReader(data) {
  356. this.data = null; // type : see implementation
  357. this.length = 0;
  358. this.index = 0;
  359. }
  360. DataReader.prototype = {
  361. /**
  362. * Check that the offset will not go too far.
  363. * @param {string} offset the additional offset to check.
  364. * @throws {Error} an Error if the offset is out of bounds.
  365. */
  366. checkOffset: function(offset) {
  367. this.checkIndex(this.index + offset);
  368. },
  369. /**
  370. * Check that the specifed index will not be too far.
  371. * @param {string} newIndex the index to check.
  372. * @throws {Error} an Error if the index is out of bounds.
  373. */
  374. checkIndex: function(newIndex) {
  375. if (this.length < newIndex || newIndex < 0) {
  376. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  377. }
  378. },
  379. /**
  380. * Change the index.
  381. * @param {number} newIndex The new index.
  382. * @throws {Error} if the new index is out of the data.
  383. */
  384. setIndex: function(newIndex) {
  385. this.checkIndex(newIndex);
  386. this.index = newIndex;
  387. },
  388. /**
  389. * Skip the next n bytes.
  390. * @param {number} n the number of bytes to skip.
  391. * @throws {Error} if the new index is out of the data.
  392. */
  393. skip: function(n) {
  394. this.setIndex(this.index + n);
  395. },
  396. /**
  397. * Get the byte at the specified index.
  398. * @param {number} i the index to use.
  399. * @return {number} a byte.
  400. */
  401. byteAt: function(i) {
  402. // see implementations
  403. },
  404. /**
  405. * Get the next number with a given byte size.
  406. * @param {number} size the number of bytes to read.
  407. * @return {number} the corresponding number.
  408. */
  409. readInt: function(size) {
  410. var result = 0,
  411. i;
  412. this.checkOffset(size);
  413. for (i = this.index + size - 1; i >= this.index; i--) {
  414. result = (result << 8) + this.byteAt(i);
  415. }
  416. this.index += size;
  417. return result;
  418. },
  419. /**
  420. * Get the next string with a given byte size.
  421. * @param {number} size the number of bytes to read.
  422. * @return {string} the corresponding string.
  423. */
  424. readString: function(size) {
  425. return utils.transformTo("string", this.readData(size));
  426. },
  427. /**
  428. * Get raw data without conversion, <size> bytes.
  429. * @param {number} size the number of bytes to read.
  430. * @return {Object} the raw data, implementation specific.
  431. */
  432. readData: function(size) {
  433. // see implementations
  434. },
  435. /**
  436. * Find the last occurence of a zip signature (4 bytes).
  437. * @param {string} sig the signature to find.
  438. * @return {number} the index of the last occurence, -1 if not found.
  439. */
  440. lastIndexOfSignature: function(sig) {
  441. // see implementations
  442. },
  443. /**
  444. * Get the next date.
  445. * @return {Date} the date.
  446. */
  447. readDate: function() {
  448. var dostime = this.readInt(4);
  449. return new Date(
  450. ((dostime >> 25) & 0x7f) + 1980, // year
  451. ((dostime >> 21) & 0x0f) - 1, // month
  452. (dostime >> 16) & 0x1f, // day
  453. (dostime >> 11) & 0x1f, // hour
  454. (dostime >> 5) & 0x3f, // minute
  455. (dostime & 0x1f) << 1); // second
  456. }
  457. };
  458. module.exports = DataReader;
  459. },{"./utils":21}],6:[function(_dereq_,module,exports){
  460. 'use strict';
  461. exports.base64 = false;
  462. exports.binary = false;
  463. exports.dir = false;
  464. exports.createFolders = false;
  465. exports.date = null;
  466. exports.compression = null;
  467. exports.comment = null;
  468. },{}],7:[function(_dereq_,module,exports){
  469. 'use strict';
  470. var utils = _dereq_('./utils');
  471. /**
  472. * @deprecated
  473. * This function will be removed in a future version without replacement.
  474. */
  475. exports.string2binary = function(str) {
  476. return utils.string2binary(str);
  477. };
  478. /**
  479. * @deprecated
  480. * This function will be removed in a future version without replacement.
  481. */
  482. exports.string2Uint8Array = function(str) {
  483. return utils.transformTo("uint8array", str);
  484. };
  485. /**
  486. * @deprecated
  487. * This function will be removed in a future version without replacement.
  488. */
  489. exports.uint8Array2String = function(array) {
  490. return utils.transformTo("string", array);
  491. };
  492. /**
  493. * @deprecated
  494. * This function will be removed in a future version without replacement.
  495. */
  496. exports.string2Blob = function(str) {
  497. var buffer = utils.transformTo("arraybuffer", str);
  498. return utils.arrayBuffer2Blob(buffer);
  499. };
  500. /**
  501. * @deprecated
  502. * This function will be removed in a future version without replacement.
  503. */
  504. exports.arrayBuffer2Blob = function(buffer) {
  505. return utils.arrayBuffer2Blob(buffer);
  506. };
  507. /**
  508. * @deprecated
  509. * This function will be removed in a future version without replacement.
  510. */
  511. exports.transformTo = function(outputType, input) {
  512. return utils.transformTo(outputType, input);
  513. };
  514. /**
  515. * @deprecated
  516. * This function will be removed in a future version without replacement.
  517. */
  518. exports.getTypeOf = function(input) {
  519. return utils.getTypeOf(input);
  520. };
  521. /**
  522. * @deprecated
  523. * This function will be removed in a future version without replacement.
  524. */
  525. exports.checkSupport = function(type) {
  526. return utils.checkSupport(type);
  527. };
  528. /**
  529. * @deprecated
  530. * This value will be removed in a future version without replacement.
  531. */
  532. exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
  533. /**
  534. * @deprecated
  535. * This value will be removed in a future version without replacement.
  536. */
  537. exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
  538. /**
  539. * @deprecated
  540. * This function will be removed in a future version without replacement.
  541. */
  542. exports.pretty = function(str) {
  543. return utils.pretty(str);
  544. };
  545. /**
  546. * @deprecated
  547. * This function will be removed in a future version without replacement.
  548. */
  549. exports.findCompression = function(compressionMethod) {
  550. return utils.findCompression(compressionMethod);
  551. };
  552. /**
  553. * @deprecated
  554. * This function will be removed in a future version without replacement.
  555. */
  556. exports.isRegExp = function (object) {
  557. return utils.isRegExp(object);
  558. };
  559. },{"./utils":21}],8:[function(_dereq_,module,exports){
  560. 'use strict';
  561. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  562. var pako = _dereq_("pako");
  563. exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  564. exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  565. exports.magic = "\x08\x00";
  566. exports.compress = function(input) {
  567. return pako.deflateRaw(input);
  568. };
  569. exports.uncompress = function(input) {
  570. return pako.inflateRaw(input);
  571. };
  572. },{"pako":24}],9:[function(_dereq_,module,exports){
  573. 'use strict';
  574. var base64 = _dereq_('./base64');
  575. /**
  576. Usage:
  577. zip = new JSZip();
  578. zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
  579. zip.folder("images").file("smile.gif", base64Data, {base64: true});
  580. zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
  581. zip.remove("tempfile");
  582. base64zip = zip.generate();
  583. **/
  584. /**
  585. * Representation a of zip file in js
  586. * @constructor
  587. * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
  588. * @param {Object=} options the options for creating this objects (optional).
  589. */
  590. function JSZipSync(data, options) {
  591. // if this constructor is used without `new`, it adds `new` before itself:
  592. if(!(this instanceof JSZipSync)) return new JSZipSync(data, options);
  593. // object containing the files :
  594. // {
  595. // "folder/" : {...},
  596. // "folder/data.txt" : {...}
  597. // }
  598. this.files = {};
  599. this.comment = null;
  600. // Where we are in the hierarchy
  601. this.root = "";
  602. if (data) {
  603. this.load(data, options);
  604. }
  605. this.clone = function() {
  606. var newObj = new JSZipSync();
  607. for (var i in this) {
  608. if (typeof this[i] !== "function") {
  609. newObj[i] = this[i];
  610. }
  611. }
  612. return newObj;
  613. };
  614. }
  615. JSZipSync.prototype = _dereq_('./object');
  616. JSZipSync.prototype.load = _dereq_('./load');
  617. JSZipSync.support = _dereq_('./support');
  618. JSZipSync.defaults = _dereq_('./defaults');
  619. /**
  620. * @deprecated
  621. * This namespace will be removed in a future version without replacement.
  622. */
  623. JSZipSync.utils = _dereq_('./deprecatedPublicUtils');
  624. JSZipSync.base64 = {
  625. /**
  626. * @deprecated
  627. * This method will be removed in a future version without replacement.
  628. */
  629. encode : function(input) {
  630. return base64.encode(input);
  631. },
  632. /**
  633. * @deprecated
  634. * This method will be removed in a future version without replacement.
  635. */
  636. decode : function(input) {
  637. return base64.decode(input);
  638. }
  639. };
  640. JSZipSync.compressions = _dereq_('./compressions');
  641. module.exports = JSZipSync;
  642. },{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(_dereq_,module,exports){
  643. 'use strict';
  644. var base64 = _dereq_('./base64');
  645. var ZipEntries = _dereq_('./zipEntries');
  646. module.exports = function(data, options) {
  647. var files, zipEntries, i, input;
  648. options = options || {};
  649. if (options.base64) {
  650. data = base64.decode(data);
  651. }
  652. zipEntries = new ZipEntries(data, options);
  653. files = zipEntries.files;
  654. for (i = 0; i < files.length; i++) {
  655. input = files[i];
  656. this.file(input.fileName, input.decompressed, {
  657. binary: true,
  658. optimizedBinaryString: true,
  659. date: input.date,
  660. dir: input.dir,
  661. comment : input.fileComment.length ? input.fileComment : null,
  662. createFolders: options.createFolders
  663. });
  664. }
  665. if (zipEntries.zipComment.length) {
  666. this.comment = zipEntries.zipComment;
  667. }
  668. return this;
  669. };
  670. },{"./base64":1,"./zipEntries":22}],11:[function(_dereq_,module,exports){
  671. (function (Buffer){
  672. 'use strict';
  673. var Buffer_from = /*::(*/function(){}/*:: :any)*/;
  674. if(typeof Buffer !== 'undefined') {
  675. var nbfs = !Buffer.from;
  676. if(!nbfs) try { Buffer.from("foo", "utf8"); } catch(e) { nbfs = true; }
  677. Buffer_from = nbfs ? function(buf, enc) { return (enc) ? new Buffer(buf, enc) : new Buffer(buf); } : Buffer.from.bind(Buffer);
  678. // $FlowIgnore
  679. if(!Buffer.alloc) Buffer.alloc = function(n) { return new Buffer(n); };
  680. }
  681. module.exports = function(data, encoding){
  682. return typeof data == 'number' ? Buffer.alloc(data) : Buffer_from(data, encoding);
  683. };
  684. module.exports.test = function(b){
  685. return Buffer.isBuffer(b);
  686. };
  687. }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
  688. },{}],12:[function(_dereq_,module,exports){
  689. 'use strict';
  690. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  691. function NodeBufferReader(data) {
  692. this.data = data;
  693. this.length = this.data.length;
  694. this.index = 0;
  695. }
  696. NodeBufferReader.prototype = new Uint8ArrayReader();
  697. /**
  698. * @see DataReader.readData
  699. */
  700. NodeBufferReader.prototype.readData = function(size) {
  701. this.checkOffset(size);
  702. var result = this.data.slice(this.index, this.index + size);
  703. this.index += size;
  704. return result;
  705. };
  706. module.exports = NodeBufferReader;
  707. },{"./uint8ArrayReader":18}],13:[function(_dereq_,module,exports){
  708. 'use strict';
  709. var support = _dereq_('./support');
  710. var utils = _dereq_('./utils');
  711. var crc32 = _dereq_('./crc32');
  712. var signature = _dereq_('./signature');
  713. var defaults = _dereq_('./defaults');
  714. var base64 = _dereq_('./base64');
  715. var compressions = _dereq_('./compressions');
  716. var CompressedObject = _dereq_('./compressedObject');
  717. var nodeBuffer = _dereq_('./nodeBuffer');
  718. var utf8 = _dereq_('./utf8');
  719. var StringWriter = _dereq_('./stringWriter');
  720. var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter');
  721. /**
  722. * Returns the raw data of a ZipObject, decompress the content if necessary.
  723. * @param {ZipObject} file the file to use.
  724. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  725. */
  726. var getRawData = function(file) {
  727. if (file._data instanceof CompressedObject) {
  728. file._data = file._data.getContent();
  729. file.options.binary = true;
  730. file.options.base64 = false;
  731. if (utils.getTypeOf(file._data) === "uint8array") {
  732. var copy = file._data;
  733. // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
  734. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
  735. file._data = new Uint8Array(copy.length);
  736. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  737. if (copy.length !== 0) {
  738. file._data.set(copy, 0);
  739. }
  740. }
  741. }
  742. return file._data;
  743. };
  744. /**
  745. * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
  746. * @param {ZipObject} file the file to use.
  747. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  748. */
  749. var getBinaryData = function(file) {
  750. var result = getRawData(file),
  751. type = utils.getTypeOf(result);
  752. if (type === "string") {
  753. if (!file.options.binary) {
  754. // unicode text !
  755. // unicode string => binary string is a painful process, check if we can avoid it.
  756. if (support.nodebuffer) {
  757. return nodeBuffer(result, "utf-8");
  758. }
  759. }
  760. return file.asBinary();
  761. }
  762. return result;
  763. };
  764. /**
  765. * Transform this._data into a string.
  766. * @param {function} filter a function String -> String, applied if not null on the result.
  767. * @return {String} the string representing this._data.
  768. */
  769. var dataToString = function(asUTF8) {
  770. var result = getRawData(this);
  771. if (result === null || typeof result === "undefined") {
  772. return "";
  773. }
  774. // if the data is a base64 string, we decode it before checking the encoding !
  775. if (this.options.base64) {
  776. result = base64.decode(result);
  777. }
  778. if (asUTF8 && this.options.binary) {
  779. // JSZip.prototype.utf8decode supports arrays as input
  780. // skip to array => string step, utf8decode will do it.
  781. result = out.utf8decode(result);
  782. }
  783. else {
  784. // no utf8 transformation, do the array => string step.
  785. result = utils.transformTo("string", result);
  786. }
  787. if (!asUTF8 && !this.options.binary) {
  788. result = utils.transformTo("string", out.utf8encode(result));
  789. }
  790. return result;
  791. };
  792. /**
  793. * A simple object representing a file in the zip file.
  794. * @constructor
  795. * @param {string} name the name of the file
  796. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  797. * @param {Object} options the options of the file
  798. */
  799. var ZipObject = function(name, data, options) {
  800. this.name = name;
  801. this.dir = options.dir;
  802. this.date = options.date;
  803. this.comment = options.comment;
  804. this._data = data;
  805. this.options = options;
  806. /*
  807. * This object contains initial values for dir and date.
  808. * With them, we can check if the user changed the deprecated metadata in
  809. * `ZipObject#options` or not.
  810. */
  811. this._initialMetadata = {
  812. dir : options.dir,
  813. date : options.date
  814. };
  815. };
  816. ZipObject.prototype = {
  817. /**
  818. * Return the content as UTF8 string.
  819. * @return {string} the UTF8 string.
  820. */
  821. asText: function() {
  822. return dataToString.call(this, true);
  823. },
  824. /**
  825. * Returns the binary content.
  826. * @return {string} the content as binary.
  827. */
  828. asBinary: function() {
  829. return dataToString.call(this, false);
  830. },
  831. /**
  832. * Returns the content as a nodejs Buffer.
  833. * @return {Buffer} the content as a Buffer.
  834. */
  835. asNodeBuffer: function() {
  836. var result = getBinaryData(this);
  837. return utils.transformTo("nodebuffer", result);
  838. },
  839. /**
  840. * Returns the content as an Uint8Array.
  841. * @return {Uint8Array} the content as an Uint8Array.
  842. */
  843. asUint8Array: function() {
  844. var result = getBinaryData(this);
  845. return utils.transformTo("uint8array", result);
  846. },
  847. /**
  848. * Returns the content as an ArrayBuffer.
  849. * @return {ArrayBuffer} the content as an ArrayBufer.
  850. */
  851. asArrayBuffer: function() {
  852. return this.asUint8Array().buffer;
  853. }
  854. };
  855. /**
  856. * Transform an integer into a string in hexadecimal.
  857. * @private
  858. * @param {number} dec the number to convert.
  859. * @param {number} bytes the number of bytes to generate.
  860. * @returns {string} the result.
  861. */
  862. var decToHex = function(dec, bytes) {
  863. var hex = "",
  864. i;
  865. for (i = 0; i < bytes; i++) {
  866. hex += String.fromCharCode(dec & 0xff);
  867. dec = dec >>> 8;
  868. }
  869. return hex;
  870. };
  871. /**
  872. * Merge the objects passed as parameters into a new one.
  873. * @private
  874. * @param {...Object} var_args All objects to merge.
  875. * @return {Object} a new object with the data of the others.
  876. */
  877. var extend = function() {
  878. var result = {}, i, attr;
  879. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  880. for (attr in arguments[i]) {
  881. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  882. result[attr] = arguments[i][attr];
  883. }
  884. }
  885. }
  886. return result;
  887. };
  888. /**
  889. * Transforms the (incomplete) options from the user into the complete
  890. * set of options to create a file.
  891. * @private
  892. * @param {Object} o the options from the user.
  893. * @return {Object} the complete set of options.
  894. */
  895. var prepareFileAttrs = function(o) {
  896. o = o || {};
  897. if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
  898. o.binary = true;
  899. }
  900. o = extend(o, defaults);
  901. o.date = o.date || new Date();
  902. if (o.compression !== null) o.compression = o.compression.toUpperCase();
  903. return o;
  904. };
  905. /**
  906. * Add a file in the current folder.
  907. * @private
  908. * @param {string} name the name of the file
  909. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  910. * @param {Object} o the options of the file
  911. * @return {Object} the new file.
  912. */
  913. var fileAdd = function(name, data, o) {
  914. // be sure sub folders exist
  915. var dataType = utils.getTypeOf(data),
  916. parent;
  917. o = prepareFileAttrs(o);
  918. if (o.createFolders && (parent = parentFolder(name))) {
  919. folderAdd.call(this, parent, true);
  920. }
  921. if (o.dir || data === null || typeof data === "undefined") {
  922. o.base64 = false;
  923. o.binary = false;
  924. data = null;
  925. }
  926. else if (dataType === "string") {
  927. if (o.binary && !o.base64) {
  928. // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
  929. if (o.optimizedBinaryString !== true) {
  930. // this is a string, not in a base64 format.
  931. // Be sure that this is a correct "binary string"
  932. data = utils.string2binary(data);
  933. }
  934. }
  935. }
  936. else { // arraybuffer, uint8array, ...
  937. o.base64 = false;
  938. o.binary = true;
  939. if (!dataType && !(data instanceof CompressedObject)) {
  940. throw new Error("The data of '" + name + "' is in an unsupported format !");
  941. }
  942. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  943. if (dataType === "arraybuffer") {
  944. data = utils.transformTo("uint8array", data);
  945. }
  946. }
  947. var object = new ZipObject(name, data, o);
  948. this.files[name] = object;
  949. return object;
  950. };
  951. /**
  952. * Find the parent folder of the path.
  953. * @private
  954. * @param {string} path the path to use
  955. * @return {string} the parent folder, or ""
  956. */
  957. var parentFolder = function (path) {
  958. if (path.slice(-1) == '/') {
  959. path = path.substring(0, path.length - 1);
  960. }
  961. var lastSlash = path.lastIndexOf('/');
  962. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  963. };
  964. /**
  965. * Add a (sub) folder in the current folder.
  966. * @private
  967. * @param {string} name the folder's name
  968. * @param {boolean=} [createFolders] If true, automatically create sub
  969. * folders. Defaults to false.
  970. * @return {Object} the new folder.
  971. */
  972. var folderAdd = function(name, createFolders) {
  973. // Check the name ends with a /
  974. if (name.slice(-1) != "/") {
  975. name += "/"; // IE doesn't like substr(-1)
  976. }
  977. createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
  978. // Does this folder already exist?
  979. if (!this.files[name]) {
  980. fileAdd.call(this, name, null, {
  981. dir: true,
  982. createFolders: createFolders
  983. });
  984. }
  985. return this.files[name];
  986. };
  987. /**
  988. * Generate a JSZip.CompressedObject for a given zipOject.
  989. * @param {ZipObject} file the object to read.
  990. * @param {JSZip.compression} compression the compression to use.
  991. * @return {JSZip.CompressedObject} the compressed result.
  992. */
  993. var generateCompressedObjectFrom = function(file, compression) {
  994. var result = new CompressedObject(),
  995. content;
  996. // the data has not been decompressed, we might reuse things !
  997. if (file._data instanceof CompressedObject) {
  998. result.uncompressedSize = file._data.uncompressedSize;
  999. result.crc32 = file._data.crc32;
  1000. if (result.uncompressedSize === 0 || file.dir) {
  1001. compression = compressions['STORE'];
  1002. result.compressedContent = "";
  1003. result.crc32 = 0;
  1004. }
  1005. else if (file._data.compressionMethod === compression.magic) {
  1006. result.compressedContent = file._data.getCompressedContent();
  1007. }
  1008. else {
  1009. content = file._data.getContent();
  1010. // need to decompress / recompress
  1011. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content));
  1012. }
  1013. }
  1014. else {
  1015. // have uncompressed data
  1016. content = getBinaryData(file);
  1017. if (!content || content.length === 0 || file.dir) {
  1018. compression = compressions['STORE'];
  1019. content = "";
  1020. }
  1021. result.uncompressedSize = content.length;
  1022. result.crc32 = crc32(content);
  1023. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content));
  1024. }
  1025. result.compressedSize = result.compressedContent.length;
  1026. result.compressionMethod = compression.magic;
  1027. return result;
  1028. };
  1029. /**
  1030. * Generate the various parts used in the construction of the final zip file.
  1031. * @param {string} name the file name.
  1032. * @param {ZipObject} file the file content.
  1033. * @param {JSZip.CompressedObject} compressedObject the compressed object.
  1034. * @param {number} offset the current offset from the start of the zip file.
  1035. * @return {object} the zip parts.
  1036. */
  1037. var generateZipParts = function(name, file, compressedObject, offset) {
  1038. var data = compressedObject.compressedContent,
  1039. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  1040. comment = file.comment || "",
  1041. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  1042. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  1043. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  1044. o = file.options,
  1045. dosTime,
  1046. dosDate,
  1047. extraFields = "",
  1048. unicodePathExtraField = "",
  1049. unicodeCommentExtraField = "",
  1050. dir, date;
  1051. // handle the deprecated options.dir
  1052. if (file._initialMetadata.dir !== file.dir) {
  1053. dir = file.dir;
  1054. } else {
  1055. dir = o.dir;
  1056. }
  1057. // handle the deprecated options.date
  1058. if(file._initialMetadata.date !== file.date) {
  1059. date = file.date;
  1060. } else {
  1061. date = o.date;
  1062. }
  1063. dosTime = date.getHours();
  1064. dosTime = dosTime << 6;
  1065. dosTime = dosTime | date.getMinutes();
  1066. dosTime = dosTime << 5;
  1067. dosTime = dosTime | date.getSeconds() / 2;
  1068. dosDate = date.getFullYear() - 1980;
  1069. dosDate = dosDate << 4;
  1070. dosDate = dosDate | (date.getMonth() + 1);
  1071. dosDate = dosDate << 5;
  1072. dosDate = dosDate | date.getDate();
  1073. if (useUTF8ForFileName) {
  1074. // set the unicode path extra field. unzip needs at least one extra
  1075. // field to correctly handle unicode path, so using the path is as good
  1076. // as any other information. This could improve the situation with
  1077. // other archive managers too.
  1078. // This field is usually used without the utf8 flag, with a non
  1079. // unicode path in the header (winrar, winzip). This helps (a bit)
  1080. // with the messy Windows' default compressed folders feature but
  1081. // breaks on p7zip which doesn't seek the unicode path extra field.
  1082. // So for now, UTF-8 everywhere !
  1083. unicodePathExtraField =
  1084. // Version
  1085. decToHex(1, 1) +
  1086. // NameCRC32
  1087. decToHex(crc32(utfEncodedFileName), 4) +
  1088. // UnicodeName
  1089. utfEncodedFileName;
  1090. extraFields +=
  1091. // Info-ZIP Unicode Path Extra Field
  1092. "\x75\x70" +
  1093. // size
  1094. decToHex(unicodePathExtraField.length, 2) +
  1095. // content
  1096. unicodePathExtraField;
  1097. }
  1098. if(useUTF8ForComment) {
  1099. unicodeCommentExtraField =
  1100. // Version
  1101. decToHex(1, 1) +
  1102. // CommentCRC32
  1103. decToHex(this.crc32(utfEncodedComment), 4) +
  1104. // UnicodeName
  1105. utfEncodedComment;
  1106. extraFields +=
  1107. // Info-ZIP Unicode Path Extra Field
  1108. "\x75\x63" +
  1109. // size
  1110. decToHex(unicodeCommentExtraField.length, 2) +
  1111. // content
  1112. unicodeCommentExtraField;
  1113. }
  1114. var header = "";
  1115. // version needed to extract
  1116. header += "\x0A\x00";
  1117. // general purpose bit flag
  1118. // set bit 11 if utf8
  1119. header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
  1120. // compression method
  1121. header += compressedObject.compressionMethod;
  1122. // last mod file time
  1123. header += decToHex(dosTime, 2);
  1124. // last mod file date
  1125. header += decToHex(dosDate, 2);
  1126. // crc-32
  1127. header += decToHex(compressedObject.crc32, 4);
  1128. // compressed size
  1129. header += decToHex(compressedObject.compressedSize, 4);
  1130. // uncompressed size
  1131. header += decToHex(compressedObject.uncompressedSize, 4);
  1132. // file name length
  1133. header += decToHex(utfEncodedFileName.length, 2);
  1134. // extra field length
  1135. header += decToHex(extraFields.length, 2);
  1136. var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
  1137. var dirRecord = signature.CENTRAL_FILE_HEADER +
  1138. // version made by (00: DOS)
  1139. "\x14\x00" +
  1140. // file header (common to file and central directory)
  1141. header +
  1142. // file comment length
  1143. decToHex(utfEncodedComment.length, 2) +
  1144. // disk number start
  1145. "\x00\x00" +
  1146. // internal file attributes TODO
  1147. "\x00\x00" +
  1148. // external file attributes
  1149. (dir === true ? "\x10\x00\x00\x00" : "\x00\x00\x00\x00") +
  1150. // relative offset of local header
  1151. decToHex(offset, 4) +
  1152. // file name
  1153. utfEncodedFileName +
  1154. // extra field
  1155. extraFields +
  1156. // file comment
  1157. utfEncodedComment;
  1158. return {
  1159. fileRecord: fileRecord,
  1160. dirRecord: dirRecord,
  1161. compressedObject: compressedObject
  1162. };
  1163. };
  1164. // return the actual prototype of JSZip
  1165. var out = {
  1166. /**
  1167. * Read an existing zip and merge the data in the current JSZip object.
  1168. * The implementation is in jszip-load.js, don't forget to include it.
  1169. * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
  1170. * @param {Object} options Options for loading the stream.
  1171. * options.base64 : is the stream in base64 ? default : false
  1172. * @return {JSZip} the current JSZip object
  1173. */
  1174. load: function(stream, options) {
  1175. throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
  1176. },
  1177. /**
  1178. * Filter nested files/folders with the specified function.
  1179. * @param {Function} search the predicate to use :
  1180. * function (relativePath, file) {...}
  1181. * It takes 2 arguments : the relative path and the file.
  1182. * @return {Array} An array of matching elements.
  1183. */
  1184. filter: function(search) {
  1185. var result = [],
  1186. filename, relativePath, file, fileClone;
  1187. for (filename in this.files) {
  1188. if (!this.files.hasOwnProperty(filename)) {
  1189. continue;
  1190. }
  1191. file = this.files[filename];
  1192. // return a new object, don't let the user mess with our internal objects :)
  1193. fileClone = new ZipObject(file.name, file._data, extend(file.options));
  1194. relativePath = filename.slice(this.root.length, filename.length);
  1195. if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
  1196. search(relativePath, fileClone)) { // and the file matches the function
  1197. result.push(fileClone);
  1198. }
  1199. }
  1200. return result;
  1201. },
  1202. /**
  1203. * Add a file to the zip file, or search a file.
  1204. * @param {string|RegExp} name The name of the file to add (if data is defined),
  1205. * the name of the file to find (if no data) or a regex to match files.
  1206. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  1207. * @param {Object} o File options
  1208. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  1209. * a file (when searching by string) or an array of files (when searching by regex).
  1210. */
  1211. file: function(name, data, o) {
  1212. if (arguments.length === 1) {
  1213. if (utils.isRegExp(name)) {
  1214. var regexp = name;
  1215. return this.filter(function(relativePath, file) {
  1216. return !file.dir && regexp.test(relativePath);
  1217. });
  1218. }
  1219. else { // text
  1220. return this.filter(function(relativePath, file) {
  1221. return !file.dir && relativePath === name;
  1222. })[0] || null;
  1223. }
  1224. }
  1225. else { // more than one argument : we have data !
  1226. name = this.root + name;
  1227. fileAdd.call(this, name, data, o);
  1228. }
  1229. return this;
  1230. },
  1231. /**
  1232. * Add a directory to the zip file, or search.
  1233. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  1234. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  1235. */
  1236. folder: function(arg) {
  1237. if (!arg) {
  1238. return this;
  1239. }
  1240. if (utils.isRegExp(arg)) {
  1241. return this.filter(function(relativePath, file) {
  1242. return file.dir && arg.test(relativePath);
  1243. });
  1244. }
  1245. // else, name is a new folder
  1246. var name = this.root + arg;
  1247. var newFolder = folderAdd.call(this, name);
  1248. // Allow chaining by returning a new object with this folder as the root
  1249. var ret = this.clone();
  1250. ret.root = newFolder.name;
  1251. return ret;
  1252. },
  1253. /**
  1254. * Delete a file, or a directory and all sub-files, from the zip
  1255. * @param {string} name the name of the file to delete
  1256. * @return {JSZip} this JSZip object
  1257. */
  1258. remove: function(name) {
  1259. name = this.root + name;
  1260. var file = this.files[name];
  1261. if (!file) {
  1262. // Look for any folders
  1263. if (name.slice(-1) != "/") {
  1264. name += "/";
  1265. }
  1266. file = this.files[name];
  1267. }
  1268. if (file && !file.dir) {
  1269. // file
  1270. delete this.files[name];
  1271. } else {
  1272. // maybe a folder, delete recursively
  1273. var kids = this.filter(function(relativePath, file) {
  1274. return file.name.slice(0, name.length) === name;
  1275. });
  1276. for (var i = 0; i < kids.length; i++) {
  1277. delete this.files[kids[i].name];
  1278. }
  1279. }
  1280. return this;
  1281. },
  1282. /**
  1283. * Generate the complete zip file
  1284. * @param {Object} options the options to generate the zip file :
  1285. * - base64, (deprecated, use type instead) true to generate base64.
  1286. * - compression, "STORE" by default.
  1287. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1288. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  1289. */
  1290. generate: function(options) {
  1291. options = extend(options || {}, {
  1292. base64: true,
  1293. compression: "STORE",
  1294. type: "base64",
  1295. comment: null
  1296. });
  1297. utils.checkSupport(options.type);
  1298. var zipData = [],
  1299. localDirLength = 0,
  1300. centralDirLength = 0,
  1301. writer, i,
  1302. utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
  1303. // first, generate all the zip parts.
  1304. for (var name in this.files) {
  1305. if (!this.files.hasOwnProperty(name)) {
  1306. continue;
  1307. }
  1308. var file = this.files[name];
  1309. var compressionName = file.options.compression || options.compression.toUpperCase();
  1310. var compression = compressions[compressionName];
  1311. if (!compression) {
  1312. throw new Error(compressionName + " is not a valid compression method !");
  1313. }
  1314. var compressedObject = generateCompressedObjectFrom.call(this, file, compression);
  1315. var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength);
  1316. localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
  1317. centralDirLength += zipPart.dirRecord.length;
  1318. zipData.push(zipPart);
  1319. }
  1320. var dirEnd = "";
  1321. // end of central dir signature
  1322. dirEnd = signature.CENTRAL_DIRECTORY_END +
  1323. // number of this disk
  1324. "\x00\x00" +
  1325. // number of the disk with the start of the central directory
  1326. "\x00\x00" +
  1327. // total number of entries in the central directory on this disk
  1328. decToHex(zipData.length, 2) +
  1329. // total number of entries in the central directory
  1330. decToHex(zipData.length, 2) +
  1331. // size of the central directory 4 bytes
  1332. decToHex(centralDirLength, 4) +
  1333. // offset of start of central directory with respect to the starting disk number
  1334. decToHex(localDirLength, 4) +
  1335. // .ZIP file comment length
  1336. decToHex(utfEncodedComment.length, 2) +
  1337. // .ZIP file comment
  1338. utfEncodedComment;
  1339. // we have all the parts (and the total length)
  1340. // time to create a writer !
  1341. var typeName = options.type.toLowerCase();
  1342. if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
  1343. writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
  1344. }else{
  1345. writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
  1346. }
  1347. for (i = 0; i < zipData.length; i++) {
  1348. writer.append(zipData[i].fileRecord);
  1349. writer.append(zipData[i].compressedObject.compressedContent);
  1350. }
  1351. for (i = 0; i < zipData.length; i++) {
  1352. writer.append(zipData[i].dirRecord);
  1353. }
  1354. writer.append(dirEnd);
  1355. var zip = writer.finalize();
  1356. switch(options.type.toLowerCase()) {
  1357. // case "zip is an Uint8Array"
  1358. case "uint8array" :
  1359. case "arraybuffer" :
  1360. case "nodebuffer" :
  1361. return utils.transformTo(options.type.toLowerCase(), zip);
  1362. case "blob" :
  1363. return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip));
  1364. // case "zip is a string"
  1365. case "base64" :
  1366. return (options.base64) ? base64.encode(zip) : zip;
  1367. default : // case "string" :
  1368. return zip;
  1369. }
  1370. },
  1371. /**
  1372. * @deprecated
  1373. * This method will be removed in a future version without replacement.
  1374. */
  1375. crc32: function (input, crc) {
  1376. return crc32(input, crc);
  1377. },
  1378. /**
  1379. * @deprecated
  1380. * This method will be removed in a future version without replacement.
  1381. */
  1382. utf8encode: function (string) {
  1383. return utils.transformTo("string", utf8.utf8encode(string));
  1384. },
  1385. /**
  1386. * @deprecated
  1387. * This method will be removed in a future version without replacement.
  1388. */
  1389. utf8decode: function (input) {
  1390. return utf8.utf8decode(input);
  1391. }
  1392. };
  1393. module.exports = out;
  1394. },{"./base64":1,"./compressedObject":2,"./compressions":3,"./crc32":4,"./defaults":6,"./nodeBuffer":11,"./signature":14,"./stringWriter":16,"./support":17,"./uint8ArrayWriter":19,"./utf8":20,"./utils":21}],14:[function(_dereq_,module,exports){
  1395. 'use strict';
  1396. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  1397. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  1398. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  1399. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  1400. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  1401. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  1402. },{}],15:[function(_dereq_,module,exports){
  1403. 'use strict';
  1404. var DataReader = _dereq_('./dataReader');
  1405. var utils = _dereq_('./utils');
  1406. function StringReader(data, optimizedBinaryString) {
  1407. this.data = data;
  1408. if (!optimizedBinaryString) {
  1409. this.data = utils.string2binary(this.data);
  1410. }
  1411. this.length = this.data.length;
  1412. this.index = 0;
  1413. }
  1414. StringReader.prototype = new DataReader();
  1415. /**
  1416. * @see DataReader.byteAt
  1417. */
  1418. StringReader.prototype.byteAt = function(i) {
  1419. return this.data.charCodeAt(i);
  1420. };
  1421. /**
  1422. * @see DataReader.lastIndexOfSignature
  1423. */
  1424. StringReader.prototype.lastIndexOfSignature = function(sig) {
  1425. return this.data.lastIndexOf(sig);
  1426. };
  1427. /**
  1428. * @see DataReader.readData
  1429. */
  1430. StringReader.prototype.readData = function(size) {
  1431. this.checkOffset(size);
  1432. // this will work because the constructor applied the "& 0xff" mask.
  1433. var result = this.data.slice(this.index, this.index + size);
  1434. this.index += size;
  1435. return result;
  1436. };
  1437. module.exports = StringReader;
  1438. },{"./dataReader":5,"./utils":21}],16:[function(_dereq_,module,exports){
  1439. 'use strict';
  1440. var utils = _dereq_('./utils');
  1441. /**
  1442. * An object to write any content to a string.
  1443. * @constructor
  1444. */
  1445. var StringWriter = function() {
  1446. this.data = [];
  1447. };
  1448. StringWriter.prototype = {
  1449. /**
  1450. * Append any content to the current string.
  1451. * @param {Object} input the content to add.
  1452. */
  1453. append: function(input) {
  1454. input = utils.transformTo("string", input);
  1455. this.data.push(input);
  1456. },
  1457. /**
  1458. * Finalize the construction an return the result.
  1459. * @return {string} the generated string.
  1460. */
  1461. finalize: function() {
  1462. return this.data.join("");
  1463. }
  1464. };
  1465. module.exports = StringWriter;
  1466. },{"./utils":21}],17:[function(_dereq_,module,exports){
  1467. (function (Buffer){
  1468. 'use strict';
  1469. exports.base64 = true;
  1470. exports.array = true;
  1471. exports.string = true;
  1472. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  1473. // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
  1474. // Browserify will provide a Buffer implementation for browsers, which is
  1475. // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
  1476. exports.nodebuffer = typeof Buffer !== "undefined";
  1477. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  1478. exports.uint8array = typeof Uint8Array !== "undefined";
  1479. if (typeof ArrayBuffer === "undefined") {
  1480. exports.blob = false;
  1481. }
  1482. else {
  1483. var buffer = new ArrayBuffer(0);
  1484. try {
  1485. exports.blob = new Blob([buffer], {
  1486. type: "application/zip"
  1487. }).size === 0;
  1488. }
  1489. catch (e) {
  1490. try {
  1491. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  1492. var builder = new Builder();
  1493. builder.append(buffer);
  1494. exports.blob = builder.getBlob('application/zip').size === 0;
  1495. }
  1496. catch (e) {
  1497. exports.blob = false;
  1498. }
  1499. }
  1500. }
  1501. }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
  1502. },{}],18:[function(_dereq_,module,exports){
  1503. 'use strict';
  1504. var DataReader = _dereq_('./dataReader');
  1505. function Uint8ArrayReader(data) {
  1506. if (data) {
  1507. this.data = data;
  1508. this.length = this.data.length;
  1509. this.index = 0;
  1510. }
  1511. }
  1512. Uint8ArrayReader.prototype = new DataReader();
  1513. /**
  1514. * @see DataReader.byteAt
  1515. */
  1516. Uint8ArrayReader.prototype.byteAt = function(i) {
  1517. return this.data[i];
  1518. };
  1519. /**
  1520. * @see DataReader.lastIndexOfSignature
  1521. */
  1522. Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  1523. var sig0 = sig.charCodeAt(0),
  1524. sig1 = sig.charCodeAt(1),
  1525. sig2 = sig.charCodeAt(2),
  1526. sig3 = sig.charCodeAt(3);
  1527. for (var i = this.length - 4; i >= 0; --i) {
  1528. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  1529. return i;
  1530. }
  1531. }
  1532. return -1;
  1533. };
  1534. /**
  1535. * @see DataReader.readData
  1536. */
  1537. Uint8ArrayReader.prototype.readData = function(size) {
  1538. this.checkOffset(size);
  1539. if(size === 0) {
  1540. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  1541. return new Uint8Array(0);
  1542. }
  1543. var result = this.data.subarray(this.index, this.index + size);
  1544. this.index += size;
  1545. return result;
  1546. };
  1547. module.exports = Uint8ArrayReader;
  1548. },{"./dataReader":5}],19:[function(_dereq_,module,exports){
  1549. 'use strict';
  1550. var utils = _dereq_('./utils');
  1551. /**
  1552. * An object to write any content to an Uint8Array.
  1553. * @constructor
  1554. * @param {number} length The length of the array.
  1555. */
  1556. var Uint8ArrayWriter = function(length) {
  1557. this.data = new Uint8Array(length);
  1558. this.index = 0;
  1559. };
  1560. Uint8ArrayWriter.prototype = {
  1561. /**
  1562. * Append any content to the current array.
  1563. * @param {Object} input the content to add.
  1564. */
  1565. append: function(input) {
  1566. if (input.length !== 0) {
  1567. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  1568. input = utils.transformTo("uint8array", input);
  1569. this.data.set(input, this.index);
  1570. this.index += input.length;
  1571. }
  1572. },
  1573. /**
  1574. * Finalize the construction an return the result.
  1575. * @return {Uint8Array} the generated array.
  1576. */
  1577. finalize: function() {
  1578. return this.data;
  1579. }
  1580. };
  1581. module.exports = Uint8ArrayWriter;
  1582. },{"./utils":21}],20:[function(_dereq_,module,exports){
  1583. 'use strict';
  1584. var utils = _dereq_('./utils');
  1585. var support = _dereq_('./support');
  1586. var nodeBuffer = _dereq_('./nodeBuffer');
  1587. /**
  1588. * The following functions come from pako, from pako/lib/utils/strings
  1589. * released under the MIT license, see pako https://github.com/nodeca/pako/
  1590. */
  1591. // Table with utf8 lengths (calculated by first byte of sequence)
  1592. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  1593. // because max possible codepoint is 0x10ffff
  1594. var _utf8len = new Array(256);
  1595. for (var i=0; i<256; i++) {
  1596. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  1597. }
  1598. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  1599. // convert string to array (typed, when possible)
  1600. var string2buf = function (str) {
  1601. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  1602. // count binary size
  1603. for (m_pos = 0; m_pos < str_len; m_pos++) {
  1604. c = str.charCodeAt(m_pos);
  1605. if (((c & 0xfc00) === 0xd800) && (m_pos+1 < str_len)) {
  1606. c2 = str.charCodeAt(m_pos+1);
  1607. if ((c2 & 0xfc00) === 0xdc00) {
  1608. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  1609. m_pos++;
  1610. }
  1611. }
  1612. buf_len += (c < 0x80) ? 1 : ((c < 0x800) ? 2 : ((c < 0x10000) ? 3 : 4));
  1613. }
  1614. // allocate buffer
  1615. if (support.uint8array) {
  1616. buf = new Uint8Array(buf_len);
  1617. } else {
  1618. buf = new Array(buf_len);
  1619. }
  1620. // convert
  1621. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  1622. c = str.charCodeAt(m_pos);
  1623. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  1624. c2 = str.charCodeAt(m_pos+1);
  1625. if ((c2 & 0xfc00) === 0xdc00) {
  1626. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  1627. m_pos++;
  1628. }
  1629. }
  1630. if (c < 0x80) {
  1631. /* one byte */
  1632. buf[i++] = c;
  1633. } else if (c < 0x800) {
  1634. /* two bytes */
  1635. buf[i++] = 0xC0 | (c >>> 6);
  1636. buf[i++] = 0x80 | (c & 0x3f);
  1637. } else if (c < 0x10000) {
  1638. /* three bytes */
  1639. buf[i++] = 0xE0 | (c >>> 12);
  1640. buf[i++] = 0x80 | ((c >>> 6) & 0x3f);
  1641. buf[i++] = 0x80 | (c & 0x3f);
  1642. } else {
  1643. /* four bytes */
  1644. buf[i++] = 0xf0 | (c >>> 18);
  1645. buf[i++] = 0x80 | ((c >>> 12) & 0x3f);
  1646. buf[i++] = 0x80 | ((c >>> 6) & 0x3f);
  1647. buf[i++] = 0x80 | (c & 0x3f);
  1648. }
  1649. }
  1650. return buf;
  1651. };
  1652. // Calculate max possible position in utf8 buffer,
  1653. // that will not break sequence. If that's not possible
  1654. // - (very small limits) return max size as is.
  1655. //
  1656. // buf[] - utf8 bytes array
  1657. // max - length limit (mandatory);
  1658. var utf8border = function(buf, max) {
  1659. var pos;
  1660. max = max || buf.length;
  1661. if (max > buf.length) { max = buf.length; }
  1662. // go back from last position, until start of sequence found
  1663. pos = max-1;
  1664. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  1665. // Fuckup - very small and broken sequence,
  1666. // return max, because we should return something anyway.
  1667. if (pos < 0) { return max; }
  1668. // If we came to start of buffer - that means vuffer is too small,
  1669. // return max too.
  1670. if (pos === 0) { return max; }
  1671. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  1672. };
  1673. // convert array to string
  1674. var buf2string = function (buf) {
  1675. var str, i, out, c, c_len;
  1676. var len = buf.length;
  1677. // Reserve max possible length (2 words per char)
  1678. // NB: by unknown reasons, Array is significantly faster for
  1679. // String.fromCharCode.apply than Uint16Array.
  1680. var utf16buf = new Array(len*2);
  1681. for (out=0, i=0; i<len;) {
  1682. c = buf[i++];
  1683. // quick process ascii
  1684. if (c < 0x80) { utf16buf[out++] = c; continue; }
  1685. c_len = _utf8len[c];
  1686. // skip 5 & 6 byte codes
  1687. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  1688. // apply mask on first byte
  1689. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  1690. // join the rest
  1691. while (c_len > 1 && i < len) {
  1692. c = (c << 6) | (buf[i++] & 0x3f);
  1693. c_len--;
  1694. }
  1695. // terminated by end of string?
  1696. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  1697. if (c < 0x10000) {
  1698. utf16buf[out++] = c;
  1699. } else {
  1700. c -= 0x10000;
  1701. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  1702. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  1703. }
  1704. }
  1705. // shrinkBuf(utf16buf, out)
  1706. if (utf16buf.length !== out) {
  1707. if(utf16buf.subarray) {
  1708. utf16buf = utf16buf.subarray(0, out);
  1709. } else {
  1710. utf16buf.length = out;
  1711. }
  1712. }
  1713. // return String.fromCharCode.apply(null, utf16buf);
  1714. return utils.applyFromCharCode(utf16buf);
  1715. };
  1716. // That's all for the pako functions.
  1717. /**
  1718. * Transform a javascript string into an array (typed if possible) of bytes,
  1719. * UTF-8 encoded.
  1720. * @param {String} str the string to encode
  1721. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  1722. */
  1723. exports.utf8encode = function utf8encode(str) {
  1724. if (support.nodebuffer) {
  1725. return nodeBuffer(str, "utf-8");
  1726. }
  1727. return string2buf(str);
  1728. };
  1729. /**
  1730. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  1731. * string into a javascript string.
  1732. * @param {Array|Uint8Array|Buffer} buf the data de decode
  1733. * @return {String} the decoded string.
  1734. */
  1735. exports.utf8decode = function utf8decode(buf) {
  1736. if (support.nodebuffer) {
  1737. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  1738. }
  1739. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  1740. // return buf2string(buf);
  1741. // Chrome prefers to work with "small" chunks of data
  1742. // for the method buf2string.
  1743. // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
  1744. var result = [], k = 0, len = buf.length, chunk = 65536;
  1745. while (k < len) {
  1746. var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
  1747. if (support.uint8array) {
  1748. result.push(buf2string(buf.subarray(k, nextBoundary)));
  1749. } else {
  1750. result.push(buf2string(buf.slice(k, nextBoundary)));
  1751. }
  1752. k = nextBoundary;
  1753. }
  1754. return result.join("");
  1755. };
  1756. // vim: set shiftwidth=4 softtabstop=4:
  1757. },{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(_dereq_,module,exports){
  1758. 'use strict';
  1759. var support = _dereq_('./support');
  1760. var compressions = _dereq_('./compressions');
  1761. var nodeBuffer = _dereq_('./nodeBuffer');
  1762. /**
  1763. * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
  1764. * @param {string} str the string to transform.
  1765. * @return {String} the binary string.
  1766. */
  1767. exports.string2binary = function(str) {
  1768. var result = "";
  1769. for (var i = 0; i < str.length; i++) {
  1770. result += String.fromCharCode(str.charCodeAt(i) & 0xff);
  1771. }
  1772. return result;
  1773. };
  1774. exports.arrayBuffer2Blob = function(buffer) {
  1775. exports.checkSupport("blob");
  1776. try {
  1777. // Blob constructor
  1778. return new Blob([buffer], {
  1779. type: "application/zip"
  1780. });
  1781. }
  1782. catch (e) {
  1783. try {
  1784. // deprecated, browser only, old way
  1785. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  1786. var builder = new Builder();
  1787. builder.append(buffer);
  1788. return builder.getBlob('application/zip');
  1789. }
  1790. catch (e) {
  1791. // well, fuck ?!
  1792. throw new Error("Bug : can't construct the Blob.");
  1793. }
  1794. }
  1795. };
  1796. /**
  1797. * The identity function.
  1798. * @param {Object} input the input.
  1799. * @return {Object} the same input.
  1800. */
  1801. function identity(input) {
  1802. return input;
  1803. }
  1804. /**
  1805. * Fill in an array with a string.
  1806. * @param {String} str the string to use.
  1807. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  1808. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  1809. */
  1810. function stringToArrayLike(str, array) {
  1811. for (var i = 0; i < str.length; ++i) {
  1812. array[i] = str.charCodeAt(i) & 0xFF;
  1813. }
  1814. return array;
  1815. }
  1816. /**
  1817. * Transform an array-like object to a string.
  1818. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  1819. * @return {String} the result.
  1820. */
  1821. function arrayLikeToString(array) {
  1822. // Performances notes :
  1823. // --------------------
  1824. // String.fromCharCode.apply(null, array) is the fastest, see
  1825. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  1826. // but the stack is limited (and we can get huge arrays !).
  1827. //
  1828. // result += String.fromCharCode(array[i]); generate too many strings !
  1829. //
  1830. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  1831. var chunk = 65536;
  1832. var result = [],
  1833. len = array.length,
  1834. type = exports.getTypeOf(array),
  1835. k = 0,
  1836. canUseApply = true;
  1837. try {
  1838. switch(type) {
  1839. case "uint8array":
  1840. String.fromCharCode.apply(null, new Uint8Array(0));
  1841. break;
  1842. case "nodebuffer":
  1843. String.fromCharCode.apply(null, nodeBuffer(0));
  1844. break;
  1845. }
  1846. } catch(e) {
  1847. canUseApply = false;
  1848. }
  1849. // no apply : slow and painful algorithm
  1850. // default browser on android 4.*
  1851. if (!canUseApply) {
  1852. var resultStr = "";
  1853. for(var i = 0; i < array.length;i++) {
  1854. resultStr += String.fromCharCode(array[i]);
  1855. }
  1856. return resultStr;
  1857. }
  1858. while (k < len && chunk > 1) {
  1859. try {
  1860. if (type === "array" || type === "nodebuffer") {
  1861. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  1862. }
  1863. else {
  1864. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  1865. }
  1866. k += chunk;
  1867. }
  1868. catch (e) {
  1869. chunk = Math.floor(chunk / 2);
  1870. }
  1871. }
  1872. return result.join("");
  1873. }
  1874. exports.applyFromCharCode = arrayLikeToString;
  1875. /**
  1876. * Copy the data from an array-like to an other array-like.
  1877. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  1878. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  1879. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  1880. */
  1881. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  1882. for (var i = 0; i < arrayFrom.length; i++) {
  1883. arrayTo[i] = arrayFrom[i];
  1884. }
  1885. return arrayTo;
  1886. }
  1887. // a matrix containing functions to transform everything into everything.
  1888. var transform = {};
  1889. // string to ?
  1890. transform["string"] = {
  1891. "string": identity,
  1892. "array": function(input) {
  1893. return stringToArrayLike(input, new Array(input.length));
  1894. },
  1895. "arraybuffer": function(input) {
  1896. return transform["string"]["uint8array"](input).buffer;
  1897. },
  1898. "uint8array": function(input) {
  1899. return stringToArrayLike(input, new Uint8Array(input.length));
  1900. },
  1901. "nodebuffer": function(input) {
  1902. return stringToArrayLike(input, nodeBuffer(input.length));
  1903. }
  1904. };
  1905. // array to ?
  1906. transform["array"] = {
  1907. "string": arrayLikeToString,
  1908. "array": identity,
  1909. "arraybuffer": function(input) {
  1910. return (new Uint8Array(input)).buffer;
  1911. },
  1912. "uint8array": function(input) {
  1913. return new Uint8Array(input);
  1914. },
  1915. "nodebuffer": function(input) {
  1916. return nodeBuffer(input);
  1917. }
  1918. };
  1919. // arraybuffer to ?
  1920. transform["arraybuffer"] = {
  1921. "string": function(input) {
  1922. return arrayLikeToString(new Uint8Array(input));
  1923. },
  1924. "array": function(input) {
  1925. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  1926. },
  1927. "arraybuffer": identity,
  1928. "uint8array": function(input) {
  1929. return new Uint8Array(input);
  1930. },
  1931. "nodebuffer": function(input) {
  1932. return nodeBuffer(new Uint8Array(input));
  1933. }
  1934. };
  1935. // uint8array to ?
  1936. transform["uint8array"] = {
  1937. "string": arrayLikeToString,
  1938. "array": function(input) {
  1939. return arrayLikeToArrayLike(input, new Array(input.length));
  1940. },
  1941. "arraybuffer": function(input) {
  1942. return input.buffer;
  1943. },
  1944. "uint8array": identity,
  1945. "nodebuffer": function(input) {
  1946. return nodeBuffer(input);
  1947. }
  1948. };
  1949. // nodebuffer to ?
  1950. transform["nodebuffer"] = {
  1951. "string": arrayLikeToString,
  1952. "array": function(input) {
  1953. return arrayLikeToArrayLike(input, new Array(input.length));
  1954. },
  1955. "arraybuffer": function(input) {
  1956. return transform["nodebuffer"]["uint8array"](input).buffer;
  1957. },
  1958. "uint8array": function(input) {
  1959. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  1960. },
  1961. "nodebuffer": identity
  1962. };
  1963. /**
  1964. * Transform an input into any type.
  1965. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  1966. * If no output type is specified, the unmodified input will be returned.
  1967. * @param {String} outputType the output type.
  1968. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  1969. * @throws {Error} an Error if the browser doesn't support the requested output type.
  1970. */
  1971. exports.transformTo = function(outputType, input) {
  1972. if (!input) {
  1973. // undefined, null, etc
  1974. // an empty string won't harm.
  1975. input = "";
  1976. }
  1977. if (!outputType) {
  1978. return input;
  1979. }
  1980. exports.checkSupport(outputType);
  1981. var inputType = exports.getTypeOf(input);
  1982. var result = transform[inputType][outputType](input);
  1983. return result;
  1984. };
  1985. /**
  1986. * Return the type of the input.
  1987. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  1988. * @param {Object} input the input to identify.
  1989. * @return {String} the (lowercase) type of the input.
  1990. */
  1991. exports.getTypeOf = function(input) {
  1992. if (typeof input === "string") {
  1993. return "string";
  1994. }
  1995. if (Object.prototype.toString.call(input) === "[object Array]") {
  1996. return "array";
  1997. }
  1998. if (support.nodebuffer && nodeBuffer.test(input)) {
  1999. return "nodebuffer";
  2000. }
  2001. if (support.uint8array && input instanceof Uint8Array) {
  2002. return "uint8array";
  2003. }
  2004. if (support.arraybuffer && input instanceof ArrayBuffer) {
  2005. return "arraybuffer";
  2006. }
  2007. };
  2008. /**
  2009. * Throw an exception if the type is not supported.
  2010. * @param {String} type the type to check.
  2011. * @throws {Error} an Error if the browser doesn't support the requested type.
  2012. */
  2013. exports.checkSupport = function(type) {
  2014. var supported = support[type.toLowerCase()];
  2015. if (!supported) {
  2016. throw new Error(type + " is not supported by this browser");
  2017. }
  2018. };
  2019. exports.MAX_VALUE_16BITS = 65535;
  2020. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  2021. /**
  2022. * Prettify a string read as binary.
  2023. * @param {string} str the string to prettify.
  2024. * @return {string} a pretty string.
  2025. */
  2026. exports.pretty = function(str) {
  2027. var res = '',
  2028. code, i;
  2029. for (i = 0; i < (str || "").length; i++) {
  2030. code = str.charCodeAt(i);
  2031. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  2032. }
  2033. return res;
  2034. };
  2035. /**
  2036. * Find a compression registered in JSZip.
  2037. * @param {string} compressionMethod the method magic to find.
  2038. * @return {Object|null} the JSZip compression object, null if none found.
  2039. */
  2040. exports.findCompression = function(compressionMethod) {
  2041. for (var method in compressions) {
  2042. if (!compressions.hasOwnProperty(method)) {
  2043. continue;
  2044. }
  2045. if (compressions[method].magic === compressionMethod) {
  2046. return compressions[method];
  2047. }
  2048. }
  2049. return null;
  2050. };
  2051. /**
  2052. * Cross-window, cross-Node-context regular expression detection
  2053. * @param {Object} object Anything
  2054. * @return {Boolean} true if the object is a regular expression,
  2055. * false otherwise
  2056. */
  2057. exports.isRegExp = function (object) {
  2058. return Object.prototype.toString.call(object) === "[object RegExp]";
  2059. };
  2060. },{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(_dereq_,module,exports){
  2061. 'use strict';
  2062. var StringReader = _dereq_('./stringReader');
  2063. var NodeBufferReader = _dereq_('./nodeBufferReader');
  2064. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  2065. var utils = _dereq_('./utils');
  2066. var sig = _dereq_('./signature');
  2067. var ZipEntry = _dereq_('./zipEntry');
  2068. var support = _dereq_('./support');
  2069. var jszipProto = _dereq_('./object');
  2070. // class ZipEntries {{{
  2071. /**
  2072. * All the entries in the zip file.
  2073. * @constructor
  2074. * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
  2075. * @param {Object} loadOptions Options for loading the stream.
  2076. */
  2077. function ZipEntries(data, loadOptions) {
  2078. this.files = [];
  2079. this.loadOptions = loadOptions;
  2080. if (data) {
  2081. this.load(data);
  2082. }
  2083. }
  2084. ZipEntries.prototype = {
  2085. /**
  2086. * Check that the reader is on the speficied signature.
  2087. * @param {string} expectedSignature the expected signature.
  2088. * @throws {Error} if it is an other signature.
  2089. */
  2090. checkSignature: function(expectedSignature) {
  2091. var signature = this.reader.readString(4);
  2092. if (signature !== expectedSignature) {
  2093. throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  2094. }
  2095. },
  2096. /**
  2097. * Read the end of the central directory.
  2098. */
  2099. readBlockEndOfCentral: function() {
  2100. this.diskNumber = this.reader.readInt(2);
  2101. this.diskWithCentralDirStart = this.reader.readInt(2);
  2102. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  2103. this.centralDirRecords = this.reader.readInt(2);
  2104. this.centralDirSize = this.reader.readInt(4);
  2105. this.centralDirOffset = this.reader.readInt(4);
  2106. this.zipCommentLength = this.reader.readInt(2);
  2107. // warning : the encoding depends of the system locale
  2108. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  2109. // On a windows machine, this field is encoded with the localized windows code page.
  2110. this.zipComment = this.reader.readString(this.zipCommentLength);
  2111. // To get consistent behavior with the generation part, we will assume that
  2112. // this is utf8 encoded.
  2113. this.zipComment = jszipProto.utf8decode(this.zipComment);
  2114. },
  2115. /**
  2116. * Read the end of the Zip 64 central directory.
  2117. * Not merged with the method readEndOfCentral :
  2118. * The end of central can coexist with its Zip64 brother,
  2119. * I don't want to read the wrong number of bytes !
  2120. */
  2121. readBlockZip64EndOfCentral: function() {
  2122. this.zip64EndOfCentralSize = this.reader.readInt(8);
  2123. this.versionMadeBy = this.reader.readString(2);
  2124. this.versionNeeded = this.reader.readInt(2);
  2125. this.diskNumber = this.reader.readInt(4);
  2126. this.diskWithCentralDirStart = this.reader.readInt(4);
  2127. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  2128. this.centralDirRecords = this.reader.readInt(8);
  2129. this.centralDirSize = this.reader.readInt(8);
  2130. this.centralDirOffset = this.reader.readInt(8);
  2131. this.zip64ExtensibleData = {};
  2132. var extraDataSize = this.zip64EndOfCentralSize - 44,
  2133. index = 0,
  2134. extraFieldId,
  2135. extraFieldLength,
  2136. extraFieldValue;
  2137. while (index < extraDataSize) {
  2138. extraFieldId = this.reader.readInt(2);
  2139. extraFieldLength = this.reader.readInt(4);
  2140. extraFieldValue = this.reader.readString(extraFieldLength);
  2141. this.zip64ExtensibleData[extraFieldId] = {
  2142. id: extraFieldId,
  2143. length: extraFieldLength,
  2144. value: extraFieldValue
  2145. };
  2146. }
  2147. },
  2148. /**
  2149. * Read the end of the Zip 64 central directory locator.
  2150. */
  2151. readBlockZip64EndOfCentralLocator: function() {
  2152. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  2153. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  2154. this.disksCount = this.reader.readInt(4);
  2155. if (this.disksCount > 1) {
  2156. throw new Error("Multi-volumes zip are not supported");
  2157. }
  2158. },
  2159. /**
  2160. * Read the local files, based on the offset read in the central part.
  2161. */
  2162. readLocalFiles: function() {
  2163. var i, file;
  2164. for (i = 0; i < this.files.length; i++) {
  2165. file = this.files[i];
  2166. this.reader.setIndex(file.localHeaderOffset);
  2167. this.checkSignature(sig.LOCAL_FILE_HEADER);
  2168. file.readLocalPart(this.reader);
  2169. file.handleUTF8();
  2170. }
  2171. },
  2172. /**
  2173. * Read the central directory.
  2174. */
  2175. readCentralDir: function() {
  2176. var file;
  2177. this.reader.setIndex(this.centralDirOffset);
  2178. while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
  2179. file = new ZipEntry({
  2180. zip64: this.zip64
  2181. }, this.loadOptions);
  2182. file.readCentralPart(this.reader);
  2183. this.files.push(file);
  2184. }
  2185. },
  2186. /**
  2187. * Read the end of central directory.
  2188. */
  2189. readEndOfCentral: function() {
  2190. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  2191. if (offset === -1) {
  2192. throw new Error("Corrupted zip : can't find end of central directory");
  2193. }
  2194. this.reader.setIndex(offset);
  2195. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  2196. this.readBlockEndOfCentral();
  2197. /* extract from the zip spec :
  2198. 4) If one of the fields in the end of central directory
  2199. record is too small to hold required data, the field
  2200. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  2201. ZIP64 format record should be created.
  2202. 5) The end of central directory record and the
  2203. Zip64 end of central directory locator record must
  2204. reside on the same disk when splitting or spanning
  2205. an archive.
  2206. */
  2207. if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {
  2208. this.zip64 = true;
  2209. /*
  2210. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  2211. the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
  2212. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  2213. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  2214. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  2215. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  2216. */
  2217. // should look for a zip64 EOCD locator
  2218. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  2219. if (offset === -1) {
  2220. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
  2221. }
  2222. this.reader.setIndex(offset);
  2223. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  2224. this.readBlockZip64EndOfCentralLocator();
  2225. // now the zip64 EOCD record
  2226. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  2227. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  2228. this.readBlockZip64EndOfCentral();
  2229. }
  2230. },
  2231. prepareReader: function(data) {
  2232. var type = utils.getTypeOf(data);
  2233. if (type === "string" && !support.uint8array) {
  2234. this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
  2235. }
  2236. else if (type === "nodebuffer") {
  2237. this.reader = new NodeBufferReader(data);
  2238. }
  2239. else {
  2240. this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
  2241. }
  2242. },
  2243. /**
  2244. * Read a zip file and create ZipEntries.
  2245. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  2246. */
  2247. load: function(data) {
  2248. this.prepareReader(data);
  2249. this.readEndOfCentral();
  2250. this.readCentralDir();
  2251. this.readLocalFiles();
  2252. }
  2253. };
  2254. // }}} end of ZipEntries
  2255. module.exports = ZipEntries;
  2256. },{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(_dereq_,module,exports){
  2257. 'use strict';
  2258. var StringReader = _dereq_('./stringReader');
  2259. var utils = _dereq_('./utils');
  2260. var CompressedObject = _dereq_('./compressedObject');
  2261. var jszipProto = _dereq_('./object');
  2262. // class ZipEntry {{{
  2263. /**
  2264. * An entry in the zip file.
  2265. * @constructor
  2266. * @param {Object} options Options of the current file.
  2267. * @param {Object} loadOptions Options for loading the stream.
  2268. */
  2269. function ZipEntry(options, loadOptions) {
  2270. this.options = options;
  2271. this.loadOptions = loadOptions;
  2272. }
  2273. ZipEntry.prototype = {
  2274. /**
  2275. * say if the file is encrypted.
  2276. * @return {boolean} true if the file is encrypted, false otherwise.
  2277. */
  2278. isEncrypted: function() {
  2279. // bit 1 is set
  2280. return (this.bitFlag & 0x0001) === 0x0001;
  2281. },
  2282. /**
  2283. * say if the file has utf-8 filename/comment.
  2284. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  2285. */
  2286. useUTF8: function() {
  2287. // bit 11 is set
  2288. return (this.bitFlag & 0x0800) === 0x0800;
  2289. },
  2290. /**
  2291. * Prepare the function used to generate the compressed content from this ZipFile.
  2292. * @param {DataReader} reader the reader to use.
  2293. * @param {number} from the offset from where we should read the data.
  2294. * @param {number} length the length of the data to read.
  2295. * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
  2296. */
  2297. prepareCompressedContent: function(reader, from, length) {
  2298. return function() {
  2299. var previousIndex = reader.index;
  2300. reader.setIndex(from);
  2301. var compressedFileData = reader.readData(length);
  2302. reader.setIndex(previousIndex);
  2303. return compressedFileData;
  2304. };
  2305. },
  2306. /**
  2307. * Prepare the function used to generate the uncompressed content from this ZipFile.
  2308. * @param {DataReader} reader the reader to use.
  2309. * @param {number} from the offset from where we should read the data.
  2310. * @param {number} length the length of the data to read.
  2311. * @param {JSZip.compression} compression the compression used on this file.
  2312. * @param {number} uncompressedSize the uncompressed size to expect.
  2313. * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
  2314. */
  2315. prepareContent: function(reader, from, length, compression, uncompressedSize) {
  2316. return function() {
  2317. var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
  2318. var uncompressedFileData = compression.uncompress(compressedFileData);
  2319. if (uncompressedFileData.length !== uncompressedSize) {
  2320. throw new Error("Bug : uncompressed data size mismatch");
  2321. }
  2322. return uncompressedFileData;
  2323. };
  2324. },
  2325. /**
  2326. * Read the local part of a zip file and add the info in this object.
  2327. * @param {DataReader} reader the reader to use.
  2328. */
  2329. readLocalPart: function(reader) {
  2330. var compression, localExtraFieldsLength;
  2331. // we already know everything from the central dir !
  2332. // If the central dir data are false, we are doomed.
  2333. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  2334. // The less data we get here, the more reliable this should be.
  2335. // Let's skip the whole header and dash to the data !
  2336. reader.skip(22);
  2337. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  2338. // Strangely, the filename here is OK.
  2339. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  2340. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  2341. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  2342. // the internet.
  2343. //
  2344. // I think I see the logic here : the central directory is used to display
  2345. // content and the local directory is used to extract the files. Mixing / and \
  2346. // may be used to display \ to windows users and use / when extracting the files.
  2347. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  2348. this.fileNameLength = reader.readInt(2);
  2349. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  2350. this.fileName = reader.readString(this.fileNameLength);
  2351. reader.skip(localExtraFieldsLength);
  2352. if (this.compressedSize == -1 || this.uncompressedSize == -1) {
  2353. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
  2354. }
  2355. compression = utils.findCompression(this.compressionMethod);
  2356. if (compression === null) { // no compression found
  2357. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
  2358. }
  2359. this.decompressed = new CompressedObject();
  2360. this.decompressed.compressedSize = this.compressedSize;
  2361. this.decompressed.uncompressedSize = this.uncompressedSize;
  2362. this.decompressed.crc32 = this.crc32;
  2363. this.decompressed.compressionMethod = this.compressionMethod;
  2364. this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
  2365. this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
  2366. // we need to compute the crc32...
  2367. if (this.loadOptions.checkCRC32) {
  2368. this.decompressed = utils.transformTo("string", this.decompressed.getContent());
  2369. if (jszipProto.crc32(this.decompressed) !== this.crc32) {
  2370. throw new Error("Corrupted zip : CRC32 mismatch");
  2371. }
  2372. }
  2373. },
  2374. /**
  2375. * Read the central part of a zip file and add the info in this object.
  2376. * @param {DataReader} reader the reader to use.
  2377. */
  2378. readCentralPart: function(reader) {
  2379. this.versionMadeBy = reader.readString(2);
  2380. this.versionNeeded = reader.readInt(2);
  2381. this.bitFlag = reader.readInt(2);
  2382. this.compressionMethod = reader.readString(2);
  2383. this.date = reader.readDate();
  2384. this.crc32 = reader.readInt(4);
  2385. this.compressedSize = reader.readInt(4);
  2386. this.uncompressedSize = reader.readInt(4);
  2387. this.fileNameLength = reader.readInt(2);
  2388. this.extraFieldsLength = reader.readInt(2);
  2389. this.fileCommentLength = reader.readInt(2);
  2390. this.diskNumberStart = reader.readInt(2);
  2391. this.internalFileAttributes = reader.readInt(2);
  2392. this.externalFileAttributes = reader.readInt(4);
  2393. this.localHeaderOffset = reader.readInt(4);
  2394. if (this.isEncrypted()) {
  2395. throw new Error("Encrypted zip are not supported");
  2396. }
  2397. this.fileName = reader.readString(this.fileNameLength);
  2398. this.readExtraFields(reader);
  2399. this.parseZIP64ExtraField(reader);
  2400. this.fileComment = reader.readString(this.fileCommentLength);
  2401. // warning, this is true only for zip with madeBy == DOS (plateform dependent feature)
  2402. this.dir = this.externalFileAttributes & 0x00000010 ? true : false;
  2403. },
  2404. /**
  2405. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  2406. * @param {DataReader} reader the reader to use.
  2407. */
  2408. parseZIP64ExtraField: function(reader) {
  2409. if (!this.extraFields[0x0001]) {
  2410. return;
  2411. }
  2412. // should be something, preparing the extra reader
  2413. var extraReader = new StringReader(this.extraFields[0x0001].value);
  2414. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  2415. // won't let us have more.
  2416. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  2417. this.uncompressedSize = extraReader.readInt(8);
  2418. }
  2419. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  2420. this.compressedSize = extraReader.readInt(8);
  2421. }
  2422. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  2423. this.localHeaderOffset = extraReader.readInt(8);
  2424. }
  2425. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  2426. this.diskNumberStart = extraReader.readInt(4);
  2427. }
  2428. },
  2429. /**
  2430. * Read the central part of a zip file and add the info in this object.
  2431. * @param {DataReader} reader the reader to use.
  2432. */
  2433. readExtraFields: function(reader) {
  2434. var start = reader.index,
  2435. extraFieldId,
  2436. extraFieldLength,
  2437. extraFieldValue;
  2438. this.extraFields = this.extraFields || {};
  2439. while (reader.index < start + this.extraFieldsLength) {
  2440. extraFieldId = reader.readInt(2);
  2441. extraFieldLength = reader.readInt(2);
  2442. extraFieldValue = reader.readString(extraFieldLength);
  2443. this.extraFields[extraFieldId] = {
  2444. id: extraFieldId,
  2445. length: extraFieldLength,
  2446. value: extraFieldValue
  2447. };
  2448. }
  2449. },
  2450. /**
  2451. * Apply an UTF8 transformation if needed.
  2452. */
  2453. handleUTF8: function() {
  2454. if (this.useUTF8()) {
  2455. this.fileName = jszipProto.utf8decode(this.fileName);
  2456. this.fileComment = jszipProto.utf8decode(this.fileComment);
  2457. } else {
  2458. var upath = this.findExtraFieldUnicodePath();
  2459. if (upath !== null) {
  2460. this.fileName = upath;
  2461. }
  2462. var ucomment = this.findExtraFieldUnicodeComment();
  2463. if (ucomment !== null) {
  2464. this.fileComment = ucomment;
  2465. }
  2466. }
  2467. },
  2468. /**
  2469. * Find the unicode path declared in the extra field, if any.
  2470. * @return {String} the unicode path, null otherwise.
  2471. */
  2472. findExtraFieldUnicodePath: function() {
  2473. var upathField = this.extraFields[0x7075];
  2474. if (upathField) {
  2475. var extraReader = new StringReader(upathField.value);
  2476. // wrong version
  2477. if (extraReader.readInt(1) !== 1) {
  2478. return null;
  2479. }
  2480. // the crc of the filename changed, this field is out of date.
  2481. if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
  2482. return null;
  2483. }
  2484. return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
  2485. }
  2486. return null;
  2487. },
  2488. /**
  2489. * Find the unicode comment declared in the extra field, if any.
  2490. * @return {String} the unicode comment, null otherwise.
  2491. */
  2492. findExtraFieldUnicodeComment: function() {
  2493. var ucommentField = this.extraFields[0x6375];
  2494. if (ucommentField) {
  2495. var extraReader = new StringReader(ucommentField.value);
  2496. // wrong version
  2497. if (extraReader.readInt(1) !== 1) {
  2498. return null;
  2499. }
  2500. // the crc of the comment changed, this field is out of date.
  2501. if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
  2502. return null;
  2503. }
  2504. return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
  2505. }
  2506. return null;
  2507. }
  2508. };
  2509. module.exports = ZipEntry;
  2510. },{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(_dereq_,module,exports){
  2511. // Top level file is just a mixin of submodules & constants
  2512. 'use strict';
  2513. var assign = _dereq_('./lib/utils/common').assign;
  2514. var deflate = _dereq_('./lib/deflate');
  2515. var inflate = _dereq_('./lib/inflate');
  2516. var constants = _dereq_('./lib/zlib/constants');
  2517. var pako = {};
  2518. assign(pako, deflate, inflate, constants);
  2519. module.exports = pako;
  2520. },{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(_dereq_,module,exports){
  2521. 'use strict';
  2522. var zlib_deflate = _dereq_('./zlib/deflate.js');
  2523. var utils = _dereq_('./utils/common');
  2524. var strings = _dereq_('./utils/strings');
  2525. var msg = _dereq_('./zlib/messages');
  2526. var zstream = _dereq_('./zlib/zstream');
  2527. /* Public constants ==========================================================*/
  2528. /* ===========================================================================*/
  2529. var Z_NO_FLUSH = 0;
  2530. var Z_FINISH = 4;
  2531. var Z_OK = 0;
  2532. var Z_STREAM_END = 1;
  2533. var Z_DEFAULT_COMPRESSION = -1;
  2534. var Z_DEFAULT_STRATEGY = 0;
  2535. var Z_DEFLATED = 8;
  2536. /* ===========================================================================*/
  2537. /**
  2538. * class Deflate
  2539. *
  2540. * Generic JS-style wrapper for zlib calls. If you don't need
  2541. * streaming behaviour - use more simple functions: [[deflate]],
  2542. * [[deflateRaw]] and [[gzip]].
  2543. **/
  2544. /* internal
  2545. * Deflate.chunks -> Array
  2546. *
  2547. * Chunks of output data, if [[Deflate#onData]] not overriden.
  2548. **/
  2549. /**
  2550. * Deflate.result -> Uint8Array|Array
  2551. *
  2552. * Compressed result, generated by default [[Deflate#onData]]
  2553. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  2554. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  2555. **/
  2556. /**
  2557. * Deflate.err -> Number
  2558. *
  2559. * Error code after deflate finished. 0 (Z_OK) on success.
  2560. * You will not need it in real life, because deflate errors
  2561. * are possible only on wrong options or bad `onData` / `onEnd`
  2562. * custom handlers.
  2563. **/
  2564. /**
  2565. * Deflate.msg -> String
  2566. *
  2567. * Error message, if [[Deflate.err]] != 0
  2568. **/
  2569. /**
  2570. * new Deflate(options)
  2571. * - options (Object): zlib deflate options.
  2572. *
  2573. * Creates new deflator instance with specified params. Throws exception
  2574. * on bad params. Supported options:
  2575. *
  2576. * - `level`
  2577. * - `windowBits`
  2578. * - `memLevel`
  2579. * - `strategy`
  2580. *
  2581. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  2582. * for more information on these.
  2583. *
  2584. * Additional options, for internal needs:
  2585. *
  2586. * - `chunkSize` - size of generated data chunks (16K by default)
  2587. * - `raw` (Boolean) - do raw deflate
  2588. * - `gzip` (Boolean) - create gzip wrapper
  2589. * - `to` (String) - if equal to 'string', then result will be "binary string"
  2590. * (each char code [0..255])
  2591. * - `header` (Object) - custom header for gzip
  2592. * - `text` (Boolean) - true if compressed data believed to be text
  2593. * - `time` (Number) - modification time, unix timestamp
  2594. * - `os` (Number) - operation system code
  2595. * - `extra` (Array) - array of bytes with extra data (max 65536)
  2596. * - `name` (String) - file name (binary string)
  2597. * - `comment` (String) - comment (binary string)
  2598. * - `hcrc` (Boolean) - true if header crc should be added
  2599. *
  2600. * ##### Example:
  2601. *
  2602. * ```javascript
  2603. * var pako = require('pako')
  2604. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  2605. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  2606. *
  2607. * var deflate = new pako.Deflate({ level: 3});
  2608. *
  2609. * deflate.push(chunk1, false);
  2610. * deflate.push(chunk2, true); // true -> last chunk
  2611. *
  2612. * if (deflate.err) { throw new Error(deflate.err); }
  2613. *
  2614. * console.log(deflate.result);
  2615. * ```
  2616. **/
  2617. var Deflate = function(options) {
  2618. this.options = utils.assign({
  2619. level: Z_DEFAULT_COMPRESSION,
  2620. method: Z_DEFLATED,
  2621. chunkSize: 16384,
  2622. windowBits: 15,
  2623. memLevel: 8,
  2624. strategy: Z_DEFAULT_STRATEGY,
  2625. to: ''
  2626. }, options || {});
  2627. var opt = this.options;
  2628. if (opt.raw && (opt.windowBits > 0)) {
  2629. opt.windowBits = -opt.windowBits;
  2630. }
  2631. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  2632. opt.windowBits += 16;
  2633. }
  2634. this.err = 0; // error code, if happens (0 = Z_OK)
  2635. this.msg = ''; // error message
  2636. this.ended = false; // used to avoid multiple onEnd() calls
  2637. this.chunks = []; // chunks of compressed data
  2638. this.strm = new zstream();
  2639. this.strm.avail_out = 0;
  2640. var status = zlib_deflate.deflateInit2(
  2641. this.strm,
  2642. opt.level,
  2643. opt.method,
  2644. opt.windowBits,
  2645. opt.memLevel,
  2646. opt.strategy
  2647. );
  2648. if (status !== Z_OK) {
  2649. throw new Error(msg[status]);
  2650. }
  2651. if (opt.header) {
  2652. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  2653. }
  2654. };
  2655. /**
  2656. * Deflate#push(data[, mode]) -> Boolean
  2657. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  2658. * utf8 byte sequence.
  2659. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  2660. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  2661. *
  2662. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  2663. * new compressed chunks. Returns `true` on success. The last data block must have
  2664. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  2665. * [[Deflate#onEnd]].
  2666. *
  2667. * On fail call [[Deflate#onEnd]] with error code and return false.
  2668. *
  2669. * We strongly recommend to use `Uint8Array` on input for best speed (output
  2670. * array format is detected automatically). Also, don't skip last param and always
  2671. * use the same type in your code (boolean or number). That will improve JS speed.
  2672. *
  2673. * For regular `Array`-s make sure all elements are [0..255].
  2674. *
  2675. * ##### Example
  2676. *
  2677. * ```javascript
  2678. * push(chunk, false); // push one of data chunks
  2679. * ...
  2680. * push(chunk, true); // push last chunk
  2681. * ```
  2682. **/
  2683. Deflate.prototype.push = function(data, mode) {
  2684. var strm = this.strm;
  2685. var chunkSize = this.options.chunkSize;
  2686. var status, _mode;
  2687. if (this.ended) { return false; }
  2688. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  2689. // Convert data if needed
  2690. if (typeof data === 'string') {
  2691. // If we need to compress text, change encoding to utf8.
  2692. strm.input = strings.string2buf(data);
  2693. } else {
  2694. strm.input = data;
  2695. }
  2696. strm.next_in = 0;
  2697. strm.avail_in = strm.input.length;
  2698. do {
  2699. if (strm.avail_out === 0) {
  2700. strm.output = new utils.Buf8(chunkSize);
  2701. strm.next_out = 0;
  2702. strm.avail_out = chunkSize;
  2703. }
  2704. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  2705. if (status !== Z_STREAM_END && status !== Z_OK) {
  2706. this.onEnd(status);
  2707. this.ended = true;
  2708. return false;
  2709. }
  2710. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  2711. if (this.options.to === 'string') {
  2712. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  2713. } else {
  2714. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  2715. }
  2716. }
  2717. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  2718. // Finalize on the last chunk.
  2719. if (_mode === Z_FINISH) {
  2720. status = zlib_deflate.deflateEnd(this.strm);
  2721. this.onEnd(status);
  2722. this.ended = true;
  2723. return status === Z_OK;
  2724. }
  2725. return true;
  2726. };
  2727. /**
  2728. * Deflate#onData(chunk) -> Void
  2729. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  2730. * on js engine support. When string output requested, each chunk
  2731. * will be string.
  2732. *
  2733. * By default, stores data blocks in `chunks[]` property and glue
  2734. * those in `onEnd`. Override this handler, if you need another behaviour.
  2735. **/
  2736. Deflate.prototype.onData = function(chunk) {
  2737. this.chunks.push(chunk);
  2738. };
  2739. /**
  2740. * Deflate#onEnd(status) -> Void
  2741. * - status (Number): deflate status. 0 (Z_OK) on success,
  2742. * other if not.
  2743. *
  2744. * Called once after you tell deflate that input stream complete
  2745. * or error happenned. By default - join collected chunks,
  2746. * free memory and fill `results` / `err` properties.
  2747. **/
  2748. Deflate.prototype.onEnd = function(status) {
  2749. // On success - join
  2750. if (status === Z_OK) {
  2751. if (this.options.to === 'string') {
  2752. this.result = this.chunks.join('');
  2753. } else {
  2754. this.result = utils.flattenChunks(this.chunks);
  2755. }
  2756. }
  2757. this.chunks = [];
  2758. this.err = status;
  2759. this.msg = this.strm.msg;
  2760. };
  2761. /**
  2762. * deflate(data[, options]) -> Uint8Array|Array|String
  2763. * - data (Uint8Array|Array|String): input data to compress.
  2764. * - options (Object): zlib deflate options.
  2765. *
  2766. * Compress `data` with deflate alrorythm and `options`.
  2767. *
  2768. * Supported options are:
  2769. *
  2770. * - level
  2771. * - windowBits
  2772. * - memLevel
  2773. * - strategy
  2774. *
  2775. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  2776. * for more information on these.
  2777. *
  2778. * Sugar (options):
  2779. *
  2780. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  2781. * negative windowBits implicitly.
  2782. * - `to` (String) - if equal to 'string', then result will be "binary string"
  2783. * (each char code [0..255])
  2784. *
  2785. * ##### Example:
  2786. *
  2787. * ```javascript
  2788. * var pako = require('pako')
  2789. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  2790. *
  2791. * console.log(pako.deflate(data));
  2792. * ```
  2793. **/
  2794. function deflate(input, options) {
  2795. var deflator = new Deflate(options);
  2796. deflator.push(input, true);
  2797. // That will never happens, if you don't cheat with options :)
  2798. if (deflator.err) { throw deflator.msg; }
  2799. return deflator.result;
  2800. }
  2801. /**
  2802. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  2803. * - data (Uint8Array|Array|String): input data to compress.
  2804. * - options (Object): zlib deflate options.
  2805. *
  2806. * The same as [[deflate]], but creates raw data, without wrapper
  2807. * (header and adler32 crc).
  2808. **/
  2809. function deflateRaw(input, options) {
  2810. options = options || {};
  2811. options.raw = true;
  2812. return deflate(input, options);
  2813. }
  2814. /**
  2815. * gzip(data[, options]) -> Uint8Array|Array|String
  2816. * - data (Uint8Array|Array|String): input data to compress.
  2817. * - options (Object): zlib deflate options.
  2818. *
  2819. * The same as [[deflate]], but create gzip wrapper instead of
  2820. * deflate one.
  2821. **/
  2822. function gzip(input, options) {
  2823. options = options || {};
  2824. options.gzip = true;
  2825. return deflate(input, options);
  2826. }
  2827. exports.Deflate = Deflate;
  2828. exports.deflate = deflate;
  2829. exports.deflateRaw = deflateRaw;
  2830. exports.gzip = gzip;
  2831. },{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(_dereq_,module,exports){
  2832. 'use strict';
  2833. var zlib_inflate = _dereq_('./zlib/inflate.js');
  2834. var utils = _dereq_('./utils/common');
  2835. var strings = _dereq_('./utils/strings');
  2836. var c = _dereq_('./zlib/constants');
  2837. var msg = _dereq_('./zlib/messages');
  2838. var zstream = _dereq_('./zlib/zstream');
  2839. var gzheader = _dereq_('./zlib/gzheader');
  2840. /**
  2841. * class Inflate
  2842. *
  2843. * Generic JS-style wrapper for zlib calls. If you don't need
  2844. * streaming behaviour - use more simple functions: [[inflate]]
  2845. * and [[inflateRaw]].
  2846. **/
  2847. /* internal
  2848. * inflate.chunks -> Array
  2849. *
  2850. * Chunks of output data, if [[Inflate#onData]] not overriden.
  2851. **/
  2852. /**
  2853. * Inflate.result -> Uint8Array|Array|String
  2854. *
  2855. * Uncompressed result, generated by default [[Inflate#onData]]
  2856. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  2857. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  2858. **/
  2859. /**
  2860. * Inflate.err -> Number
  2861. *
  2862. * Error code after inflate finished. 0 (Z_OK) on success.
  2863. * Should be checked if broken data possible.
  2864. **/
  2865. /**
  2866. * Inflate.msg -> String
  2867. *
  2868. * Error message, if [[Inflate.err]] != 0
  2869. **/
  2870. /**
  2871. * new Inflate(options)
  2872. * - options (Object): zlib inflate options.
  2873. *
  2874. * Creates new inflator instance with specified params. Throws exception
  2875. * on bad params. Supported options:
  2876. *
  2877. * - `windowBits`
  2878. *
  2879. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  2880. * for more information on these.
  2881. *
  2882. * Additional options, for internal needs:
  2883. *
  2884. * - `chunkSize` - size of generated data chunks (16K by default)
  2885. * - `raw` (Boolean) - do raw inflate
  2886. * - `to` (String) - if equal to 'string', then result will be converted
  2887. * from utf8 to utf16 (javascript) string. When string output requested,
  2888. * chunk length can differ from `chunkSize`, depending on content.
  2889. *
  2890. * By default, when no options set, autodetect deflate/gzip data format via
  2891. * wrapper header.
  2892. *
  2893. * ##### Example:
  2894. *
  2895. * ```javascript
  2896. * var pako = require('pako')
  2897. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  2898. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  2899. *
  2900. * var inflate = new pako.Inflate({ level: 3});
  2901. *
  2902. * inflate.push(chunk1, false);
  2903. * inflate.push(chunk2, true); // true -> last chunk
  2904. *
  2905. * if (inflate.err) { throw new Error(inflate.err); }
  2906. *
  2907. * console.log(inflate.result);
  2908. * ```
  2909. **/
  2910. var Inflate = function(options) {
  2911. this.options = utils.assign({
  2912. chunkSize: 16384,
  2913. windowBits: 0,
  2914. to: ''
  2915. }, options || {});
  2916. var opt = this.options;
  2917. // Force window size for `raw` data, if not set directly,
  2918. // because we have no header for autodetect.
  2919. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  2920. opt.windowBits = -opt.windowBits;
  2921. if (opt.windowBits === 0) { opt.windowBits = -15; }
  2922. }
  2923. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  2924. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  2925. !(options && options.windowBits)) {
  2926. opt.windowBits += 32;
  2927. }
  2928. // Gzip header has no info about windows size, we can do autodetect only
  2929. // for deflate. So, if window size not set, force it to max when gzip possible
  2930. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  2931. // bit 3 (16) -> gzipped data
  2932. // bit 4 (32) -> autodetect gzip/deflate
  2933. if ((opt.windowBits & 15) === 0) {
  2934. opt.windowBits |= 15;
  2935. }
  2936. }
  2937. this.err = 0; // error code, if happens (0 = Z_OK)
  2938. this.msg = ''; // error message
  2939. this.ended = false; // used to avoid multiple onEnd() calls
  2940. this.chunks = []; // chunks of compressed data
  2941. this.strm = new zstream();
  2942. this.strm.avail_out = 0;
  2943. var status = zlib_inflate.inflateInit2(
  2944. this.strm,
  2945. opt.windowBits
  2946. );
  2947. if (status !== c.Z_OK) {
  2948. throw new Error(msg[status]);
  2949. }
  2950. this.header = new gzheader();
  2951. zlib_inflate.inflateGetHeader(this.strm, this.header);
  2952. };
  2953. /**
  2954. * Inflate#push(data[, mode]) -> Boolean
  2955. * - data (Uint8Array|Array|String): input data
  2956. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  2957. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  2958. *
  2959. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  2960. * new output chunks. Returns `true` on success. The last data block must have
  2961. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  2962. * [[Inflate#onEnd]].
  2963. *
  2964. * On fail call [[Inflate#onEnd]] with error code and return false.
  2965. *
  2966. * We strongly recommend to use `Uint8Array` on input for best speed (output
  2967. * format is detected automatically). Also, don't skip last param and always
  2968. * use the same type in your code (boolean or number). That will improve JS speed.
  2969. *
  2970. * For regular `Array`-s make sure all elements are [0..255].
  2971. *
  2972. * ##### Example
  2973. *
  2974. * ```javascript
  2975. * push(chunk, false); // push one of data chunks
  2976. * ...
  2977. * push(chunk, true); // push last chunk
  2978. * ```
  2979. **/
  2980. Inflate.prototype.push = function(data, mode) {
  2981. var strm = this.strm;
  2982. var chunkSize = this.options.chunkSize;
  2983. var status, _mode;
  2984. var next_out_utf8, tail, utf8str;
  2985. if (this.ended) { return false; }
  2986. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  2987. // Convert data if needed
  2988. if (typeof data === 'string') {
  2989. // Only binary strings can be decompressed on practice
  2990. strm.input = strings.binstring2buf(data);
  2991. } else {
  2992. strm.input = data;
  2993. }
  2994. strm.next_in = 0;
  2995. strm.avail_in = strm.input.length;
  2996. do {
  2997. if (strm.avail_out === 0) {
  2998. strm.output = new utils.Buf8(chunkSize);
  2999. strm.next_out = 0;
  3000. strm.avail_out = chunkSize;
  3001. }
  3002. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  3003. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  3004. this.onEnd(status);
  3005. this.ended = true;
  3006. return false;
  3007. }
  3008. if (strm.next_out) {
  3009. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  3010. if (this.options.to === 'string') {
  3011. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  3012. tail = strm.next_out - next_out_utf8;
  3013. utf8str = strings.buf2string(strm.output, next_out_utf8);
  3014. // move tail
  3015. strm.next_out = tail;
  3016. strm.avail_out = chunkSize - tail;
  3017. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  3018. this.onData(utf8str);
  3019. } else {
  3020. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  3021. }
  3022. }
  3023. }
  3024. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  3025. if (status === c.Z_STREAM_END) {
  3026. _mode = c.Z_FINISH;
  3027. }
  3028. // Finalize on the last chunk.
  3029. if (_mode === c.Z_FINISH) {
  3030. status = zlib_inflate.inflateEnd(this.strm);
  3031. this.onEnd(status);
  3032. this.ended = true;
  3033. return status === c.Z_OK;
  3034. }
  3035. return true;
  3036. };
  3037. /**
  3038. * Inflate#onData(chunk) -> Void
  3039. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  3040. * on js engine support. When string output requested, each chunk
  3041. * will be string.
  3042. *
  3043. * By default, stores data blocks in `chunks[]` property and glue
  3044. * those in `onEnd`. Override this handler, if you need another behaviour.
  3045. **/
  3046. Inflate.prototype.onData = function(chunk) {
  3047. this.chunks.push(chunk);
  3048. };
  3049. /**
  3050. * Inflate#onEnd(status) -> Void
  3051. * - status (Number): inflate status. 0 (Z_OK) on success,
  3052. * other if not.
  3053. *
  3054. * Called once after you tell inflate that input stream complete
  3055. * or error happenned. By default - join collected chunks,
  3056. * free memory and fill `results` / `err` properties.
  3057. **/
  3058. Inflate.prototype.onEnd = function(status) {
  3059. // On success - join
  3060. if (status === c.Z_OK) {
  3061. if (this.options.to === 'string') {
  3062. // Glue & convert here, until we teach pako to send
  3063. // utf8 alligned strings to onData
  3064. this.result = this.chunks.join('');
  3065. } else {
  3066. this.result = utils.flattenChunks(this.chunks);
  3067. }
  3068. }
  3069. this.chunks = [];
  3070. this.err = status;
  3071. this.msg = this.strm.msg;
  3072. };
  3073. /**
  3074. * inflate(data[, options]) -> Uint8Array|Array|String
  3075. * - data (Uint8Array|Array|String): input data to decompress.
  3076. * - options (Object): zlib inflate options.
  3077. *
  3078. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  3079. * format via wrapper header by default. That's why we don't provide
  3080. * separate `ungzip` method.
  3081. *
  3082. * Supported options are:
  3083. *
  3084. * - windowBits
  3085. *
  3086. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3087. * for more information.
  3088. *
  3089. * Sugar (options):
  3090. *
  3091. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  3092. * negative windowBits implicitly.
  3093. * - `to` (String) - if equal to 'string', then result will be converted
  3094. * from utf8 to utf16 (javascript) string. When string output requested,
  3095. * chunk length can differ from `chunkSize`, depending on content.
  3096. *
  3097. *
  3098. * ##### Example:
  3099. *
  3100. * ```javascript
  3101. * var pako = require('pako')
  3102. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  3103. * , output;
  3104. *
  3105. * try {
  3106. * output = pako.inflate(input);
  3107. * } catch (err)
  3108. * console.log(err);
  3109. * }
  3110. * ```
  3111. **/
  3112. function inflate(input, options) {
  3113. var inflator = new Inflate(options);
  3114. inflator.push(input, true);
  3115. // That will never happens, if you don't cheat with options :)
  3116. if (inflator.err) { throw inflator.msg; }
  3117. return inflator.result;
  3118. }
  3119. /**
  3120. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  3121. * - data (Uint8Array|Array|String): input data to decompress.
  3122. * - options (Object): zlib inflate options.
  3123. *
  3124. * The same as [[inflate]], but creates raw data, without wrapper
  3125. * (header and adler32 crc).
  3126. **/
  3127. function inflateRaw(input, options) {
  3128. options = options || {};
  3129. options.raw = true;
  3130. return inflate(input, options);
  3131. }
  3132. /**
  3133. * ungzip(data[, options]) -> Uint8Array|Array|String
  3134. * - data (Uint8Array|Array|String): input data to decompress.
  3135. * - options (Object): zlib inflate options.
  3136. *
  3137. * Just shortcut to [[inflate]], because it autodetects format
  3138. * by header.content. Done for convenience.
  3139. **/
  3140. exports.Inflate = Inflate;
  3141. exports.inflate = inflate;
  3142. exports.inflateRaw = inflateRaw;
  3143. exports.ungzip = inflate;
  3144. },{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(_dereq_,module,exports){
  3145. 'use strict';
  3146. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  3147. (typeof Uint16Array !== 'undefined') &&
  3148. (typeof Int32Array !== 'undefined');
  3149. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  3150. var sources = Array.prototype.slice.call(arguments, 1);
  3151. while (sources.length) {
  3152. var source = sources.shift();
  3153. if (!source) { continue; }
  3154. if (typeof(source) !== 'object') {
  3155. throw new TypeError(source + 'must be non-object');
  3156. }
  3157. for (var p in source) {
  3158. if (source.hasOwnProperty(p)) {
  3159. obj[p] = source[p];
  3160. }
  3161. }
  3162. }
  3163. return obj;
  3164. };
  3165. // reduce buffer size, avoiding mem copy
  3166. exports.shrinkBuf = function (buf, size) {
  3167. if (buf.length === size) { return buf; }
  3168. if (buf.subarray) { return buf.subarray(0, size); }
  3169. buf.length = size;
  3170. return buf;
  3171. };
  3172. var fnTyped = {
  3173. arraySet: function (dest, src, src_offs, len, dest_offs) {
  3174. if (src.subarray && dest.subarray) {
  3175. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  3176. return;
  3177. }
  3178. // Fallback to ordinary array
  3179. for(var i=0; i<len; i++) {
  3180. dest[dest_offs + i] = src[src_offs + i];
  3181. }
  3182. },
  3183. // Join array of chunks to single array.
  3184. flattenChunks: function(chunks) {
  3185. var i, l, len, pos, chunk, result;
  3186. // calculate data length
  3187. len = 0;
  3188. for (i=0, l=chunks.length; i<l; i++) {
  3189. len += chunks[i].length;
  3190. }
  3191. // join chunks
  3192. result = new Uint8Array(len);
  3193. pos = 0;
  3194. for (i=0, l=chunks.length; i<l; i++) {
  3195. chunk = chunks[i];
  3196. result.set(chunk, pos);
  3197. pos += chunk.length;
  3198. }
  3199. return result;
  3200. }
  3201. };
  3202. var fnUntyped = {
  3203. arraySet: function (dest, src, src_offs, len, dest_offs) {
  3204. for(var i=0; i<len; i++) {
  3205. dest[dest_offs + i] = src[src_offs + i];
  3206. }
  3207. },
  3208. // Join array of chunks to single array.
  3209. flattenChunks: function(chunks) {
  3210. return [].concat.apply([], chunks);
  3211. }
  3212. };
  3213. // Enable/Disable typed arrays use, for testing
  3214. //
  3215. exports.setTyped = function (on) {
  3216. if (on) {
  3217. exports.Buf8 = Uint8Array;
  3218. exports.Buf16 = Uint16Array;
  3219. exports.Buf32 = Int32Array;
  3220. exports.assign(exports, fnTyped);
  3221. } else {
  3222. exports.Buf8 = Array;
  3223. exports.Buf16 = Array;
  3224. exports.Buf32 = Array;
  3225. exports.assign(exports, fnUntyped);
  3226. }
  3227. };
  3228. exports.setTyped(TYPED_OK);
  3229. },{}],28:[function(_dereq_,module,exports){
  3230. // String encode/decode helpers
  3231. 'use strict';
  3232. var utils = _dereq_('./common');
  3233. // Quick check if we can use fast array to bin string conversion
  3234. //
  3235. // - apply(Array) can fail on Android 2.2
  3236. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  3237. //
  3238. var STR_APPLY_OK = true;
  3239. var STR_APPLY_UIA_OK = true;
  3240. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  3241. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  3242. // Table with utf8 lengths (calculated by first byte of sequence)
  3243. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  3244. // because max possible codepoint is 0x10ffff
  3245. var _utf8len = new utils.Buf8(256);
  3246. for (var i=0; i<256; i++) {
  3247. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  3248. }
  3249. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  3250. // convert string to array (typed, when possible)
  3251. exports.string2buf = function (str) {
  3252. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  3253. // count binary size
  3254. for (m_pos = 0; m_pos < str_len; m_pos++) {
  3255. c = str.charCodeAt(m_pos);
  3256. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3257. c2 = str.charCodeAt(m_pos+1);
  3258. if ((c2 & 0xfc00) === 0xdc00) {
  3259. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3260. m_pos++;
  3261. }
  3262. }
  3263. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  3264. }
  3265. // allocate buffer
  3266. buf = new utils.Buf8(buf_len);
  3267. // convert
  3268. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  3269. c = str.charCodeAt(m_pos);
  3270. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3271. c2 = str.charCodeAt(m_pos+1);
  3272. if ((c2 & 0xfc00) === 0xdc00) {
  3273. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3274. m_pos++;
  3275. }
  3276. }
  3277. if (c < 0x80) {
  3278. /* one byte */
  3279. buf[i++] = c;
  3280. } else if (c < 0x800) {
  3281. /* two bytes */
  3282. buf[i++] = 0xC0 | (c >>> 6);
  3283. buf[i++] = 0x80 | (c & 0x3f);
  3284. } else if (c < 0x10000) {
  3285. /* three bytes */
  3286. buf[i++] = 0xE0 | (c >>> 12);
  3287. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3288. buf[i++] = 0x80 | (c & 0x3f);
  3289. } else {
  3290. /* four bytes */
  3291. buf[i++] = 0xf0 | (c >>> 18);
  3292. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  3293. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3294. buf[i++] = 0x80 | (c & 0x3f);
  3295. }
  3296. }
  3297. return buf;
  3298. };
  3299. // Helper (used in 2 places)
  3300. function buf2binstring(buf, len) {
  3301. // use fallback for big arrays to avoid stack overflow
  3302. if (len < 65537) {
  3303. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  3304. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  3305. }
  3306. }
  3307. var result = '';
  3308. for(var i=0; i < len; i++) {
  3309. result += String.fromCharCode(buf[i]);
  3310. }
  3311. return result;
  3312. }
  3313. // Convert byte array to binary string
  3314. exports.buf2binstring = function(buf) {
  3315. return buf2binstring(buf, buf.length);
  3316. };
  3317. // Convert binary string (typed, when possible)
  3318. exports.binstring2buf = function(str) {
  3319. var buf = new utils.Buf8(str.length);
  3320. for(var i=0, len=buf.length; i < len; i++) {
  3321. buf[i] = str.charCodeAt(i);
  3322. }
  3323. return buf;
  3324. };
  3325. // convert array to string
  3326. exports.buf2string = function (buf, max) {
  3327. var i, out, c, c_len;
  3328. var len = max || buf.length;
  3329. // Reserve max possible length (2 words per char)
  3330. // NB: by unknown reasons, Array is significantly faster for
  3331. // String.fromCharCode.apply than Uint16Array.
  3332. var utf16buf = new Array(len*2);
  3333. for (out=0, i=0; i<len;) {
  3334. c = buf[i++];
  3335. // quick process ascii
  3336. if (c < 0x80) { utf16buf[out++] = c; continue; }
  3337. c_len = _utf8len[c];
  3338. // skip 5 & 6 byte codes
  3339. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  3340. // apply mask on first byte
  3341. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  3342. // join the rest
  3343. while (c_len > 1 && i < len) {
  3344. c = (c << 6) | (buf[i++] & 0x3f);
  3345. c_len--;
  3346. }
  3347. // terminated by end of string?
  3348. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  3349. if (c < 0x10000) {
  3350. utf16buf[out++] = c;
  3351. } else {
  3352. c -= 0x10000;
  3353. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  3354. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  3355. }
  3356. }
  3357. return buf2binstring(utf16buf, out);
  3358. };
  3359. // Calculate max possible position in utf8 buffer,
  3360. // that will not break sequence. If that's not possible
  3361. // - (very small limits) return max size as is.
  3362. //
  3363. // buf[] - utf8 bytes array
  3364. // max - length limit (mandatory);
  3365. exports.utf8border = function(buf, max) {
  3366. var pos;
  3367. max = max || buf.length;
  3368. if (max > buf.length) { max = buf.length; }
  3369. // go back from last position, until start of sequence found
  3370. pos = max-1;
  3371. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  3372. // Fuckup - very small and broken sequence,
  3373. // return max, because we should return something anyway.
  3374. if (pos < 0) { return max; }
  3375. // If we came to start of buffer - that means vuffer is too small,
  3376. // return max too.
  3377. if (pos === 0) { return max; }
  3378. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  3379. };
  3380. },{"./common":27}],29:[function(_dereq_,module,exports){
  3381. 'use strict';
  3382. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  3383. // It doesn't worth to make additional optimizationa as in original.
  3384. // Small size is preferable.
  3385. function adler32(adler, buf, len, pos) {
  3386. var s1 = (adler & 0xffff) |0
  3387. , s2 = ((adler >>> 16) & 0xffff) |0
  3388. , n = 0;
  3389. while (len !== 0) {
  3390. // Set limit ~ twice less than 5552, to keep
  3391. // s2 in 31-bits, because we force signed ints.
  3392. // in other case %= will fail.
  3393. n = len > 2000 ? 2000 : len;
  3394. len -= n;
  3395. do {
  3396. s1 = (s1 + buf[pos++]) |0;
  3397. s2 = (s2 + s1) |0;
  3398. } while (--n);
  3399. s1 %= 65521;
  3400. s2 %= 65521;
  3401. }
  3402. return (s1 | (s2 << 16)) |0;
  3403. }
  3404. module.exports = adler32;
  3405. },{}],30:[function(_dereq_,module,exports){
  3406. module.exports = {
  3407. /* Allowed flush values; see deflate() and inflate() below for details */
  3408. Z_NO_FLUSH: 0,
  3409. Z_PARTIAL_FLUSH: 1,
  3410. Z_SYNC_FLUSH: 2,
  3411. Z_FULL_FLUSH: 3,
  3412. Z_FINISH: 4,
  3413. Z_BLOCK: 5,
  3414. Z_TREES: 6,
  3415. /* Return codes for the compression/decompression functions. Negative values
  3416. * are errors, positive values are used for special but normal events.
  3417. */
  3418. Z_OK: 0,
  3419. Z_STREAM_END: 1,
  3420. Z_NEED_DICT: 2,
  3421. Z_ERRNO: -1,
  3422. Z_STREAM_ERROR: -2,
  3423. Z_DATA_ERROR: -3,
  3424. //Z_MEM_ERROR: -4,
  3425. Z_BUF_ERROR: -5,
  3426. //Z_VERSION_ERROR: -6,
  3427. /* compression levels */
  3428. Z_NO_COMPRESSION: 0,
  3429. Z_BEST_SPEED: 1,
  3430. Z_BEST_COMPRESSION: 9,
  3431. Z_DEFAULT_COMPRESSION: -1,
  3432. Z_FILTERED: 1,
  3433. Z_HUFFMAN_ONLY: 2,
  3434. Z_RLE: 3,
  3435. Z_FIXED: 4,
  3436. Z_DEFAULT_STRATEGY: 0,
  3437. /* Possible values of the data_type field (though see inflate()) */
  3438. Z_BINARY: 0,
  3439. Z_TEXT: 1,
  3440. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  3441. Z_UNKNOWN: 2,
  3442. /* The deflate compression method */
  3443. Z_DEFLATED: 8
  3444. //Z_NULL: null // Use -1 or null inline, depending on var type
  3445. };
  3446. },{}],31:[function(_dereq_,module,exports){
  3447. 'use strict';
  3448. // Note: we can't get significant speed boost here.
  3449. // So write code to minimize size - no pregenerated tables
  3450. // and array tools dependencies.
  3451. // Use ordinary array, since untyped makes no boost here
  3452. function makeTable() {
  3453. var c, table = [];
  3454. for(var n =0; n < 256; n++){
  3455. c = n;
  3456. for(var k =0; k < 8; k++){
  3457. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  3458. }
  3459. table[n] = c;
  3460. }
  3461. return table;
  3462. }
  3463. // Create table on load. Just 255 signed longs. Not a problem.
  3464. var crcTable = makeTable();
  3465. function crc32(crc, buf, len, pos) {
  3466. var t = crcTable
  3467. , end = pos + len;
  3468. crc = crc ^ (-1);
  3469. for (var i = pos; i < end; i++ ) {
  3470. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  3471. }
  3472. return (crc ^ (-1)); // >>> 0;
  3473. }
  3474. module.exports = crc32;
  3475. },{}],32:[function(_dereq_,module,exports){
  3476. 'use strict';
  3477. var utils = _dereq_('../utils/common');
  3478. var trees = _dereq_('./trees');
  3479. var adler32 = _dereq_('./adler32');
  3480. var crc32 = _dereq_('./crc32');
  3481. var msg = _dereq_('./messages');
  3482. /* Public constants ==========================================================*/
  3483. /* ===========================================================================*/
  3484. /* Allowed flush values; see deflate() and inflate() below for details */
  3485. var Z_NO_FLUSH = 0;
  3486. var Z_PARTIAL_FLUSH = 1;
  3487. //var Z_SYNC_FLUSH = 2;
  3488. var Z_FULL_FLUSH = 3;
  3489. var Z_FINISH = 4;
  3490. var Z_BLOCK = 5;
  3491. //var Z_TREES = 6;
  3492. /* Return codes for the compression/decompression functions. Negative values
  3493. * are errors, positive values are used for special but normal events.
  3494. */
  3495. var Z_OK = 0;
  3496. var Z_STREAM_END = 1;
  3497. //var Z_NEED_DICT = 2;
  3498. //var Z_ERRNO = -1;
  3499. var Z_STREAM_ERROR = -2;
  3500. var Z_DATA_ERROR = -3;
  3501. //var Z_MEM_ERROR = -4;
  3502. var Z_BUF_ERROR = -5;
  3503. //var Z_VERSION_ERROR = -6;
  3504. /* compression levels */
  3505. //var Z_NO_COMPRESSION = 0;
  3506. //var Z_BEST_SPEED = 1;
  3507. //var Z_BEST_COMPRESSION = 9;
  3508. var Z_DEFAULT_COMPRESSION = -1;
  3509. var Z_FILTERED = 1;
  3510. var Z_HUFFMAN_ONLY = 2;
  3511. var Z_RLE = 3;
  3512. var Z_FIXED = 4;
  3513. var Z_DEFAULT_STRATEGY = 0;
  3514. /* Possible values of the data_type field (though see inflate()) */
  3515. //var Z_BINARY = 0;
  3516. //var Z_TEXT = 1;
  3517. //var Z_ASCII = 1; // = Z_TEXT
  3518. var Z_UNKNOWN = 2;
  3519. /* The deflate compression method */
  3520. var Z_DEFLATED = 8;
  3521. /*============================================================================*/
  3522. var MAX_MEM_LEVEL = 9;
  3523. /* Maximum value for memLevel in deflateInit2 */
  3524. var MAX_WBITS = 15;
  3525. /* 32K LZ77 window */
  3526. var DEF_MEM_LEVEL = 8;
  3527. var LENGTH_CODES = 29;
  3528. /* number of length codes, not counting the special END_BLOCK code */
  3529. var LITERALS = 256;
  3530. /* number of literal bytes 0..255 */
  3531. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  3532. /* number of Literal or Length codes, including the END_BLOCK code */
  3533. var D_CODES = 30;
  3534. /* number of distance codes */
  3535. var BL_CODES = 19;
  3536. /* number of codes used to transfer the bit lengths */
  3537. var HEAP_SIZE = 2*L_CODES + 1;
  3538. /* maximum heap size */
  3539. var MAX_BITS = 15;
  3540. /* All codes must not exceed MAX_BITS bits */
  3541. var MIN_MATCH = 3;
  3542. var MAX_MATCH = 258;
  3543. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  3544. var PRESET_DICT = 0x20;
  3545. var INIT_STATE = 42;
  3546. var EXTRA_STATE = 69;
  3547. var NAME_STATE = 73;
  3548. var COMMENT_STATE = 91;
  3549. var HCRC_STATE = 103;
  3550. var BUSY_STATE = 113;
  3551. var FINISH_STATE = 666;
  3552. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  3553. var BS_BLOCK_DONE = 2; /* block flush performed */
  3554. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  3555. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  3556. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  3557. function err(strm, errorCode) {
  3558. strm.msg = msg[errorCode];
  3559. return errorCode;
  3560. }
  3561. function rank(f) {
  3562. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  3563. }
  3564. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  3565. /* =========================================================================
  3566. * Flush as much pending output as possible. All deflate() output goes
  3567. * through this function so some applications may wish to modify it
  3568. * to avoid allocating a large strm->output buffer and copying into it.
  3569. * (See also read_buf()).
  3570. */
  3571. function flush_pending(strm) {
  3572. var s = strm.state;
  3573. //_tr_flush_bits(s);
  3574. var len = s.pending;
  3575. if (len > strm.avail_out) {
  3576. len = strm.avail_out;
  3577. }
  3578. if (len === 0) { return; }
  3579. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  3580. strm.next_out += len;
  3581. s.pending_out += len;
  3582. strm.total_out += len;
  3583. strm.avail_out -= len;
  3584. s.pending -= len;
  3585. if (s.pending === 0) {
  3586. s.pending_out = 0;
  3587. }
  3588. }
  3589. function flush_block_only (s, last) {
  3590. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  3591. s.block_start = s.strstart;
  3592. flush_pending(s.strm);
  3593. }
  3594. function put_byte(s, b) {
  3595. s.pending_buf[s.pending++] = b;
  3596. }
  3597. /* =========================================================================
  3598. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  3599. * IN assertion: the stream state is correct and there is enough room in
  3600. * pending_buf.
  3601. */
  3602. function putShortMSB(s, b) {
  3603. // put_byte(s, (Byte)(b >> 8));
  3604. // put_byte(s, (Byte)(b & 0xff));
  3605. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  3606. s.pending_buf[s.pending++] = b & 0xff;
  3607. }
  3608. /* ===========================================================================
  3609. * Read a new buffer from the current input stream, update the adler32
  3610. * and total number of bytes read. All deflate() input goes through
  3611. * this function so some applications may wish to modify it to avoid
  3612. * allocating a large strm->input buffer and copying from it.
  3613. * (See also flush_pending()).
  3614. */
  3615. function read_buf(strm, buf, start, size) {
  3616. var len = strm.avail_in;
  3617. if (len > size) { len = size; }
  3618. if (len === 0) { return 0; }
  3619. strm.avail_in -= len;
  3620. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  3621. if (strm.state.wrap === 1) {
  3622. strm.adler = adler32(strm.adler, buf, len, start);
  3623. }
  3624. else if (strm.state.wrap === 2) {
  3625. strm.adler = crc32(strm.adler, buf, len, start);
  3626. }
  3627. strm.next_in += len;
  3628. strm.total_in += len;
  3629. return len;
  3630. }
  3631. /* ===========================================================================
  3632. * Set match_start to the longest match starting at the given string and
  3633. * return its length. Matches shorter or equal to prev_length are discarded,
  3634. * in which case the result is equal to prev_length and match_start is
  3635. * garbage.
  3636. * IN assertions: cur_match is the head of the hash chain for the current
  3637. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  3638. * OUT assertion: the match length is not greater than s->lookahead.
  3639. */
  3640. function longest_match(s, cur_match) {
  3641. var chain_length = s.max_chain_length; /* max hash chain length */
  3642. var scan = s.strstart; /* current string */
  3643. var match; /* matched string */
  3644. var len; /* length of current match */
  3645. var best_len = s.prev_length; /* best match length so far */
  3646. var nice_match = s.nice_match; /* stop if match long enough */
  3647. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  3648. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  3649. var _win = s.window; // shortcut
  3650. var wmask = s.w_mask;
  3651. var prev = s.prev;
  3652. /* Stop when cur_match becomes <= limit. To simplify the code,
  3653. * we prevent matches with the string of window index 0.
  3654. */
  3655. var strend = s.strstart + MAX_MATCH;
  3656. var scan_end1 = _win[scan + best_len - 1];
  3657. var scan_end = _win[scan + best_len];
  3658. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  3659. * It is easy to get rid of this optimization if necessary.
  3660. */
  3661. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  3662. /* Do not waste too much time if we already have a good match: */
  3663. if (s.prev_length >= s.good_match) {
  3664. chain_length >>= 2;
  3665. }
  3666. /* Do not look for matches beyond the end of the input. This is necessary
  3667. * to make deflate deterministic.
  3668. */
  3669. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  3670. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  3671. do {
  3672. // Assert(cur_match < s->strstart, "no future");
  3673. match = cur_match;
  3674. /* Skip to next match if the match length cannot increase
  3675. * or if the match length is less than 2. Note that the checks below
  3676. * for insufficient lookahead only occur occasionally for performance
  3677. * reasons. Therefore uninitialized memory will be accessed, and
  3678. * conditional jumps will be made that depend on those values.
  3679. * However the length of the match is limited to the lookahead, so
  3680. * the output of deflate is not affected by the uninitialized values.
  3681. */
  3682. if (_win[match + best_len] !== scan_end ||
  3683. _win[match + best_len - 1] !== scan_end1 ||
  3684. _win[match] !== _win[scan] ||
  3685. _win[++match] !== _win[scan + 1]) {
  3686. continue;
  3687. }
  3688. /* The check at best_len-1 can be removed because it will be made
  3689. * again later. (This heuristic is not always a win.)
  3690. * It is not necessary to compare scan[2] and match[2] since they
  3691. * are always equal when the other bytes match, given that
  3692. * the hash keys are equal and that HASH_BITS >= 8.
  3693. */
  3694. scan += 2;
  3695. match++;
  3696. // Assert(*scan == *match, "match[2]?");
  3697. /* We check for insufficient lookahead only every 8th comparison;
  3698. * the 256th check will be made at strstart+258.
  3699. */
  3700. do {
  3701. /*jshint noempty:false*/
  3702. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3703. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3704. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3705. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3706. scan < strend);
  3707. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  3708. len = MAX_MATCH - (strend - scan);
  3709. scan = strend - MAX_MATCH;
  3710. if (len > best_len) {
  3711. s.match_start = cur_match;
  3712. best_len = len;
  3713. if (len >= nice_match) {
  3714. break;
  3715. }
  3716. scan_end1 = _win[scan + best_len - 1];
  3717. scan_end = _win[scan + best_len];
  3718. }
  3719. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  3720. if (best_len <= s.lookahead) {
  3721. return best_len;
  3722. }
  3723. return s.lookahead;
  3724. }
  3725. /* ===========================================================================
  3726. * Fill the window when the lookahead becomes insufficient.
  3727. * Updates strstart and lookahead.
  3728. *
  3729. * IN assertion: lookahead < MIN_LOOKAHEAD
  3730. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  3731. * At least one byte has been read, or avail_in == 0; reads are
  3732. * performed for at least two bytes (required for the zip translate_eol
  3733. * option -- not supported here).
  3734. */
  3735. function fill_window(s) {
  3736. var _w_size = s.w_size;
  3737. var p, n, m, more, str;
  3738. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  3739. do {
  3740. more = s.window_size - s.lookahead - s.strstart;
  3741. // JS ints have 32 bit, block below not needed
  3742. /* Deal with !@#$% 64K limit: */
  3743. //if (sizeof(int) <= 2) {
  3744. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  3745. // more = wsize;
  3746. //
  3747. // } else if (more == (unsigned)(-1)) {
  3748. // /* Very unlikely, but possible on 16 bit machine if
  3749. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  3750. // */
  3751. // more--;
  3752. // }
  3753. //}
  3754. /* If the window is almost full and there is insufficient lookahead,
  3755. * move the upper half to the lower one to make room in the upper half.
  3756. */
  3757. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  3758. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  3759. s.match_start -= _w_size;
  3760. s.strstart -= _w_size;
  3761. /* we now have strstart >= MAX_DIST */
  3762. s.block_start -= _w_size;
  3763. /* Slide the hash table (could be avoided with 32 bit values
  3764. at the expense of memory usage). We slide even when level == 0
  3765. to keep the hash table consistent if we switch back to level > 0
  3766. later. (Using level 0 permanently is not an optimal usage of
  3767. zlib, so we don't care about this pathological case.)
  3768. */
  3769. n = s.hash_size;
  3770. p = n;
  3771. do {
  3772. m = s.head[--p];
  3773. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  3774. } while (--n);
  3775. n = _w_size;
  3776. p = n;
  3777. do {
  3778. m = s.prev[--p];
  3779. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  3780. /* If n is not on any hash chain, prev[n] is garbage but
  3781. * its value will never be used.
  3782. */
  3783. } while (--n);
  3784. more += _w_size;
  3785. }
  3786. if (s.strm.avail_in === 0) {
  3787. break;
  3788. }
  3789. /* If there was no sliding:
  3790. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  3791. * more == window_size - lookahead - strstart
  3792. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  3793. * => more >= window_size - 2*WSIZE + 2
  3794. * In the BIG_MEM or MMAP case (not yet supported),
  3795. * window_size == input_size + MIN_LOOKAHEAD &&
  3796. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  3797. * Otherwise, window_size == 2*WSIZE so more >= 2.
  3798. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  3799. */
  3800. //Assert(more >= 2, "more < 2");
  3801. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  3802. s.lookahead += n;
  3803. /* Initialize the hash value now that we have some input: */
  3804. if (s.lookahead + s.insert >= MIN_MATCH) {
  3805. str = s.strstart - s.insert;
  3806. s.ins_h = s.window[str];
  3807. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  3808. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  3809. //#if MIN_MATCH != 3
  3810. // Call update_hash() MIN_MATCH-3 more times
  3811. //#endif
  3812. while (s.insert) {
  3813. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  3814. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  3815. s.prev[str & s.w_mask] = s.head[s.ins_h];
  3816. s.head[s.ins_h] = str;
  3817. str++;
  3818. s.insert--;
  3819. if (s.lookahead + s.insert < MIN_MATCH) {
  3820. break;
  3821. }
  3822. }
  3823. }
  3824. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  3825. * but this is not important since only literal bytes will be emitted.
  3826. */
  3827. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  3828. /* If the WIN_INIT bytes after the end of the current data have never been
  3829. * written, then zero those bytes in order to avoid memory check reports of
  3830. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  3831. * the longest match routines. Update the high water mark for the next
  3832. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  3833. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  3834. */
  3835. // if (s.high_water < s.window_size) {
  3836. // var curr = s.strstart + s.lookahead;
  3837. // var init = 0;
  3838. //
  3839. // if (s.high_water < curr) {
  3840. // /* Previous high water mark below current data -- zero WIN_INIT
  3841. // * bytes or up to end of window, whichever is less.
  3842. // */
  3843. // init = s.window_size - curr;
  3844. // if (init > WIN_INIT)
  3845. // init = WIN_INIT;
  3846. // zmemzero(s->window + curr, (unsigned)init);
  3847. // s->high_water = curr + init;
  3848. // }
  3849. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  3850. // /* High water mark at or above current data, but below current data
  3851. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  3852. // * to end of window, whichever is less.
  3853. // */
  3854. // init = (ulg)curr + WIN_INIT - s->high_water;
  3855. // if (init > s->window_size - s->high_water)
  3856. // init = s->window_size - s->high_water;
  3857. // zmemzero(s->window + s->high_water, (unsigned)init);
  3858. // s->high_water += init;
  3859. // }
  3860. // }
  3861. //
  3862. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  3863. // "not enough room for search");
  3864. }
  3865. /* ===========================================================================
  3866. * Copy without compression as much as possible from the input stream, return
  3867. * the current block state.
  3868. * This function does not insert new strings in the dictionary since
  3869. * uncompressible data is probably not useful. This function is used
  3870. * only for the level=0 compression option.
  3871. * NOTE: this function should be optimized to avoid extra copying from
  3872. * window to pending_buf.
  3873. */
  3874. function deflate_stored(s, flush) {
  3875. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  3876. * to pending_buf_size, and each stored block has a 5 byte header:
  3877. */
  3878. var max_block_size = 0xffff;
  3879. if (max_block_size > s.pending_buf_size - 5) {
  3880. max_block_size = s.pending_buf_size - 5;
  3881. }
  3882. /* Copy as much as possible from input to output: */
  3883. for (;;) {
  3884. /* Fill the window as much as possible: */
  3885. if (s.lookahead <= 1) {
  3886. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  3887. // s->block_start >= (long)s->w_size, "slide too late");
  3888. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  3889. // s.block_start >= s.w_size)) {
  3890. // throw new Error("slide too late");
  3891. // }
  3892. fill_window(s);
  3893. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  3894. return BS_NEED_MORE;
  3895. }
  3896. if (s.lookahead === 0) {
  3897. break;
  3898. }
  3899. /* flush the current block */
  3900. }
  3901. //Assert(s->block_start >= 0L, "block gone");
  3902. // if (s.block_start < 0) throw new Error("block gone");
  3903. s.strstart += s.lookahead;
  3904. s.lookahead = 0;
  3905. /* Emit a stored block if pending_buf will be full: */
  3906. var max_start = s.block_start + max_block_size;
  3907. if (s.strstart === 0 || s.strstart >= max_start) {
  3908. /* strstart == 0 is possible when wraparound on 16-bit machine */
  3909. s.lookahead = s.strstart - max_start;
  3910. s.strstart = max_start;
  3911. /*** FLUSH_BLOCK(s, 0); ***/
  3912. flush_block_only(s, false);
  3913. if (s.strm.avail_out === 0) {
  3914. return BS_NEED_MORE;
  3915. }
  3916. /***/
  3917. }
  3918. /* Flush if we may have to slide, otherwise block_start may become
  3919. * negative and the data will be gone:
  3920. */
  3921. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  3922. /*** FLUSH_BLOCK(s, 0); ***/
  3923. flush_block_only(s, false);
  3924. if (s.strm.avail_out === 0) {
  3925. return BS_NEED_MORE;
  3926. }
  3927. /***/
  3928. }
  3929. }
  3930. s.insert = 0;
  3931. if (flush === Z_FINISH) {
  3932. /*** FLUSH_BLOCK(s, 1); ***/
  3933. flush_block_only(s, true);
  3934. if (s.strm.avail_out === 0) {
  3935. return BS_FINISH_STARTED;
  3936. }
  3937. /***/
  3938. return BS_FINISH_DONE;
  3939. }
  3940. if (s.strstart > s.block_start) {
  3941. /*** FLUSH_BLOCK(s, 0); ***/
  3942. flush_block_only(s, false);
  3943. if (s.strm.avail_out === 0) {
  3944. return BS_NEED_MORE;
  3945. }
  3946. /***/
  3947. }
  3948. return BS_NEED_MORE;
  3949. }
  3950. /* ===========================================================================
  3951. * Compress as much as possible from the input stream, return the current
  3952. * block state.
  3953. * This function does not perform lazy evaluation of matches and inserts
  3954. * new strings in the dictionary only for unmatched strings or for short
  3955. * matches. It is used only for the fast compression options.
  3956. */
  3957. function deflate_fast(s, flush) {
  3958. var hash_head; /* head of the hash chain */
  3959. var bflush; /* set if current block must be flushed */
  3960. for (;;) {
  3961. /* Make sure that we always have enough lookahead, except
  3962. * at the end of the input file. We need MAX_MATCH bytes
  3963. * for the next match, plus MIN_MATCH bytes to insert the
  3964. * string following the next match.
  3965. */
  3966. if (s.lookahead < MIN_LOOKAHEAD) {
  3967. fill_window(s);
  3968. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  3969. return BS_NEED_MORE;
  3970. }
  3971. if (s.lookahead === 0) {
  3972. break; /* flush the current block */
  3973. }
  3974. }
  3975. /* Insert the string window[strstart .. strstart+2] in the
  3976. * dictionary, and set hash_head to the head of the hash chain:
  3977. */
  3978. hash_head = 0/*NIL*/;
  3979. if (s.lookahead >= MIN_MATCH) {
  3980. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  3981. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  3982. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  3983. s.head[s.ins_h] = s.strstart;
  3984. /***/
  3985. }
  3986. /* Find the longest match, discarding those <= prev_length.
  3987. * At this point we have always match_length < MIN_MATCH
  3988. */
  3989. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  3990. /* To simplify the code, we prevent matches with the string
  3991. * of window index 0 (in particular we have to avoid a match
  3992. * of the string with itself at the start of the input file).
  3993. */
  3994. s.match_length = longest_match(s, hash_head);
  3995. /* longest_match() sets match_start */
  3996. }
  3997. if (s.match_length >= MIN_MATCH) {
  3998. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  3999. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  4000. s.match_length - MIN_MATCH, bflush); ***/
  4001. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  4002. s.lookahead -= s.match_length;
  4003. /* Insert new strings in the hash table only if the match length
  4004. * is not too large. This saves time but degrades compression.
  4005. */
  4006. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  4007. s.match_length--; /* string at strstart already in table */
  4008. do {
  4009. s.strstart++;
  4010. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4011. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4012. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4013. s.head[s.ins_h] = s.strstart;
  4014. /***/
  4015. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  4016. * always MIN_MATCH bytes ahead.
  4017. */
  4018. } while (--s.match_length !== 0);
  4019. s.strstart++;
  4020. } else
  4021. {
  4022. s.strstart += s.match_length;
  4023. s.match_length = 0;
  4024. s.ins_h = s.window[s.strstart];
  4025. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  4026. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  4027. //#if MIN_MATCH != 3
  4028. // Call UPDATE_HASH() MIN_MATCH-3 more times
  4029. //#endif
  4030. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  4031. * matter since it will be recomputed at next deflate call.
  4032. */
  4033. }
  4034. } else {
  4035. /* No match, output a literal byte */
  4036. //Tracevv((stderr,"%c", s.window[s.strstart]));
  4037. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4038. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4039. s.lookahead--;
  4040. s.strstart++;
  4041. }
  4042. if (bflush) {
  4043. /*** FLUSH_BLOCK(s, 0); ***/
  4044. flush_block_only(s, false);
  4045. if (s.strm.avail_out === 0) {
  4046. return BS_NEED_MORE;
  4047. }
  4048. /***/
  4049. }
  4050. }
  4051. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  4052. if (flush === Z_FINISH) {
  4053. /*** FLUSH_BLOCK(s, 1); ***/
  4054. flush_block_only(s, true);
  4055. if (s.strm.avail_out === 0) {
  4056. return BS_FINISH_STARTED;
  4057. }
  4058. /***/
  4059. return BS_FINISH_DONE;
  4060. }
  4061. if (s.last_lit) {
  4062. /*** FLUSH_BLOCK(s, 0); ***/
  4063. flush_block_only(s, false);
  4064. if (s.strm.avail_out === 0) {
  4065. return BS_NEED_MORE;
  4066. }
  4067. /***/
  4068. }
  4069. return BS_BLOCK_DONE;
  4070. }
  4071. /* ===========================================================================
  4072. * Same as above, but achieves better compression. We use a lazy
  4073. * evaluation for matches: a match is finally adopted only if there is
  4074. * no better match at the next window position.
  4075. */
  4076. function deflate_slow(s, flush) {
  4077. var hash_head; /* head of hash chain */
  4078. var bflush; /* set if current block must be flushed */
  4079. var max_insert;
  4080. /* Process the input block. */
  4081. for (;;) {
  4082. /* Make sure that we always have enough lookahead, except
  4083. * at the end of the input file. We need MAX_MATCH bytes
  4084. * for the next match, plus MIN_MATCH bytes to insert the
  4085. * string following the next match.
  4086. */
  4087. if (s.lookahead < MIN_LOOKAHEAD) {
  4088. fill_window(s);
  4089. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  4090. return BS_NEED_MORE;
  4091. }
  4092. if (s.lookahead === 0) { break; } /* flush the current block */
  4093. }
  4094. /* Insert the string window[strstart .. strstart+2] in the
  4095. * dictionary, and set hash_head to the head of the hash chain:
  4096. */
  4097. hash_head = 0/*NIL*/;
  4098. if (s.lookahead >= MIN_MATCH) {
  4099. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4100. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4101. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4102. s.head[s.ins_h] = s.strstart;
  4103. /***/
  4104. }
  4105. /* Find the longest match, discarding those <= prev_length.
  4106. */
  4107. s.prev_length = s.match_length;
  4108. s.prev_match = s.match_start;
  4109. s.match_length = MIN_MATCH-1;
  4110. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  4111. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  4112. /* To simplify the code, we prevent matches with the string
  4113. * of window index 0 (in particular we have to avoid a match
  4114. * of the string with itself at the start of the input file).
  4115. */
  4116. s.match_length = longest_match(s, hash_head);
  4117. /* longest_match() sets match_start */
  4118. if (s.match_length <= 5 &&
  4119. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  4120. /* If prev_match is also MIN_MATCH, match_start is garbage
  4121. * but we will ignore the current match anyway.
  4122. */
  4123. s.match_length = MIN_MATCH-1;
  4124. }
  4125. }
  4126. /* If there was a match at the previous step and the current
  4127. * match is not better, output the previous match:
  4128. */
  4129. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  4130. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  4131. /* Do not insert strings in hash table beyond this. */
  4132. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  4133. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  4134. s.prev_length - MIN_MATCH, bflush);***/
  4135. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  4136. /* Insert in hash table all strings up to the end of the match.
  4137. * strstart-1 and strstart are already inserted. If there is not
  4138. * enough lookahead, the last two strings are not inserted in
  4139. * the hash table.
  4140. */
  4141. s.lookahead -= s.prev_length-1;
  4142. s.prev_length -= 2;
  4143. do {
  4144. if (++s.strstart <= max_insert) {
  4145. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4146. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4147. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4148. s.head[s.ins_h] = s.strstart;
  4149. /***/
  4150. }
  4151. } while (--s.prev_length !== 0);
  4152. s.match_available = 0;
  4153. s.match_length = MIN_MATCH-1;
  4154. s.strstart++;
  4155. if (bflush) {
  4156. /*** FLUSH_BLOCK(s, 0); ***/
  4157. flush_block_only(s, false);
  4158. if (s.strm.avail_out === 0) {
  4159. return BS_NEED_MORE;
  4160. }
  4161. /***/
  4162. }
  4163. } else if (s.match_available) {
  4164. /* If there was no match at the previous position, output a
  4165. * single literal. If there was a match but the current match
  4166. * is longer, truncate the previous match to a single literal.
  4167. */
  4168. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  4169. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  4170. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  4171. if (bflush) {
  4172. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  4173. flush_block_only(s, false);
  4174. /***/
  4175. }
  4176. s.strstart++;
  4177. s.lookahead--;
  4178. if (s.strm.avail_out === 0) {
  4179. return BS_NEED_MORE;
  4180. }
  4181. } else {
  4182. /* There is no previous match to compare with, wait for
  4183. * the next step to decide.
  4184. */
  4185. s.match_available = 1;
  4186. s.strstart++;
  4187. s.lookahead--;
  4188. }
  4189. }
  4190. //Assert (flush != Z_NO_FLUSH, "no flush?");
  4191. if (s.match_available) {
  4192. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  4193. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  4194. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  4195. s.match_available = 0;
  4196. }
  4197. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  4198. if (flush === Z_FINISH) {
  4199. /*** FLUSH_BLOCK(s, 1); ***/
  4200. flush_block_only(s, true);
  4201. if (s.strm.avail_out === 0) {
  4202. return BS_FINISH_STARTED;
  4203. }
  4204. /***/
  4205. return BS_FINISH_DONE;
  4206. }
  4207. if (s.last_lit) {
  4208. /*** FLUSH_BLOCK(s, 0); ***/
  4209. flush_block_only(s, false);
  4210. if (s.strm.avail_out === 0) {
  4211. return BS_NEED_MORE;
  4212. }
  4213. /***/
  4214. }
  4215. return BS_BLOCK_DONE;
  4216. }
  4217. /* ===========================================================================
  4218. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  4219. * one. Do not maintain a hash table. (It will be regenerated if this run of
  4220. * deflate switches away from Z_RLE.)
  4221. */
  4222. function deflate_rle(s, flush) {
  4223. var bflush; /* set if current block must be flushed */
  4224. var prev; /* byte at distance one to match */
  4225. var scan, strend; /* scan goes up to strend for length of run */
  4226. var _win = s.window;
  4227. for (;;) {
  4228. /* Make sure that we always have enough lookahead, except
  4229. * at the end of the input file. We need MAX_MATCH bytes
  4230. * for the longest run, plus one for the unrolled loop.
  4231. */
  4232. if (s.lookahead <= MAX_MATCH) {
  4233. fill_window(s);
  4234. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  4235. return BS_NEED_MORE;
  4236. }
  4237. if (s.lookahead === 0) { break; } /* flush the current block */
  4238. }
  4239. /* See how many times the previous byte repeats */
  4240. s.match_length = 0;
  4241. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  4242. scan = s.strstart - 1;
  4243. prev = _win[scan];
  4244. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  4245. strend = s.strstart + MAX_MATCH;
  4246. do {
  4247. /*jshint noempty:false*/
  4248. } while (prev === _win[++scan] && prev === _win[++scan] &&
  4249. prev === _win[++scan] && prev === _win[++scan] &&
  4250. prev === _win[++scan] && prev === _win[++scan] &&
  4251. prev === _win[++scan] && prev === _win[++scan] &&
  4252. scan < strend);
  4253. s.match_length = MAX_MATCH - (strend - scan);
  4254. if (s.match_length > s.lookahead) {
  4255. s.match_length = s.lookahead;
  4256. }
  4257. }
  4258. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  4259. }
  4260. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  4261. if (s.match_length >= MIN_MATCH) {
  4262. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  4263. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  4264. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  4265. s.lookahead -= s.match_length;
  4266. s.strstart += s.match_length;
  4267. s.match_length = 0;
  4268. } else {
  4269. /* No match, output a literal byte */
  4270. //Tracevv((stderr,"%c", s->window[s->strstart]));
  4271. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4272. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4273. s.lookahead--;
  4274. s.strstart++;
  4275. }
  4276. if (bflush) {
  4277. /*** FLUSH_BLOCK(s, 0); ***/
  4278. flush_block_only(s, false);
  4279. if (s.strm.avail_out === 0) {
  4280. return BS_NEED_MORE;
  4281. }
  4282. /***/
  4283. }
  4284. }
  4285. s.insert = 0;
  4286. if (flush === Z_FINISH) {
  4287. /*** FLUSH_BLOCK(s, 1); ***/
  4288. flush_block_only(s, true);
  4289. if (s.strm.avail_out === 0) {
  4290. return BS_FINISH_STARTED;
  4291. }
  4292. /***/
  4293. return BS_FINISH_DONE;
  4294. }
  4295. if (s.last_lit) {
  4296. /*** FLUSH_BLOCK(s, 0); ***/
  4297. flush_block_only(s, false);
  4298. if (s.strm.avail_out === 0) {
  4299. return BS_NEED_MORE;
  4300. }
  4301. /***/
  4302. }
  4303. return BS_BLOCK_DONE;
  4304. }
  4305. /* ===========================================================================
  4306. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  4307. * (It will be regenerated if this run of deflate switches away from Huffman.)
  4308. */
  4309. function deflate_huff(s, flush) {
  4310. var bflush; /* set if current block must be flushed */
  4311. for (;;) {
  4312. /* Make sure that we have a literal to write. */
  4313. if (s.lookahead === 0) {
  4314. fill_window(s);
  4315. if (s.lookahead === 0) {
  4316. if (flush === Z_NO_FLUSH) {
  4317. return BS_NEED_MORE;
  4318. }
  4319. break; /* flush the current block */
  4320. }
  4321. }
  4322. /* Output a literal byte */
  4323. s.match_length = 0;
  4324. //Tracevv((stderr,"%c", s->window[s->strstart]));
  4325. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4326. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4327. s.lookahead--;
  4328. s.strstart++;
  4329. if (bflush) {
  4330. /*** FLUSH_BLOCK(s, 0); ***/
  4331. flush_block_only(s, false);
  4332. if (s.strm.avail_out === 0) {
  4333. return BS_NEED_MORE;
  4334. }
  4335. /***/
  4336. }
  4337. }
  4338. s.insert = 0;
  4339. if (flush === Z_FINISH) {
  4340. /*** FLUSH_BLOCK(s, 1); ***/
  4341. flush_block_only(s, true);
  4342. if (s.strm.avail_out === 0) {
  4343. return BS_FINISH_STARTED;
  4344. }
  4345. /***/
  4346. return BS_FINISH_DONE;
  4347. }
  4348. if (s.last_lit) {
  4349. /*** FLUSH_BLOCK(s, 0); ***/
  4350. flush_block_only(s, false);
  4351. if (s.strm.avail_out === 0) {
  4352. return BS_NEED_MORE;
  4353. }
  4354. /***/
  4355. }
  4356. return BS_BLOCK_DONE;
  4357. }
  4358. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  4359. * the desired pack level (0..9). The values given below have been tuned to
  4360. * exclude worst case performance for pathological files. Better values may be
  4361. * found for specific files.
  4362. */
  4363. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  4364. this.good_length = good_length;
  4365. this.max_lazy = max_lazy;
  4366. this.nice_length = nice_length;
  4367. this.max_chain = max_chain;
  4368. this.func = func;
  4369. };
  4370. var configuration_table;
  4371. configuration_table = [
  4372. /* good lazy nice chain */
  4373. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  4374. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  4375. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  4376. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  4377. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  4378. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  4379. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  4380. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  4381. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  4382. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  4383. ];
  4384. /* ===========================================================================
  4385. * Initialize the "longest match" routines for a new zlib stream
  4386. */
  4387. function lm_init(s) {
  4388. s.window_size = 2 * s.w_size;
  4389. /*** CLEAR_HASH(s); ***/
  4390. zero(s.head); // Fill with NIL (= 0);
  4391. /* Set the default configuration parameters:
  4392. */
  4393. s.max_lazy_match = configuration_table[s.level].max_lazy;
  4394. s.good_match = configuration_table[s.level].good_length;
  4395. s.nice_match = configuration_table[s.level].nice_length;
  4396. s.max_chain_length = configuration_table[s.level].max_chain;
  4397. s.strstart = 0;
  4398. s.block_start = 0;
  4399. s.lookahead = 0;
  4400. s.insert = 0;
  4401. s.match_length = s.prev_length = MIN_MATCH - 1;
  4402. s.match_available = 0;
  4403. s.ins_h = 0;
  4404. }
  4405. function DeflateState() {
  4406. this.strm = null; /* pointer back to this zlib stream */
  4407. this.status = 0; /* as the name implies */
  4408. this.pending_buf = null; /* output still pending */
  4409. this.pending_buf_size = 0; /* size of pending_buf */
  4410. this.pending_out = 0; /* next pending byte to output to the stream */
  4411. this.pending = 0; /* nb of bytes in the pending buffer */
  4412. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  4413. this.gzhead = null; /* gzip header information to write */
  4414. this.gzindex = 0; /* where in extra, name, or comment */
  4415. this.method = Z_DEFLATED; /* can only be DEFLATED */
  4416. this.last_flush = -1; /* value of flush param for previous deflate call */
  4417. this.w_size = 0; /* LZ77 window size (32K by default) */
  4418. this.w_bits = 0; /* log2(w_size) (8..16) */
  4419. this.w_mask = 0; /* w_size - 1 */
  4420. this.window = null;
  4421. /* Sliding window. Input bytes are read into the second half of the window,
  4422. * and move to the first half later to keep a dictionary of at least wSize
  4423. * bytes. With this organization, matches are limited to a distance of
  4424. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  4425. * performed with a length multiple of the block size.
  4426. */
  4427. this.window_size = 0;
  4428. /* Actual size of window: 2*wSize, except when the user input buffer
  4429. * is directly used as sliding window.
  4430. */
  4431. this.prev = null;
  4432. /* Link to older string with same hash index. To limit the size of this
  4433. * array to 64K, this link is maintained only for the last 32K strings.
  4434. * An index in this array is thus a window index modulo 32K.
  4435. */
  4436. this.head = null; /* Heads of the hash chains or NIL. */
  4437. this.ins_h = 0; /* hash index of string to be inserted */
  4438. this.hash_size = 0; /* number of elements in hash table */
  4439. this.hash_bits = 0; /* log2(hash_size) */
  4440. this.hash_mask = 0; /* hash_size-1 */
  4441. this.hash_shift = 0;
  4442. /* Number of bits by which ins_h must be shifted at each input
  4443. * step. It must be such that after MIN_MATCH steps, the oldest
  4444. * byte no longer takes part in the hash key, that is:
  4445. * hash_shift * MIN_MATCH >= hash_bits
  4446. */
  4447. this.block_start = 0;
  4448. /* Window position at the beginning of the current output block. Gets
  4449. * negative when the window is moved backwards.
  4450. */
  4451. this.match_length = 0; /* length of best match */
  4452. this.prev_match = 0; /* previous match */
  4453. this.match_available = 0; /* set if previous match exists */
  4454. this.strstart = 0; /* start of string to insert */
  4455. this.match_start = 0; /* start of matching string */
  4456. this.lookahead = 0; /* number of valid bytes ahead in window */
  4457. this.prev_length = 0;
  4458. /* Length of the best match at previous step. Matches not greater than this
  4459. * are discarded. This is used in the lazy match evaluation.
  4460. */
  4461. this.max_chain_length = 0;
  4462. /* To speed up deflation, hash chains are never searched beyond this
  4463. * length. A higher limit improves compression ratio but degrades the
  4464. * speed.
  4465. */
  4466. this.max_lazy_match = 0;
  4467. /* Attempt to find a better match only when the current match is strictly
  4468. * smaller than this value. This mechanism is used only for compression
  4469. * levels >= 4.
  4470. */
  4471. // That's alias to max_lazy_match, don't use directly
  4472. //this.max_insert_length = 0;
  4473. /* Insert new strings in the hash table only if the match length is not
  4474. * greater than this length. This saves time but degrades compression.
  4475. * max_insert_length is used only for compression levels <= 3.
  4476. */
  4477. this.level = 0; /* compression level (1..9) */
  4478. this.strategy = 0; /* favor or force Huffman coding*/
  4479. this.good_match = 0;
  4480. /* Use a faster search when the previous match is longer than this */
  4481. this.nice_match = 0; /* Stop searching when current match exceeds this */
  4482. /* used by trees.c: */
  4483. /* Didn't use ct_data typedef below to suppress compiler warning */
  4484. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  4485. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  4486. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  4487. // Use flat array of DOUBLE size, with interleaved fata,
  4488. // because JS does not support effective
  4489. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  4490. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  4491. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  4492. zero(this.dyn_ltree);
  4493. zero(this.dyn_dtree);
  4494. zero(this.bl_tree);
  4495. this.l_desc = null; /* desc. for literal tree */
  4496. this.d_desc = null; /* desc. for distance tree */
  4497. this.bl_desc = null; /* desc. for bit length tree */
  4498. //ush bl_count[MAX_BITS+1];
  4499. this.bl_count = new utils.Buf16(MAX_BITS+1);
  4500. /* number of codes at each bit length for an optimal tree */
  4501. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  4502. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  4503. zero(this.heap);
  4504. this.heap_len = 0; /* number of elements in the heap */
  4505. this.heap_max = 0; /* element of largest frequency */
  4506. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  4507. * The same heap array is used to build all trees.
  4508. */
  4509. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  4510. zero(this.depth);
  4511. /* Depth of each subtree used as tie breaker for trees of equal frequency
  4512. */
  4513. this.l_buf = 0; /* buffer index for literals or lengths */
  4514. this.lit_bufsize = 0;
  4515. /* Size of match buffer for literals/lengths. There are 4 reasons for
  4516. * limiting lit_bufsize to 64K:
  4517. * - frequencies can be kept in 16 bit counters
  4518. * - if compression is not successful for the first block, all input
  4519. * data is still in the window so we can still emit a stored block even
  4520. * when input comes from standard input. (This can also be done for
  4521. * all blocks if lit_bufsize is not greater than 32K.)
  4522. * - if compression is not successful for a file smaller than 64K, we can
  4523. * even emit a stored file instead of a stored block (saving 5 bytes).
  4524. * This is applicable only for zip (not gzip or zlib).
  4525. * - creating new Huffman trees less frequently may not provide fast
  4526. * adaptation to changes in the input data statistics. (Take for
  4527. * example a binary file with poorly compressible code followed by
  4528. * a highly compressible string table.) Smaller buffer sizes give
  4529. * fast adaptation but have of course the overhead of transmitting
  4530. * trees more frequently.
  4531. * - I can't count above 4
  4532. */
  4533. this.last_lit = 0; /* running index in l_buf */
  4534. this.d_buf = 0;
  4535. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  4536. * the same number of elements. To use different lengths, an extra flag
  4537. * array would be necessary.
  4538. */
  4539. this.opt_len = 0; /* bit length of current block with optimal trees */
  4540. this.static_len = 0; /* bit length of current block with static trees */
  4541. this.matches = 0; /* number of string matches in current block */
  4542. this.insert = 0; /* bytes at end of window left to insert */
  4543. this.bi_buf = 0;
  4544. /* Output buffer. bits are inserted starting at the bottom (least
  4545. * significant bits).
  4546. */
  4547. this.bi_valid = 0;
  4548. /* Number of valid bits in bi_buf. All bits above the last valid bit
  4549. * are always zero.
  4550. */
  4551. // Used for window memory init. We safely ignore it for JS. That makes
  4552. // sense only for pointers and memory check tools.
  4553. //this.high_water = 0;
  4554. /* High water mark offset in window for initialized bytes -- bytes above
  4555. * this are set to zero in order to avoid memory check warnings when
  4556. * longest match routines access bytes past the input. This is then
  4557. * updated to the new high water mark.
  4558. */
  4559. }
  4560. function deflateResetKeep(strm) {
  4561. var s;
  4562. if (!strm || !strm.state) {
  4563. return err(strm, Z_STREAM_ERROR);
  4564. }
  4565. strm.total_in = strm.total_out = 0;
  4566. strm.data_type = Z_UNKNOWN;
  4567. s = strm.state;
  4568. s.pending = 0;
  4569. s.pending_out = 0;
  4570. if (s.wrap < 0) {
  4571. s.wrap = -s.wrap;
  4572. /* was made negative by deflate(..., Z_FINISH); */
  4573. }
  4574. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  4575. strm.adler = (s.wrap === 2) ?
  4576. 0 // crc32(0, Z_NULL, 0)
  4577. :
  4578. 1; // adler32(0, Z_NULL, 0)
  4579. s.last_flush = Z_NO_FLUSH;
  4580. trees._tr_init(s);
  4581. return Z_OK;
  4582. }
  4583. function deflateReset(strm) {
  4584. var ret = deflateResetKeep(strm);
  4585. if (ret === Z_OK) {
  4586. lm_init(strm.state);
  4587. }
  4588. return ret;
  4589. }
  4590. function deflateSetHeader(strm, head) {
  4591. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  4592. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  4593. strm.state.gzhead = head;
  4594. return Z_OK;
  4595. }
  4596. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  4597. if (!strm) { // === Z_NULL
  4598. return Z_STREAM_ERROR;
  4599. }
  4600. var wrap = 1;
  4601. if (level === Z_DEFAULT_COMPRESSION) {
  4602. level = 6;
  4603. }
  4604. if (windowBits < 0) { /* suppress zlib wrapper */
  4605. wrap = 0;
  4606. windowBits = -windowBits;
  4607. }
  4608. else if (windowBits > 15) {
  4609. wrap = 2; /* write gzip wrapper instead */
  4610. windowBits -= 16;
  4611. }
  4612. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  4613. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  4614. strategy < 0 || strategy > Z_FIXED) {
  4615. return err(strm, Z_STREAM_ERROR);
  4616. }
  4617. if (windowBits === 8) {
  4618. windowBits = 9;
  4619. }
  4620. /* until 256-byte window bug fixed */
  4621. var s = new DeflateState();
  4622. strm.state = s;
  4623. s.strm = strm;
  4624. s.wrap = wrap;
  4625. s.gzhead = null;
  4626. s.w_bits = windowBits;
  4627. s.w_size = 1 << s.w_bits;
  4628. s.w_mask = s.w_size - 1;
  4629. s.hash_bits = memLevel + 7;
  4630. s.hash_size = 1 << s.hash_bits;
  4631. s.hash_mask = s.hash_size - 1;
  4632. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  4633. s.window = new utils.Buf8(s.w_size * 2);
  4634. s.head = new utils.Buf16(s.hash_size);
  4635. s.prev = new utils.Buf16(s.w_size);
  4636. // Don't need mem init magic for JS.
  4637. //s.high_water = 0; /* nothing written to s->window yet */
  4638. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  4639. s.pending_buf_size = s.lit_bufsize * 4;
  4640. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  4641. s.d_buf = s.lit_bufsize >> 1;
  4642. s.l_buf = (1 + 2) * s.lit_bufsize;
  4643. s.level = level;
  4644. s.strategy = strategy;
  4645. s.method = method;
  4646. return deflateReset(strm);
  4647. }
  4648. function deflateInit(strm, level) {
  4649. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  4650. }
  4651. function deflate(strm, flush) {
  4652. var old_flush, s;
  4653. var beg, val; // for gzip header write only
  4654. if (!strm || !strm.state ||
  4655. flush > Z_BLOCK || flush < 0) {
  4656. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  4657. }
  4658. s = strm.state;
  4659. if (!strm.output ||
  4660. (!strm.input && strm.avail_in !== 0) ||
  4661. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  4662. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  4663. }
  4664. s.strm = strm; /* just in case */
  4665. old_flush = s.last_flush;
  4666. s.last_flush = flush;
  4667. /* Write the header */
  4668. if (s.status === INIT_STATE) {
  4669. if (s.wrap === 2) { // GZIP header
  4670. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  4671. put_byte(s, 31);
  4672. put_byte(s, 139);
  4673. put_byte(s, 8);
  4674. if (!s.gzhead) { // s->gzhead == Z_NULL
  4675. put_byte(s, 0);
  4676. put_byte(s, 0);
  4677. put_byte(s, 0);
  4678. put_byte(s, 0);
  4679. put_byte(s, 0);
  4680. put_byte(s, s.level === 9 ? 2 :
  4681. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  4682. 4 : 0));
  4683. put_byte(s, OS_CODE);
  4684. s.status = BUSY_STATE;
  4685. }
  4686. else {
  4687. put_byte(s, (s.gzhead.text ? 1 : 0) +
  4688. (s.gzhead.hcrc ? 2 : 0) +
  4689. (!s.gzhead.extra ? 0 : 4) +
  4690. (!s.gzhead.name ? 0 : 8) +
  4691. (!s.gzhead.comment ? 0 : 16)
  4692. );
  4693. put_byte(s, s.gzhead.time & 0xff);
  4694. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  4695. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  4696. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  4697. put_byte(s, s.level === 9 ? 2 :
  4698. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  4699. 4 : 0));
  4700. put_byte(s, s.gzhead.os & 0xff);
  4701. if (s.gzhead.extra && s.gzhead.extra.length) {
  4702. put_byte(s, s.gzhead.extra.length & 0xff);
  4703. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  4704. }
  4705. if (s.gzhead.hcrc) {
  4706. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  4707. }
  4708. s.gzindex = 0;
  4709. s.status = EXTRA_STATE;
  4710. }
  4711. }
  4712. else // DEFLATE header
  4713. {
  4714. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  4715. var level_flags = -1;
  4716. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  4717. level_flags = 0;
  4718. } else if (s.level < 6) {
  4719. level_flags = 1;
  4720. } else if (s.level === 6) {
  4721. level_flags = 2;
  4722. } else {
  4723. level_flags = 3;
  4724. }
  4725. header |= (level_flags << 6);
  4726. if (s.strstart !== 0) { header |= PRESET_DICT; }
  4727. header += 31 - (header % 31);
  4728. s.status = BUSY_STATE;
  4729. putShortMSB(s, header);
  4730. /* Save the adler32 of the preset dictionary: */
  4731. if (s.strstart !== 0) {
  4732. putShortMSB(s, strm.adler >>> 16);
  4733. putShortMSB(s, strm.adler & 0xffff);
  4734. }
  4735. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  4736. }
  4737. }
  4738. //#ifdef GZIP
  4739. if (s.status === EXTRA_STATE) {
  4740. if (s.gzhead.extra/* != Z_NULL*/) {
  4741. beg = s.pending; /* start of bytes to update crc */
  4742. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  4743. if (s.pending === s.pending_buf_size) {
  4744. if (s.gzhead.hcrc && s.pending > beg) {
  4745. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4746. }
  4747. flush_pending(strm);
  4748. beg = s.pending;
  4749. if (s.pending === s.pending_buf_size) {
  4750. break;
  4751. }
  4752. }
  4753. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  4754. s.gzindex++;
  4755. }
  4756. if (s.gzhead.hcrc && s.pending > beg) {
  4757. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4758. }
  4759. if (s.gzindex === s.gzhead.extra.length) {
  4760. s.gzindex = 0;
  4761. s.status = NAME_STATE;
  4762. }
  4763. }
  4764. else {
  4765. s.status = NAME_STATE;
  4766. }
  4767. }
  4768. if (s.status === NAME_STATE) {
  4769. if (s.gzhead.name/* != Z_NULL*/) {
  4770. beg = s.pending; /* start of bytes to update crc */
  4771. //int val;
  4772. do {
  4773. if (s.pending === s.pending_buf_size) {
  4774. if (s.gzhead.hcrc && s.pending > beg) {
  4775. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4776. }
  4777. flush_pending(strm);
  4778. beg = s.pending;
  4779. if (s.pending === s.pending_buf_size) {
  4780. val = 1;
  4781. break;
  4782. }
  4783. }
  4784. // JS specific: little magic to add zero terminator to end of string
  4785. if (s.gzindex < s.gzhead.name.length) {
  4786. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  4787. } else {
  4788. val = 0;
  4789. }
  4790. put_byte(s, val);
  4791. } while (val !== 0);
  4792. if (s.gzhead.hcrc && s.pending > beg){
  4793. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4794. }
  4795. if (val === 0) {
  4796. s.gzindex = 0;
  4797. s.status = COMMENT_STATE;
  4798. }
  4799. }
  4800. else {
  4801. s.status = COMMENT_STATE;
  4802. }
  4803. }
  4804. if (s.status === COMMENT_STATE) {
  4805. if (s.gzhead.comment/* != Z_NULL*/) {
  4806. beg = s.pending; /* start of bytes to update crc */
  4807. //int val;
  4808. do {
  4809. if (s.pending === s.pending_buf_size) {
  4810. if (s.gzhead.hcrc && s.pending > beg) {
  4811. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4812. }
  4813. flush_pending(strm);
  4814. beg = s.pending;
  4815. if (s.pending === s.pending_buf_size) {
  4816. val = 1;
  4817. break;
  4818. }
  4819. }
  4820. // JS specific: little magic to add zero terminator to end of string
  4821. if (s.gzindex < s.gzhead.comment.length) {
  4822. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  4823. } else {
  4824. val = 0;
  4825. }
  4826. put_byte(s, val);
  4827. } while (val !== 0);
  4828. if (s.gzhead.hcrc && s.pending > beg) {
  4829. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4830. }
  4831. if (val === 0) {
  4832. s.status = HCRC_STATE;
  4833. }
  4834. }
  4835. else {
  4836. s.status = HCRC_STATE;
  4837. }
  4838. }
  4839. if (s.status === HCRC_STATE) {
  4840. if (s.gzhead.hcrc) {
  4841. if (s.pending + 2 > s.pending_buf_size) {
  4842. flush_pending(strm);
  4843. }
  4844. if (s.pending + 2 <= s.pending_buf_size) {
  4845. put_byte(s, strm.adler & 0xff);
  4846. put_byte(s, (strm.adler >> 8) & 0xff);
  4847. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  4848. s.status = BUSY_STATE;
  4849. }
  4850. }
  4851. else {
  4852. s.status = BUSY_STATE;
  4853. }
  4854. }
  4855. //#endif
  4856. /* Flush as much pending output as possible */
  4857. if (s.pending !== 0) {
  4858. flush_pending(strm);
  4859. if (strm.avail_out === 0) {
  4860. /* Since avail_out is 0, deflate will be called again with
  4861. * more output space, but possibly with both pending and
  4862. * avail_in equal to zero. There won't be anything to do,
  4863. * but this is not an error situation so make sure we
  4864. * return OK instead of BUF_ERROR at next call of deflate:
  4865. */
  4866. s.last_flush = -1;
  4867. return Z_OK;
  4868. }
  4869. /* Make sure there is something to do and avoid duplicate consecutive
  4870. * flushes. For repeated and useless calls with Z_FINISH, we keep
  4871. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  4872. */
  4873. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  4874. flush !== Z_FINISH) {
  4875. return err(strm, Z_BUF_ERROR);
  4876. }
  4877. /* User must not provide more input after the first FINISH: */
  4878. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  4879. return err(strm, Z_BUF_ERROR);
  4880. }
  4881. /* Start a new block or continue the current one.
  4882. */
  4883. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  4884. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  4885. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  4886. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  4887. configuration_table[s.level].func(s, flush));
  4888. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  4889. s.status = FINISH_STATE;
  4890. }
  4891. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  4892. if (strm.avail_out === 0) {
  4893. s.last_flush = -1;
  4894. /* avoid BUF_ERROR next call, see above */
  4895. }
  4896. return Z_OK;
  4897. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  4898. * of deflate should use the same flush parameter to make sure
  4899. * that the flush is complete. So we don't have to output an
  4900. * empty block here, this will be done at next call. This also
  4901. * ensures that for a very small output buffer, we emit at most
  4902. * one empty block.
  4903. */
  4904. }
  4905. if (bstate === BS_BLOCK_DONE) {
  4906. if (flush === Z_PARTIAL_FLUSH) {
  4907. trees._tr_align(s);
  4908. }
  4909. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  4910. trees._tr_stored_block(s, 0, 0, false);
  4911. /* For a full flush, this empty block will be recognized
  4912. * as a special marker by inflate_sync().
  4913. */
  4914. if (flush === Z_FULL_FLUSH) {
  4915. /*** CLEAR_HASH(s); ***/ /* forget history */
  4916. zero(s.head); // Fill with NIL (= 0);
  4917. if (s.lookahead === 0) {
  4918. s.strstart = 0;
  4919. s.block_start = 0;
  4920. s.insert = 0;
  4921. }
  4922. }
  4923. }
  4924. flush_pending(strm);
  4925. if (strm.avail_out === 0) {
  4926. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  4927. return Z_OK;
  4928. }
  4929. }
  4930. }
  4931. //Assert(strm->avail_out > 0, "bug2");
  4932. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  4933. if (flush !== Z_FINISH) { return Z_OK; }
  4934. if (s.wrap <= 0) { return Z_STREAM_END; }
  4935. /* Write the trailer */
  4936. if (s.wrap === 2) {
  4937. put_byte(s, strm.adler & 0xff);
  4938. put_byte(s, (strm.adler >> 8) & 0xff);
  4939. put_byte(s, (strm.adler >> 16) & 0xff);
  4940. put_byte(s, (strm.adler >> 24) & 0xff);
  4941. put_byte(s, strm.total_in & 0xff);
  4942. put_byte(s, (strm.total_in >> 8) & 0xff);
  4943. put_byte(s, (strm.total_in >> 16) & 0xff);
  4944. put_byte(s, (strm.total_in >> 24) & 0xff);
  4945. }
  4946. else
  4947. {
  4948. putShortMSB(s, strm.adler >>> 16);
  4949. putShortMSB(s, strm.adler & 0xffff);
  4950. }
  4951. flush_pending(strm);
  4952. /* If avail_out is zero, the application will call deflate again
  4953. * to flush the rest.
  4954. */
  4955. if (s.wrap > 0) { s.wrap = -s.wrap; }
  4956. /* write the trailer only once! */
  4957. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  4958. }
  4959. function deflateEnd(strm) {
  4960. var status;
  4961. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  4962. return Z_STREAM_ERROR;
  4963. }
  4964. status = strm.state.status;
  4965. if (status !== INIT_STATE &&
  4966. status !== EXTRA_STATE &&
  4967. status !== NAME_STATE &&
  4968. status !== COMMENT_STATE &&
  4969. status !== HCRC_STATE &&
  4970. status !== BUSY_STATE &&
  4971. status !== FINISH_STATE
  4972. ) {
  4973. return err(strm, Z_STREAM_ERROR);
  4974. }
  4975. strm.state = null;
  4976. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  4977. }
  4978. /* =========================================================================
  4979. * Copy the source state to the destination state
  4980. */
  4981. //function deflateCopy(dest, source) {
  4982. //
  4983. //}
  4984. exports.deflateInit = deflateInit;
  4985. exports.deflateInit2 = deflateInit2;
  4986. exports.deflateReset = deflateReset;
  4987. exports.deflateResetKeep = deflateResetKeep;
  4988. exports.deflateSetHeader = deflateSetHeader;
  4989. exports.deflate = deflate;
  4990. exports.deflateEnd = deflateEnd;
  4991. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  4992. /* Not implemented
  4993. exports.deflateBound = deflateBound;
  4994. exports.deflateCopy = deflateCopy;
  4995. exports.deflateSetDictionary = deflateSetDictionary;
  4996. exports.deflateParams = deflateParams;
  4997. exports.deflatePending = deflatePending;
  4998. exports.deflatePrime = deflatePrime;
  4999. exports.deflateTune = deflateTune;
  5000. */
  5001. },{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(_dereq_,module,exports){
  5002. 'use strict';
  5003. function GZheader() {
  5004. /* true if compressed data believed to be text */
  5005. this.text = 0;
  5006. /* modification time */
  5007. this.time = 0;
  5008. /* extra flags (not used when writing a gzip file) */
  5009. this.xflags = 0;
  5010. /* operating system */
  5011. this.os = 0;
  5012. /* pointer to extra field or Z_NULL if none */
  5013. this.extra = null;
  5014. /* extra field length (valid if extra != Z_NULL) */
  5015. this.extra_len = 0; // Actually, we don't need it in JS,
  5016. // but leave for few code modifications
  5017. //
  5018. // Setup limits is not necessary because in js we should not preallocate memory
  5019. // for inflate use constant limit in 65536 bytes
  5020. //
  5021. /* space at extra (only when reading header) */
  5022. // this.extra_max = 0;
  5023. /* pointer to zero-terminated file name or Z_NULL */
  5024. this.name = '';
  5025. /* space at name (only when reading header) */
  5026. // this.name_max = 0;
  5027. /* pointer to zero-terminated comment or Z_NULL */
  5028. this.comment = '';
  5029. /* space at comment (only when reading header) */
  5030. // this.comm_max = 0;
  5031. /* true if there was or will be a header crc */
  5032. this.hcrc = 0;
  5033. /* true when done reading gzip header (not used when writing a gzip file) */
  5034. this.done = false;
  5035. }
  5036. module.exports = GZheader;
  5037. },{}],34:[function(_dereq_,module,exports){
  5038. 'use strict';
  5039. // See state defs from inflate.js
  5040. var BAD = 30; /* got a data error -- remain here until reset */
  5041. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  5042. /*
  5043. Decode literal, length, and distance codes and write out the resulting
  5044. literal and match bytes until either not enough input or output is
  5045. available, an end-of-block is encountered, or a data error is encountered.
  5046. When large enough input and output buffers are supplied to inflate(), for
  5047. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  5048. inflate execution time is spent in this routine.
  5049. Entry assumptions:
  5050. state.mode === LEN
  5051. strm.avail_in >= 6
  5052. strm.avail_out >= 258
  5053. start >= strm.avail_out
  5054. state.bits < 8
  5055. On return, state.mode is one of:
  5056. LEN -- ran out of enough output space or enough available input
  5057. TYPE -- reached end of block code, inflate() to interpret next block
  5058. BAD -- error in block data
  5059. Notes:
  5060. - The maximum input bits used by a length/distance pair is 15 bits for the
  5061. length code, 5 bits for the length extra, 15 bits for the distance code,
  5062. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  5063. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  5064. checking for available input while decoding.
  5065. - The maximum bytes that a single length/distance pair can output is 258
  5066. bytes, which is the maximum length that can be coded. inflate_fast()
  5067. requires strm.avail_out >= 258 for each loop to avoid checking for
  5068. output space.
  5069. */
  5070. module.exports = function inflate_fast(strm, start) {
  5071. var state;
  5072. var _in; /* local strm.input */
  5073. var last; /* have enough input while in < last */
  5074. var _out; /* local strm.output */
  5075. var beg; /* inflate()'s initial strm.output */
  5076. var end; /* while out < end, enough space available */
  5077. //#ifdef INFLATE_STRICT
  5078. var dmax; /* maximum distance from zlib header */
  5079. //#endif
  5080. var wsize; /* window size or zero if not using window */
  5081. var whave; /* valid bytes in the window */
  5082. var wnext; /* window write index */
  5083. var window; /* allocated sliding window, if wsize != 0 */
  5084. var hold; /* local strm.hold */
  5085. var bits; /* local strm.bits */
  5086. var lcode; /* local strm.lencode */
  5087. var dcode; /* local strm.distcode */
  5088. var lmask; /* mask for first level of length codes */
  5089. var dmask; /* mask for first level of distance codes */
  5090. var here; /* retrieved table entry */
  5091. var op; /* code bits, operation, extra bits, or */
  5092. /* window position, window bytes to copy */
  5093. var len; /* match length, unused bytes */
  5094. var dist; /* match distance */
  5095. var from; /* where to copy match from */
  5096. var from_source;
  5097. var input, output; // JS specific, because we have no pointers
  5098. /* copy state to local variables */
  5099. state = strm.state;
  5100. //here = state.here;
  5101. _in = strm.next_in;
  5102. input = strm.input;
  5103. last = _in + (strm.avail_in - 5);
  5104. _out = strm.next_out;
  5105. output = strm.output;
  5106. beg = _out - (start - strm.avail_out);
  5107. end = _out + (strm.avail_out - 257);
  5108. //#ifdef INFLATE_STRICT
  5109. dmax = state.dmax;
  5110. //#endif
  5111. wsize = state.wsize;
  5112. whave = state.whave;
  5113. wnext = state.wnext;
  5114. window = state.window;
  5115. hold = state.hold;
  5116. bits = state.bits;
  5117. lcode = state.lencode;
  5118. dcode = state.distcode;
  5119. lmask = (1 << state.lenbits) - 1;
  5120. dmask = (1 << state.distbits) - 1;
  5121. /* decode literals and length/distances until end-of-block or not enough
  5122. input data or output space */
  5123. top:
  5124. do {
  5125. if (bits < 15) {
  5126. hold += input[_in++] << bits;
  5127. bits += 8;
  5128. hold += input[_in++] << bits;
  5129. bits += 8;
  5130. }
  5131. here = lcode[hold & lmask];
  5132. dolen:
  5133. for (;;) { // Goto emulation
  5134. op = here >>> 24/*here.bits*/;
  5135. hold >>>= op;
  5136. bits -= op;
  5137. op = (here >>> 16) & 0xff/*here.op*/;
  5138. if (op === 0) { /* literal */
  5139. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  5140. // "inflate: literal '%c'\n" :
  5141. // "inflate: literal 0x%02x\n", here.val));
  5142. output[_out++] = here & 0xffff/*here.val*/;
  5143. }
  5144. else if (op & 16) { /* length base */
  5145. len = here & 0xffff/*here.val*/;
  5146. op &= 15; /* number of extra bits */
  5147. if (op) {
  5148. if (bits < op) {
  5149. hold += input[_in++] << bits;
  5150. bits += 8;
  5151. }
  5152. len += hold & ((1 << op) - 1);
  5153. hold >>>= op;
  5154. bits -= op;
  5155. }
  5156. //Tracevv((stderr, "inflate: length %u\n", len));
  5157. if (bits < 15) {
  5158. hold += input[_in++] << bits;
  5159. bits += 8;
  5160. hold += input[_in++] << bits;
  5161. bits += 8;
  5162. }
  5163. here = dcode[hold & dmask];
  5164. dodist:
  5165. for (;;) { // goto emulation
  5166. op = here >>> 24/*here.bits*/;
  5167. hold >>>= op;
  5168. bits -= op;
  5169. op = (here >>> 16) & 0xff/*here.op*/;
  5170. if (op & 16) { /* distance base */
  5171. dist = here & 0xffff/*here.val*/;
  5172. op &= 15; /* number of extra bits */
  5173. if (bits < op) {
  5174. hold += input[_in++] << bits;
  5175. bits += 8;
  5176. if (bits < op) {
  5177. hold += input[_in++] << bits;
  5178. bits += 8;
  5179. }
  5180. }
  5181. dist += hold & ((1 << op) - 1);
  5182. //#ifdef INFLATE_STRICT
  5183. if (dist > dmax) {
  5184. strm.msg = 'invalid distance too far back';
  5185. state.mode = BAD;
  5186. break top;
  5187. }
  5188. //#endif
  5189. hold >>>= op;
  5190. bits -= op;
  5191. //Tracevv((stderr, "inflate: distance %u\n", dist));
  5192. op = _out - beg; /* max distance in output */
  5193. if (dist > op) { /* see if copy from window */
  5194. op = dist - op; /* distance back in window */
  5195. if (op > whave) {
  5196. if (state.sane) {
  5197. strm.msg = 'invalid distance too far back';
  5198. state.mode = BAD;
  5199. break top;
  5200. }
  5201. // (!) This block is disabled in zlib defailts,
  5202. // don't enable it for binary compatibility
  5203. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  5204. // if (len <= op - whave) {
  5205. // do {
  5206. // output[_out++] = 0;
  5207. // } while (--len);
  5208. // continue top;
  5209. // }
  5210. // len -= op - whave;
  5211. // do {
  5212. // output[_out++] = 0;
  5213. // } while (--op > whave);
  5214. // if (op === 0) {
  5215. // from = _out - dist;
  5216. // do {
  5217. // output[_out++] = output[from++];
  5218. // } while (--len);
  5219. // continue top;
  5220. // }
  5221. //#endif
  5222. }
  5223. from = 0; // window index
  5224. from_source = window;
  5225. if (wnext === 0) { /* very common case */
  5226. from += wsize - op;
  5227. if (op < len) { /* some from window */
  5228. len -= op;
  5229. do {
  5230. output[_out++] = window[from++];
  5231. } while (--op);
  5232. from = _out - dist; /* rest from output */
  5233. from_source = output;
  5234. }
  5235. }
  5236. else if (wnext < op) { /* wrap around window */
  5237. from += wsize + wnext - op;
  5238. op -= wnext;
  5239. if (op < len) { /* some from end of window */
  5240. len -= op;
  5241. do {
  5242. output[_out++] = window[from++];
  5243. } while (--op);
  5244. from = 0;
  5245. if (wnext < len) { /* some from start of window */
  5246. op = wnext;
  5247. len -= op;
  5248. do {
  5249. output[_out++] = window[from++];
  5250. } while (--op);
  5251. from = _out - dist; /* rest from output */
  5252. from_source = output;
  5253. }
  5254. }
  5255. }
  5256. else { /* contiguous in window */
  5257. from += wnext - op;
  5258. if (op < len) { /* some from window */
  5259. len -= op;
  5260. do {
  5261. output[_out++] = window[from++];
  5262. } while (--op);
  5263. from = _out - dist; /* rest from output */
  5264. from_source = output;
  5265. }
  5266. }
  5267. while (len > 2) {
  5268. output[_out++] = from_source[from++];
  5269. output[_out++] = from_source[from++];
  5270. output[_out++] = from_source[from++];
  5271. len -= 3;
  5272. }
  5273. if (len) {
  5274. output[_out++] = from_source[from++];
  5275. if (len > 1) {
  5276. output[_out++] = from_source[from++];
  5277. }
  5278. }
  5279. }
  5280. else {
  5281. from = _out - dist; /* copy direct from output */
  5282. do { /* minimum length is three */
  5283. output[_out++] = output[from++];
  5284. output[_out++] = output[from++];
  5285. output[_out++] = output[from++];
  5286. len -= 3;
  5287. } while (len > 2);
  5288. if (len) {
  5289. output[_out++] = output[from++];
  5290. if (len > 1) {
  5291. output[_out++] = output[from++];
  5292. }
  5293. }
  5294. }
  5295. }
  5296. else if ((op & 64) === 0) { /* 2nd level distance code */
  5297. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  5298. continue dodist;
  5299. }
  5300. else {
  5301. strm.msg = 'invalid distance code';
  5302. state.mode = BAD;
  5303. break top;
  5304. }
  5305. break; // need to emulate goto via "continue"
  5306. }
  5307. }
  5308. else if ((op & 64) === 0) { /* 2nd level length code */
  5309. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  5310. continue dolen;
  5311. }
  5312. else if (op & 32) { /* end-of-block */
  5313. //Tracevv((stderr, "inflate: end of block\n"));
  5314. state.mode = TYPE;
  5315. break top;
  5316. }
  5317. else {
  5318. strm.msg = 'invalid literal/length code';
  5319. state.mode = BAD;
  5320. break top;
  5321. }
  5322. break; // need to emulate goto via "continue"
  5323. }
  5324. } while (_in < last && _out < end);
  5325. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  5326. len = bits >> 3;
  5327. _in -= len;
  5328. bits -= len << 3;
  5329. hold &= (1 << bits) - 1;
  5330. /* update state and return */
  5331. strm.next_in = _in;
  5332. strm.next_out = _out;
  5333. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  5334. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  5335. state.hold = hold;
  5336. state.bits = bits;
  5337. return;
  5338. };
  5339. },{}],35:[function(_dereq_,module,exports){
  5340. 'use strict';
  5341. var utils = _dereq_('../utils/common');
  5342. var adler32 = _dereq_('./adler32');
  5343. var crc32 = _dereq_('./crc32');
  5344. var inflate_fast = _dereq_('./inffast');
  5345. var inflate_table = _dereq_('./inftrees');
  5346. var CODES = 0;
  5347. var LENS = 1;
  5348. var DISTS = 2;
  5349. /* Public constants ==========================================================*/
  5350. /* ===========================================================================*/
  5351. /* Allowed flush values; see deflate() and inflate() below for details */
  5352. //var Z_NO_FLUSH = 0;
  5353. //var Z_PARTIAL_FLUSH = 1;
  5354. //var Z_SYNC_FLUSH = 2;
  5355. //var Z_FULL_FLUSH = 3;
  5356. var Z_FINISH = 4;
  5357. var Z_BLOCK = 5;
  5358. var Z_TREES = 6;
  5359. /* Return codes for the compression/decompression functions. Negative values
  5360. * are errors, positive values are used for special but normal events.
  5361. */
  5362. var Z_OK = 0;
  5363. var Z_STREAM_END = 1;
  5364. var Z_NEED_DICT = 2;
  5365. //var Z_ERRNO = -1;
  5366. var Z_STREAM_ERROR = -2;
  5367. var Z_DATA_ERROR = -3;
  5368. var Z_MEM_ERROR = -4;
  5369. var Z_BUF_ERROR = -5;
  5370. //var Z_VERSION_ERROR = -6;
  5371. /* The deflate compression method */
  5372. var Z_DEFLATED = 8;
  5373. /* STATES ====================================================================*/
  5374. /* ===========================================================================*/
  5375. var HEAD = 1; /* i: waiting for magic header */
  5376. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  5377. var TIME = 3; /* i: waiting for modification time (gzip) */
  5378. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  5379. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  5380. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  5381. var NAME = 7; /* i: waiting for end of file name (gzip) */
  5382. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  5383. var HCRC = 9; /* i: waiting for header crc (gzip) */
  5384. var DICTID = 10; /* i: waiting for dictionary check value */
  5385. var DICT = 11; /* waiting for inflateSetDictionary() call */
  5386. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  5387. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  5388. var STORED = 14; /* i: waiting for stored size (length and complement) */
  5389. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  5390. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  5391. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  5392. var LENLENS = 18; /* i: waiting for code length code lengths */
  5393. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  5394. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  5395. var LEN = 21; /* i: waiting for length/lit/eob code */
  5396. var LENEXT = 22; /* i: waiting for length extra bits */
  5397. var DIST = 23; /* i: waiting for distance code */
  5398. var DISTEXT = 24; /* i: waiting for distance extra bits */
  5399. var MATCH = 25; /* o: waiting for output space to copy string */
  5400. var LIT = 26; /* o: waiting for output space to write literal */
  5401. var CHECK = 27; /* i: waiting for 32-bit check value */
  5402. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  5403. var DONE = 29; /* finished check, done -- remain here until reset */
  5404. var BAD = 30; /* got a data error -- remain here until reset */
  5405. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  5406. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  5407. /* ===========================================================================*/
  5408. var ENOUGH_LENS = 852;
  5409. var ENOUGH_DISTS = 592;
  5410. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  5411. var MAX_WBITS = 15;
  5412. /* 32K LZ77 window */
  5413. var DEF_WBITS = MAX_WBITS;
  5414. function ZSWAP32(q) {
  5415. return (((q >>> 24) & 0xff) +
  5416. ((q >>> 8) & 0xff00) +
  5417. ((q & 0xff00) << 8) +
  5418. ((q & 0xff) << 24));
  5419. }
  5420. function InflateState() {
  5421. this.mode = 0; /* current inflate mode */
  5422. this.last = false; /* true if processing last block */
  5423. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  5424. this.havedict = false; /* true if dictionary provided */
  5425. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  5426. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  5427. this.check = 0; /* protected copy of check value */
  5428. this.total = 0; /* protected copy of output count */
  5429. // TODO: may be {}
  5430. this.head = null; /* where to save gzip header information */
  5431. /* sliding window */
  5432. this.wbits = 0; /* log base 2 of requested window size */
  5433. this.wsize = 0; /* window size or zero if not using window */
  5434. this.whave = 0; /* valid bytes in the window */
  5435. this.wnext = 0; /* window write index */
  5436. this.window = null; /* allocated sliding window, if needed */
  5437. /* bit accumulator */
  5438. this.hold = 0; /* input bit accumulator */
  5439. this.bits = 0; /* number of bits in "in" */
  5440. /* for string and stored block copying */
  5441. this.length = 0; /* literal or length of data to copy */
  5442. this.offset = 0; /* distance back to copy string from */
  5443. /* for table and code decoding */
  5444. this.extra = 0; /* extra bits needed */
  5445. /* fixed and dynamic code tables */
  5446. this.lencode = null; /* starting table for length/literal codes */
  5447. this.distcode = null; /* starting table for distance codes */
  5448. this.lenbits = 0; /* index bits for lencode */
  5449. this.distbits = 0; /* index bits for distcode */
  5450. /* dynamic table building */
  5451. this.ncode = 0; /* number of code length code lengths */
  5452. this.nlen = 0; /* number of length code lengths */
  5453. this.ndist = 0; /* number of distance code lengths */
  5454. this.have = 0; /* number of code lengths in lens[] */
  5455. this.next = null; /* next available space in codes[] */
  5456. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  5457. this.work = new utils.Buf16(288); /* work area for code table building */
  5458. /*
  5459. because we don't have pointers in js, we use lencode and distcode directly
  5460. as buffers so we don't need codes
  5461. */
  5462. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  5463. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  5464. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  5465. this.sane = 0; /* if false, allow invalid distance too far */
  5466. this.back = 0; /* bits back of last unprocessed length/lit */
  5467. this.was = 0; /* initial length of match */
  5468. }
  5469. function inflateResetKeep(strm) {
  5470. var state;
  5471. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5472. state = strm.state;
  5473. strm.total_in = strm.total_out = state.total = 0;
  5474. strm.msg = ''; /*Z_NULL*/
  5475. if (state.wrap) { /* to support ill-conceived Java test suite */
  5476. strm.adler = state.wrap & 1;
  5477. }
  5478. state.mode = HEAD;
  5479. state.last = 0;
  5480. state.havedict = 0;
  5481. state.dmax = 32768;
  5482. state.head = null/*Z_NULL*/;
  5483. state.hold = 0;
  5484. state.bits = 0;
  5485. //state.lencode = state.distcode = state.next = state.codes;
  5486. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  5487. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  5488. state.sane = 1;
  5489. state.back = -1;
  5490. //Tracev((stderr, "inflate: reset\n"));
  5491. return Z_OK;
  5492. }
  5493. function inflateReset(strm) {
  5494. var state;
  5495. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5496. state = strm.state;
  5497. state.wsize = 0;
  5498. state.whave = 0;
  5499. state.wnext = 0;
  5500. return inflateResetKeep(strm);
  5501. }
  5502. function inflateReset2(strm, windowBits) {
  5503. var wrap;
  5504. var state;
  5505. /* get the state */
  5506. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5507. state = strm.state;
  5508. /* extract wrap request from windowBits parameter */
  5509. if (windowBits < 0) {
  5510. wrap = 0;
  5511. windowBits = -windowBits;
  5512. }
  5513. else {
  5514. wrap = (windowBits >> 4) + 1;
  5515. if (windowBits < 48) {
  5516. windowBits &= 15;
  5517. }
  5518. }
  5519. /* set number of window bits, free window if different */
  5520. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  5521. return Z_STREAM_ERROR;
  5522. }
  5523. if (state.window !== null && state.wbits !== windowBits) {
  5524. state.window = null;
  5525. }
  5526. /* update state and reset the rest of it */
  5527. state.wrap = wrap;
  5528. state.wbits = windowBits;
  5529. return inflateReset(strm);
  5530. }
  5531. function inflateInit2(strm, windowBits) {
  5532. var ret;
  5533. var state;
  5534. if (!strm) { return Z_STREAM_ERROR; }
  5535. //strm.msg = Z_NULL; /* in case we return an error */
  5536. state = new InflateState();
  5537. //if (state === Z_NULL) return Z_MEM_ERROR;
  5538. //Tracev((stderr, "inflate: allocated\n"));
  5539. strm.state = state;
  5540. state.window = null/*Z_NULL*/;
  5541. ret = inflateReset2(strm, windowBits);
  5542. if (ret !== Z_OK) {
  5543. strm.state = null/*Z_NULL*/;
  5544. }
  5545. return ret;
  5546. }
  5547. function inflateInit(strm) {
  5548. return inflateInit2(strm, DEF_WBITS);
  5549. }
  5550. /*
  5551. Return state with length and distance decoding tables and index sizes set to
  5552. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  5553. If BUILDFIXED is defined, then instead this routine builds the tables the
  5554. first time it's called, and returns those tables the first time and
  5555. thereafter. This reduces the size of the code by about 2K bytes, in
  5556. exchange for a little execution time. However, BUILDFIXED should not be
  5557. used for threaded applications, since the rewriting of the tables and virgin
  5558. may not be thread-safe.
  5559. */
  5560. var virgin = true;
  5561. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  5562. function fixedtables(state) {
  5563. /* build fixed huffman tables if first call (may not be thread safe) */
  5564. if (virgin) {
  5565. var sym;
  5566. lenfix = new utils.Buf32(512);
  5567. distfix = new utils.Buf32(32);
  5568. /* literal/length table */
  5569. sym = 0;
  5570. while (sym < 144) { state.lens[sym++] = 8; }
  5571. while (sym < 256) { state.lens[sym++] = 9; }
  5572. while (sym < 280) { state.lens[sym++] = 7; }
  5573. while (sym < 288) { state.lens[sym++] = 8; }
  5574. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  5575. /* distance table */
  5576. sym = 0;
  5577. while (sym < 32) { state.lens[sym++] = 5; }
  5578. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  5579. /* do this just once */
  5580. virgin = false;
  5581. }
  5582. state.lencode = lenfix;
  5583. state.lenbits = 9;
  5584. state.distcode = distfix;
  5585. state.distbits = 5;
  5586. }
  5587. /*
  5588. Update the window with the last wsize (normally 32K) bytes written before
  5589. returning. If window does not exist yet, create it. This is only called
  5590. when a window is already in use, or when output has been written during this
  5591. inflate call, but the end of the deflate stream has not been reached yet.
  5592. It is also called to create a window for dictionary data when a dictionary
  5593. is loaded.
  5594. Providing output buffers larger than 32K to inflate() should provide a speed
  5595. advantage, since only the last 32K of output is copied to the sliding window
  5596. upon return from inflate(), and since all distances after the first 32K of
  5597. output will fall in the output data, making match copies simpler and faster.
  5598. The advantage may be dependent on the size of the processor's data caches.
  5599. */
  5600. function updatewindow(strm, src, end, copy) {
  5601. var dist;
  5602. var state = strm.state;
  5603. /* if it hasn't been done already, allocate space for the window */
  5604. if (state.window === null) {
  5605. state.wsize = 1 << state.wbits;
  5606. state.wnext = 0;
  5607. state.whave = 0;
  5608. state.window = new utils.Buf8(state.wsize);
  5609. }
  5610. /* copy state->wsize or less output bytes into the circular window */
  5611. if (copy >= state.wsize) {
  5612. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  5613. state.wnext = 0;
  5614. state.whave = state.wsize;
  5615. }
  5616. else {
  5617. dist = state.wsize - state.wnext;
  5618. if (dist > copy) {
  5619. dist = copy;
  5620. }
  5621. //zmemcpy(state->window + state->wnext, end - copy, dist);
  5622. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  5623. copy -= dist;
  5624. if (copy) {
  5625. //zmemcpy(state->window, end - copy, copy);
  5626. utils.arraySet(state.window,src, end - copy, copy, 0);
  5627. state.wnext = copy;
  5628. state.whave = state.wsize;
  5629. }
  5630. else {
  5631. state.wnext += dist;
  5632. if (state.wnext === state.wsize) { state.wnext = 0; }
  5633. if (state.whave < state.wsize) { state.whave += dist; }
  5634. }
  5635. }
  5636. return 0;
  5637. }
  5638. function inflate(strm, flush) {
  5639. var state;
  5640. var input, output; // input/output buffers
  5641. var next; /* next input INDEX */
  5642. var put; /* next output INDEX */
  5643. var have, left; /* available input and output */
  5644. var hold; /* bit buffer */
  5645. var bits; /* bits in bit buffer */
  5646. var _in, _out; /* save starting available input and output */
  5647. var copy; /* number of stored or match bytes to copy */
  5648. var from; /* where to copy match bytes from */
  5649. var from_source;
  5650. var here = 0; /* current decoding table entry */
  5651. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  5652. //var last; /* parent table entry */
  5653. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  5654. var len; /* length to copy for repeats, bits to drop */
  5655. var ret; /* return code */
  5656. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  5657. var opts;
  5658. var n; // temporary var for NEED_BITS
  5659. var order = /* permutation of code lengths */
  5660. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  5661. if (!strm || !strm.state || !strm.output ||
  5662. (!strm.input && strm.avail_in !== 0)) {
  5663. return Z_STREAM_ERROR;
  5664. }
  5665. state = strm.state;
  5666. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  5667. //--- LOAD() ---
  5668. put = strm.next_out;
  5669. output = strm.output;
  5670. left = strm.avail_out;
  5671. next = strm.next_in;
  5672. input = strm.input;
  5673. have = strm.avail_in;
  5674. hold = state.hold;
  5675. bits = state.bits;
  5676. //---
  5677. _in = have;
  5678. _out = left;
  5679. ret = Z_OK;
  5680. inf_leave: // goto emulation
  5681. for (;;) {
  5682. switch (state.mode) {
  5683. case HEAD:
  5684. if (state.wrap === 0) {
  5685. state.mode = TYPEDO;
  5686. break;
  5687. }
  5688. //=== NEEDBITS(16);
  5689. while (bits < 16) {
  5690. if (have === 0) { break inf_leave; }
  5691. have--;
  5692. hold += input[next++] << bits;
  5693. bits += 8;
  5694. }
  5695. //===//
  5696. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  5697. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  5698. //=== CRC2(state.check, hold);
  5699. hbuf[0] = hold & 0xff;
  5700. hbuf[1] = (hold >>> 8) & 0xff;
  5701. state.check = crc32(state.check, hbuf, 2, 0);
  5702. //===//
  5703. //=== INITBITS();
  5704. hold = 0;
  5705. bits = 0;
  5706. //===//
  5707. state.mode = FLAGS;
  5708. break;
  5709. }
  5710. state.flags = 0; /* expect zlib header */
  5711. if (state.head) {
  5712. state.head.done = false;
  5713. }
  5714. if (!(state.wrap & 1) || /* check if zlib header allowed */
  5715. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  5716. strm.msg = 'incorrect header check';
  5717. state.mode = BAD;
  5718. break;
  5719. }
  5720. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  5721. strm.msg = 'unknown compression method';
  5722. state.mode = BAD;
  5723. break;
  5724. }
  5725. //--- DROPBITS(4) ---//
  5726. hold >>>= 4;
  5727. bits -= 4;
  5728. //---//
  5729. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  5730. if (state.wbits === 0) {
  5731. state.wbits = len;
  5732. }
  5733. else if (len > state.wbits) {
  5734. strm.msg = 'invalid window size';
  5735. state.mode = BAD;
  5736. break;
  5737. }
  5738. state.dmax = 1 << len;
  5739. //Tracev((stderr, "inflate: zlib header ok\n"));
  5740. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  5741. state.mode = hold & 0x200 ? DICTID : TYPE;
  5742. //=== INITBITS();
  5743. hold = 0;
  5744. bits = 0;
  5745. //===//
  5746. break;
  5747. case FLAGS:
  5748. //=== NEEDBITS(16); */
  5749. while (bits < 16) {
  5750. if (have === 0) { break inf_leave; }
  5751. have--;
  5752. hold += input[next++] << bits;
  5753. bits += 8;
  5754. }
  5755. //===//
  5756. state.flags = hold;
  5757. if ((state.flags & 0xff) !== Z_DEFLATED) {
  5758. strm.msg = 'unknown compression method';
  5759. state.mode = BAD;
  5760. break;
  5761. }
  5762. if (state.flags & 0xe000) {
  5763. strm.msg = 'unknown header flags set';
  5764. state.mode = BAD;
  5765. break;
  5766. }
  5767. if (state.head) {
  5768. state.head.text = ((hold >> 8) & 1);
  5769. }
  5770. if (state.flags & 0x0200) {
  5771. //=== CRC2(state.check, hold);
  5772. hbuf[0] = hold & 0xff;
  5773. hbuf[1] = (hold >>> 8) & 0xff;
  5774. state.check = crc32(state.check, hbuf, 2, 0);
  5775. //===//
  5776. }
  5777. //=== INITBITS();
  5778. hold = 0;
  5779. bits = 0;
  5780. //===//
  5781. state.mode = TIME;
  5782. /* falls through */
  5783. case TIME:
  5784. //=== NEEDBITS(32); */
  5785. while (bits < 32) {
  5786. if (have === 0) { break inf_leave; }
  5787. have--;
  5788. hold += input[next++] << bits;
  5789. bits += 8;
  5790. }
  5791. //===//
  5792. if (state.head) {
  5793. state.head.time = hold;
  5794. }
  5795. if (state.flags & 0x0200) {
  5796. //=== CRC4(state.check, hold)
  5797. hbuf[0] = hold & 0xff;
  5798. hbuf[1] = (hold >>> 8) & 0xff;
  5799. hbuf[2] = (hold >>> 16) & 0xff;
  5800. hbuf[3] = (hold >>> 24) & 0xff;
  5801. state.check = crc32(state.check, hbuf, 4, 0);
  5802. //===
  5803. }
  5804. //=== INITBITS();
  5805. hold = 0;
  5806. bits = 0;
  5807. //===//
  5808. state.mode = OS;
  5809. /* falls through */
  5810. case OS:
  5811. //=== NEEDBITS(16); */
  5812. while (bits < 16) {
  5813. if (have === 0) { break inf_leave; }
  5814. have--;
  5815. hold += input[next++] << bits;
  5816. bits += 8;
  5817. }
  5818. //===//
  5819. if (state.head) {
  5820. state.head.xflags = (hold & 0xff);
  5821. state.head.os = (hold >> 8);
  5822. }
  5823. if (state.flags & 0x0200) {
  5824. //=== CRC2(state.check, hold);
  5825. hbuf[0] = hold & 0xff;
  5826. hbuf[1] = (hold >>> 8) & 0xff;
  5827. state.check = crc32(state.check, hbuf, 2, 0);
  5828. //===//
  5829. }
  5830. //=== INITBITS();
  5831. hold = 0;
  5832. bits = 0;
  5833. //===//
  5834. state.mode = EXLEN;
  5835. /* falls through */
  5836. case EXLEN:
  5837. if (state.flags & 0x0400) {
  5838. //=== NEEDBITS(16); */
  5839. while (bits < 16) {
  5840. if (have === 0) { break inf_leave; }
  5841. have--;
  5842. hold += input[next++] << bits;
  5843. bits += 8;
  5844. }
  5845. //===//
  5846. state.length = hold;
  5847. if (state.head) {
  5848. state.head.extra_len = hold;
  5849. }
  5850. if (state.flags & 0x0200) {
  5851. //=== CRC2(state.check, hold);
  5852. hbuf[0] = hold & 0xff;
  5853. hbuf[1] = (hold >>> 8) & 0xff;
  5854. state.check = crc32(state.check, hbuf, 2, 0);
  5855. //===//
  5856. }
  5857. //=== INITBITS();
  5858. hold = 0;
  5859. bits = 0;
  5860. //===//
  5861. }
  5862. else if (state.head) {
  5863. state.head.extra = null/*Z_NULL*/;
  5864. }
  5865. state.mode = EXTRA;
  5866. /* falls through */
  5867. case EXTRA:
  5868. if (state.flags & 0x0400) {
  5869. copy = state.length;
  5870. if (copy > have) { copy = have; }
  5871. if (copy) {
  5872. if (state.head) {
  5873. len = state.head.extra_len - state.length;
  5874. if (!state.head.extra) {
  5875. // Use untyped array for more conveniend processing later
  5876. state.head.extra = new Array(state.head.extra_len);
  5877. }
  5878. utils.arraySet(
  5879. state.head.extra,
  5880. input,
  5881. next,
  5882. // extra field is limited to 65536 bytes
  5883. // - no need for additional size check
  5884. copy,
  5885. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  5886. len
  5887. );
  5888. //zmemcpy(state.head.extra + len, next,
  5889. // len + copy > state.head.extra_max ?
  5890. // state.head.extra_max - len : copy);
  5891. }
  5892. if (state.flags & 0x0200) {
  5893. state.check = crc32(state.check, input, copy, next);
  5894. }
  5895. have -= copy;
  5896. next += copy;
  5897. state.length -= copy;
  5898. }
  5899. if (state.length) { break inf_leave; }
  5900. }
  5901. state.length = 0;
  5902. state.mode = NAME;
  5903. /* falls through */
  5904. case NAME:
  5905. if (state.flags & 0x0800) {
  5906. if (have === 0) { break inf_leave; }
  5907. copy = 0;
  5908. do {
  5909. // TODO: 2 or 1 bytes?
  5910. len = input[next + copy++];
  5911. /* use constant limit because in js we should not preallocate memory */
  5912. if (state.head && len &&
  5913. (state.length < 65536 /*state.head.name_max*/)) {
  5914. state.head.name += String.fromCharCode(len);
  5915. }
  5916. } while (len && copy < have);
  5917. if (state.flags & 0x0200) {
  5918. state.check = crc32(state.check, input, copy, next);
  5919. }
  5920. have -= copy;
  5921. next += copy;
  5922. if (len) { break inf_leave; }
  5923. }
  5924. else if (state.head) {
  5925. state.head.name = null;
  5926. }
  5927. state.length = 0;
  5928. state.mode = COMMENT;
  5929. /* falls through */
  5930. case COMMENT:
  5931. if (state.flags & 0x1000) {
  5932. if (have === 0) { break inf_leave; }
  5933. copy = 0;
  5934. do {
  5935. len = input[next + copy++];
  5936. /* use constant limit because in js we should not preallocate memory */
  5937. if (state.head && len &&
  5938. (state.length < 65536 /*state.head.comm_max*/)) {
  5939. state.head.comment += String.fromCharCode(len);
  5940. }
  5941. } while (len && copy < have);
  5942. if (state.flags & 0x0200) {
  5943. state.check = crc32(state.check, input, copy, next);
  5944. }
  5945. have -= copy;
  5946. next += copy;
  5947. if (len) { break inf_leave; }
  5948. }
  5949. else if (state.head) {
  5950. state.head.comment = null;
  5951. }
  5952. state.mode = HCRC;
  5953. /* falls through */
  5954. case HCRC:
  5955. if (state.flags & 0x0200) {
  5956. //=== NEEDBITS(16); */
  5957. while (bits < 16) {
  5958. if (have === 0) { break inf_leave; }
  5959. have--;
  5960. hold += input[next++] << bits;
  5961. bits += 8;
  5962. }
  5963. //===//
  5964. if (hold !== (state.check & 0xffff)) {
  5965. strm.msg = 'header crc mismatch';
  5966. state.mode = BAD;
  5967. break;
  5968. }
  5969. //=== INITBITS();
  5970. hold = 0;
  5971. bits = 0;
  5972. //===//
  5973. }
  5974. if (state.head) {
  5975. state.head.hcrc = ((state.flags >> 9) & 1);
  5976. state.head.done = true;
  5977. }
  5978. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  5979. state.mode = TYPE;
  5980. break;
  5981. case DICTID:
  5982. //=== NEEDBITS(32); */
  5983. while (bits < 32) {
  5984. if (have === 0) { break inf_leave; }
  5985. have--;
  5986. hold += input[next++] << bits;
  5987. bits += 8;
  5988. }
  5989. //===//
  5990. strm.adler = state.check = ZSWAP32(hold);
  5991. //=== INITBITS();
  5992. hold = 0;
  5993. bits = 0;
  5994. //===//
  5995. state.mode = DICT;
  5996. /* falls through */
  5997. case DICT:
  5998. if (state.havedict === 0) {
  5999. //--- RESTORE() ---
  6000. strm.next_out = put;
  6001. strm.avail_out = left;
  6002. strm.next_in = next;
  6003. strm.avail_in = have;
  6004. state.hold = hold;
  6005. state.bits = bits;
  6006. //---
  6007. return Z_NEED_DICT;
  6008. }
  6009. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  6010. state.mode = TYPE;
  6011. /* falls through */
  6012. case TYPE:
  6013. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  6014. /* falls through */
  6015. case TYPEDO:
  6016. if (state.last) {
  6017. //--- BYTEBITS() ---//
  6018. hold >>>= bits & 7;
  6019. bits -= bits & 7;
  6020. //---//
  6021. state.mode = CHECK;
  6022. break;
  6023. }
  6024. //=== NEEDBITS(3); */
  6025. while (bits < 3) {
  6026. if (have === 0) { break inf_leave; }
  6027. have--;
  6028. hold += input[next++] << bits;
  6029. bits += 8;
  6030. }
  6031. //===//
  6032. state.last = (hold & 0x01)/*BITS(1)*/;
  6033. //--- DROPBITS(1) ---//
  6034. hold >>>= 1;
  6035. bits -= 1;
  6036. //---//
  6037. switch ((hold & 0x03)/*BITS(2)*/) {
  6038. case 0: /* stored block */
  6039. //Tracev((stderr, "inflate: stored block%s\n",
  6040. // state.last ? " (last)" : ""));
  6041. state.mode = STORED;
  6042. break;
  6043. case 1: /* fixed block */
  6044. fixedtables(state);
  6045. //Tracev((stderr, "inflate: fixed codes block%s\n",
  6046. // state.last ? " (last)" : ""));
  6047. state.mode = LEN_; /* decode codes */
  6048. if (flush === Z_TREES) {
  6049. //--- DROPBITS(2) ---//
  6050. hold >>>= 2;
  6051. bits -= 2;
  6052. //---//
  6053. break inf_leave;
  6054. }
  6055. break;
  6056. case 2: /* dynamic block */
  6057. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  6058. // state.last ? " (last)" : ""));
  6059. state.mode = TABLE;
  6060. break;
  6061. case 3:
  6062. strm.msg = 'invalid block type';
  6063. state.mode = BAD;
  6064. }
  6065. //--- DROPBITS(2) ---//
  6066. hold >>>= 2;
  6067. bits -= 2;
  6068. //---//
  6069. break;
  6070. case STORED:
  6071. //--- BYTEBITS() ---// /* go to byte boundary */
  6072. hold >>>= bits & 7;
  6073. bits -= bits & 7;
  6074. //---//
  6075. //=== NEEDBITS(32); */
  6076. while (bits < 32) {
  6077. if (have === 0) { break inf_leave; }
  6078. have--;
  6079. hold += input[next++] << bits;
  6080. bits += 8;
  6081. }
  6082. //===//
  6083. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  6084. strm.msg = 'invalid stored block lengths';
  6085. state.mode = BAD;
  6086. break;
  6087. }
  6088. state.length = hold & 0xffff;
  6089. //Tracev((stderr, "inflate: stored length %u\n",
  6090. // state.length));
  6091. //=== INITBITS();
  6092. hold = 0;
  6093. bits = 0;
  6094. //===//
  6095. state.mode = COPY_;
  6096. if (flush === Z_TREES) { break inf_leave; }
  6097. /* falls through */
  6098. case COPY_:
  6099. state.mode = COPY;
  6100. /* falls through */
  6101. case COPY:
  6102. copy = state.length;
  6103. if (copy) {
  6104. if (copy > have) { copy = have; }
  6105. if (copy > left) { copy = left; }
  6106. if (copy === 0) { break inf_leave; }
  6107. //--- zmemcpy(put, next, copy); ---
  6108. utils.arraySet(output, input, next, copy, put);
  6109. //---//
  6110. have -= copy;
  6111. next += copy;
  6112. left -= copy;
  6113. put += copy;
  6114. state.length -= copy;
  6115. break;
  6116. }
  6117. //Tracev((stderr, "inflate: stored end\n"));
  6118. state.mode = TYPE;
  6119. break;
  6120. case TABLE:
  6121. //=== NEEDBITS(14); */
  6122. while (bits < 14) {
  6123. if (have === 0) { break inf_leave; }
  6124. have--;
  6125. hold += input[next++] << bits;
  6126. bits += 8;
  6127. }
  6128. //===//
  6129. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  6130. //--- DROPBITS(5) ---//
  6131. hold >>>= 5;
  6132. bits -= 5;
  6133. //---//
  6134. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  6135. //--- DROPBITS(5) ---//
  6136. hold >>>= 5;
  6137. bits -= 5;
  6138. //---//
  6139. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  6140. //--- DROPBITS(4) ---//
  6141. hold >>>= 4;
  6142. bits -= 4;
  6143. //---//
  6144. //#ifndef PKZIP_BUG_WORKAROUND
  6145. if (state.nlen > 286 || state.ndist > 30) {
  6146. strm.msg = 'too many length or distance symbols';
  6147. state.mode = BAD;
  6148. break;
  6149. }
  6150. //#endif
  6151. //Tracev((stderr, "inflate: table sizes ok\n"));
  6152. state.have = 0;
  6153. state.mode = LENLENS;
  6154. /* falls through */
  6155. case LENLENS:
  6156. while (state.have < state.ncode) {
  6157. //=== NEEDBITS(3);
  6158. while (bits < 3) {
  6159. if (have === 0) { break inf_leave; }
  6160. have--;
  6161. hold += input[next++] << bits;
  6162. bits += 8;
  6163. }
  6164. //===//
  6165. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  6166. //--- DROPBITS(3) ---//
  6167. hold >>>= 3;
  6168. bits -= 3;
  6169. //---//
  6170. }
  6171. while (state.have < 19) {
  6172. state.lens[order[state.have++]] = 0;
  6173. }
  6174. // We have separate tables & no pointers. 2 commented lines below not needed.
  6175. //state.next = state.codes;
  6176. //state.lencode = state.next;
  6177. // Switch to use dynamic table
  6178. state.lencode = state.lendyn;
  6179. state.lenbits = 7;
  6180. opts = {bits: state.lenbits};
  6181. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  6182. state.lenbits = opts.bits;
  6183. if (ret) {
  6184. strm.msg = 'invalid code lengths set';
  6185. state.mode = BAD;
  6186. break;
  6187. }
  6188. //Tracev((stderr, "inflate: code lengths ok\n"));
  6189. state.have = 0;
  6190. state.mode = CODELENS;
  6191. /* falls through */
  6192. case CODELENS:
  6193. while (state.have < state.nlen + state.ndist) {
  6194. for (;;) {
  6195. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  6196. here_bits = here >>> 24;
  6197. here_op = (here >>> 16) & 0xff;
  6198. here_val = here & 0xffff;
  6199. if ((here_bits) <= bits) { break; }
  6200. //--- PULLBYTE() ---//
  6201. if (have === 0) { break inf_leave; }
  6202. have--;
  6203. hold += input[next++] << bits;
  6204. bits += 8;
  6205. //---//
  6206. }
  6207. if (here_val < 16) {
  6208. //--- DROPBITS(here.bits) ---//
  6209. hold >>>= here_bits;
  6210. bits -= here_bits;
  6211. //---//
  6212. state.lens[state.have++] = here_val;
  6213. }
  6214. else {
  6215. if (here_val === 16) {
  6216. //=== NEEDBITS(here.bits + 2);
  6217. n = here_bits + 2;
  6218. while (bits < n) {
  6219. if (have === 0) { break inf_leave; }
  6220. have--;
  6221. hold += input[next++] << bits;
  6222. bits += 8;
  6223. }
  6224. //===//
  6225. //--- DROPBITS(here.bits) ---//
  6226. hold >>>= here_bits;
  6227. bits -= here_bits;
  6228. //---//
  6229. if (state.have === 0) {
  6230. strm.msg = 'invalid bit length repeat';
  6231. state.mode = BAD;
  6232. break;
  6233. }
  6234. len = state.lens[state.have - 1];
  6235. copy = 3 + (hold & 0x03);//BITS(2);
  6236. //--- DROPBITS(2) ---//
  6237. hold >>>= 2;
  6238. bits -= 2;
  6239. //---//
  6240. }
  6241. else if (here_val === 17) {
  6242. //=== NEEDBITS(here.bits + 3);
  6243. n = here_bits + 3;
  6244. while (bits < n) {
  6245. if (have === 0) { break inf_leave; }
  6246. have--;
  6247. hold += input[next++] << bits;
  6248. bits += 8;
  6249. }
  6250. //===//
  6251. //--- DROPBITS(here.bits) ---//
  6252. hold >>>= here_bits;
  6253. bits -= here_bits;
  6254. //---//
  6255. len = 0;
  6256. copy = 3 + (hold & 0x07);//BITS(3);
  6257. //--- DROPBITS(3) ---//
  6258. hold >>>= 3;
  6259. bits -= 3;
  6260. //---//
  6261. }
  6262. else {
  6263. //=== NEEDBITS(here.bits + 7);
  6264. n = here_bits + 7;
  6265. while (bits < n) {
  6266. if (have === 0) { break inf_leave; }
  6267. have--;
  6268. hold += input[next++] << bits;
  6269. bits += 8;
  6270. }
  6271. //===//
  6272. //--- DROPBITS(here.bits) ---//
  6273. hold >>>= here_bits;
  6274. bits -= here_bits;
  6275. //---//
  6276. len = 0;
  6277. copy = 11 + (hold & 0x7f);//BITS(7);
  6278. //--- DROPBITS(7) ---//
  6279. hold >>>= 7;
  6280. bits -= 7;
  6281. //---//
  6282. }
  6283. if (state.have + copy > state.nlen + state.ndist) {
  6284. strm.msg = 'invalid bit length repeat';
  6285. state.mode = BAD;
  6286. break;
  6287. }
  6288. while (copy--) {
  6289. state.lens[state.have++] = len;
  6290. }
  6291. }
  6292. }
  6293. /* handle error breaks in while */
  6294. if (state.mode === BAD) { break; }
  6295. /* check for end-of-block code (better have one) */
  6296. if (state.lens[256] === 0) {
  6297. strm.msg = 'invalid code -- missing end-of-block';
  6298. state.mode = BAD;
  6299. break;
  6300. }
  6301. /* build code tables -- note: do not change the lenbits or distbits
  6302. values here (9 and 6) without reading the comments in inftrees.h
  6303. concerning the ENOUGH constants, which depend on those values */
  6304. state.lenbits = 9;
  6305. opts = {bits: state.lenbits};
  6306. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  6307. // We have separate tables & no pointers. 2 commented lines below not needed.
  6308. // state.next_index = opts.table_index;
  6309. state.lenbits = opts.bits;
  6310. // state.lencode = state.next;
  6311. if (ret) {
  6312. strm.msg = 'invalid literal/lengths set';
  6313. state.mode = BAD;
  6314. break;
  6315. }
  6316. state.distbits = 6;
  6317. //state.distcode.copy(state.codes);
  6318. // Switch to use dynamic table
  6319. state.distcode = state.distdyn;
  6320. opts = {bits: state.distbits};
  6321. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  6322. // We have separate tables & no pointers. 2 commented lines below not needed.
  6323. // state.next_index = opts.table_index;
  6324. state.distbits = opts.bits;
  6325. // state.distcode = state.next;
  6326. if (ret) {
  6327. strm.msg = 'invalid distances set';
  6328. state.mode = BAD;
  6329. break;
  6330. }
  6331. //Tracev((stderr, 'inflate: codes ok\n'));
  6332. state.mode = LEN_;
  6333. if (flush === Z_TREES) { break inf_leave; }
  6334. /* falls through */
  6335. case LEN_:
  6336. state.mode = LEN;
  6337. /* falls through */
  6338. case LEN:
  6339. if (have >= 6 && left >= 258) {
  6340. //--- RESTORE() ---
  6341. strm.next_out = put;
  6342. strm.avail_out = left;
  6343. strm.next_in = next;
  6344. strm.avail_in = have;
  6345. state.hold = hold;
  6346. state.bits = bits;
  6347. //---
  6348. inflate_fast(strm, _out);
  6349. //--- LOAD() ---
  6350. put = strm.next_out;
  6351. output = strm.output;
  6352. left = strm.avail_out;
  6353. next = strm.next_in;
  6354. input = strm.input;
  6355. have = strm.avail_in;
  6356. hold = state.hold;
  6357. bits = state.bits;
  6358. //---
  6359. if (state.mode === TYPE) {
  6360. state.back = -1;
  6361. }
  6362. break;
  6363. }
  6364. state.back = 0;
  6365. for (;;) {
  6366. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  6367. here_bits = here >>> 24;
  6368. here_op = (here >>> 16) & 0xff;
  6369. here_val = here & 0xffff;
  6370. if (here_bits <= bits) { break; }
  6371. //--- PULLBYTE() ---//
  6372. if (have === 0) { break inf_leave; }
  6373. have--;
  6374. hold += input[next++] << bits;
  6375. bits += 8;
  6376. //---//
  6377. }
  6378. if (here_op && (here_op & 0xf0) === 0) {
  6379. last_bits = here_bits;
  6380. last_op = here_op;
  6381. last_val = here_val;
  6382. for (;;) {
  6383. here = state.lencode[last_val +
  6384. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  6385. here_bits = here >>> 24;
  6386. here_op = (here >>> 16) & 0xff;
  6387. here_val = here & 0xffff;
  6388. if ((last_bits + here_bits) <= bits) { break; }
  6389. //--- PULLBYTE() ---//
  6390. if (have === 0) { break inf_leave; }
  6391. have--;
  6392. hold += input[next++] << bits;
  6393. bits += 8;
  6394. //---//
  6395. }
  6396. //--- DROPBITS(last.bits) ---//
  6397. hold >>>= last_bits;
  6398. bits -= last_bits;
  6399. //---//
  6400. state.back += last_bits;
  6401. }
  6402. //--- DROPBITS(here.bits) ---//
  6403. hold >>>= here_bits;
  6404. bits -= here_bits;
  6405. //---//
  6406. state.back += here_bits;
  6407. state.length = here_val;
  6408. if (here_op === 0) {
  6409. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  6410. // "inflate: literal '%c'\n" :
  6411. // "inflate: literal 0x%02x\n", here.val));
  6412. state.mode = LIT;
  6413. break;
  6414. }
  6415. if (here_op & 32) {
  6416. //Tracevv((stderr, "inflate: end of block\n"));
  6417. state.back = -1;
  6418. state.mode = TYPE;
  6419. break;
  6420. }
  6421. if (here_op & 64) {
  6422. strm.msg = 'invalid literal/length code';
  6423. state.mode = BAD;
  6424. break;
  6425. }
  6426. state.extra = here_op & 15;
  6427. state.mode = LENEXT;
  6428. /* falls through */
  6429. case LENEXT:
  6430. if (state.extra) {
  6431. //=== NEEDBITS(state.extra);
  6432. n = state.extra;
  6433. while (bits < n) {
  6434. if (have === 0) { break inf_leave; }
  6435. have--;
  6436. hold += input[next++] << bits;
  6437. bits += 8;
  6438. }
  6439. //===//
  6440. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  6441. //--- DROPBITS(state.extra) ---//
  6442. hold >>>= state.extra;
  6443. bits -= state.extra;
  6444. //---//
  6445. state.back += state.extra;
  6446. }
  6447. //Tracevv((stderr, "inflate: length %u\n", state.length));
  6448. state.was = state.length;
  6449. state.mode = DIST;
  6450. /* falls through */
  6451. case DIST:
  6452. for (;;) {
  6453. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  6454. here_bits = here >>> 24;
  6455. here_op = (here >>> 16) & 0xff;
  6456. here_val = here & 0xffff;
  6457. if ((here_bits) <= bits) { break; }
  6458. //--- PULLBYTE() ---//
  6459. if (have === 0) { break inf_leave; }
  6460. have--;
  6461. hold += input[next++] << bits;
  6462. bits += 8;
  6463. //---//
  6464. }
  6465. if ((here_op & 0xf0) === 0) {
  6466. last_bits = here_bits;
  6467. last_op = here_op;
  6468. last_val = here_val;
  6469. for (;;) {
  6470. here = state.distcode[last_val +
  6471. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  6472. here_bits = here >>> 24;
  6473. here_op = (here >>> 16) & 0xff;
  6474. here_val = here & 0xffff;
  6475. if ((last_bits + here_bits) <= bits) { break; }
  6476. //--- PULLBYTE() ---//
  6477. if (have === 0) { break inf_leave; }
  6478. have--;
  6479. hold += input[next++] << bits;
  6480. bits += 8;
  6481. //---//
  6482. }
  6483. //--- DROPBITS(last.bits) ---//
  6484. hold >>>= last_bits;
  6485. bits -= last_bits;
  6486. //---//
  6487. state.back += last_bits;
  6488. }
  6489. //--- DROPBITS(here.bits) ---//
  6490. hold >>>= here_bits;
  6491. bits -= here_bits;
  6492. //---//
  6493. state.back += here_bits;
  6494. if (here_op & 64) {
  6495. strm.msg = 'invalid distance code';
  6496. state.mode = BAD;
  6497. break;
  6498. }
  6499. state.offset = here_val;
  6500. state.extra = (here_op) & 15;
  6501. state.mode = DISTEXT;
  6502. /* falls through */
  6503. case DISTEXT:
  6504. if (state.extra) {
  6505. //=== NEEDBITS(state.extra);
  6506. n = state.extra;
  6507. while (bits < n) {
  6508. if (have === 0) { break inf_leave; }
  6509. have--;
  6510. hold += input[next++] << bits;
  6511. bits += 8;
  6512. }
  6513. //===//
  6514. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  6515. //--- DROPBITS(state.extra) ---//
  6516. hold >>>= state.extra;
  6517. bits -= state.extra;
  6518. //---//
  6519. state.back += state.extra;
  6520. }
  6521. //#ifdef INFLATE_STRICT
  6522. if (state.offset > state.dmax) {
  6523. strm.msg = 'invalid distance too far back';
  6524. state.mode = BAD;
  6525. break;
  6526. }
  6527. //#endif
  6528. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  6529. state.mode = MATCH;
  6530. /* falls through */
  6531. case MATCH:
  6532. if (left === 0) { break inf_leave; }
  6533. copy = _out - left;
  6534. if (state.offset > copy) { /* copy from window */
  6535. copy = state.offset - copy;
  6536. if (copy > state.whave) {
  6537. if (state.sane) {
  6538. strm.msg = 'invalid distance too far back';
  6539. state.mode = BAD;
  6540. break;
  6541. }
  6542. // (!) This block is disabled in zlib defailts,
  6543. // don't enable it for binary compatibility
  6544. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  6545. // Trace((stderr, "inflate.c too far\n"));
  6546. // copy -= state.whave;
  6547. // if (copy > state.length) { copy = state.length; }
  6548. // if (copy > left) { copy = left; }
  6549. // left -= copy;
  6550. // state.length -= copy;
  6551. // do {
  6552. // output[put++] = 0;
  6553. // } while (--copy);
  6554. // if (state.length === 0) { state.mode = LEN; }
  6555. // break;
  6556. //#endif
  6557. }
  6558. if (copy > state.wnext) {
  6559. copy -= state.wnext;
  6560. from = state.wsize - copy;
  6561. }
  6562. else {
  6563. from = state.wnext - copy;
  6564. }
  6565. if (copy > state.length) { copy = state.length; }
  6566. from_source = state.window;
  6567. }
  6568. else { /* copy from output */
  6569. from_source = output;
  6570. from = put - state.offset;
  6571. copy = state.length;
  6572. }
  6573. if (copy > left) { copy = left; }
  6574. left -= copy;
  6575. state.length -= copy;
  6576. do {
  6577. output[put++] = from_source[from++];
  6578. } while (--copy);
  6579. if (state.length === 0) { state.mode = LEN; }
  6580. break;
  6581. case LIT:
  6582. if (left === 0) { break inf_leave; }
  6583. output[put++] = state.length;
  6584. left--;
  6585. state.mode = LEN;
  6586. break;
  6587. case CHECK:
  6588. if (state.wrap) {
  6589. //=== NEEDBITS(32);
  6590. while (bits < 32) {
  6591. if (have === 0) { break inf_leave; }
  6592. have--;
  6593. // Use '|' insdead of '+' to make sure that result is signed
  6594. hold |= input[next++] << bits;
  6595. bits += 8;
  6596. }
  6597. //===//
  6598. _out -= left;
  6599. strm.total_out += _out;
  6600. state.total += _out;
  6601. if (_out) {
  6602. strm.adler = state.check =
  6603. /*UPDATE(state.check, put - _out, _out);*/
  6604. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  6605. }
  6606. _out = left;
  6607. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  6608. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  6609. strm.msg = 'incorrect data check';
  6610. state.mode = BAD;
  6611. break;
  6612. }
  6613. //=== INITBITS();
  6614. hold = 0;
  6615. bits = 0;
  6616. //===//
  6617. //Tracev((stderr, "inflate: check matches trailer\n"));
  6618. }
  6619. state.mode = LENGTH;
  6620. /* falls through */
  6621. case LENGTH:
  6622. if (state.wrap && state.flags) {
  6623. //=== NEEDBITS(32);
  6624. while (bits < 32) {
  6625. if (have === 0) { break inf_leave; }
  6626. have--;
  6627. hold += input[next++] << bits;
  6628. bits += 8;
  6629. }
  6630. //===//
  6631. if (hold !== (state.total & 0xffffffff)) {
  6632. strm.msg = 'incorrect length check';
  6633. state.mode = BAD;
  6634. break;
  6635. }
  6636. //=== INITBITS();
  6637. hold = 0;
  6638. bits = 0;
  6639. //===//
  6640. //Tracev((stderr, "inflate: length matches trailer\n"));
  6641. }
  6642. state.mode = DONE;
  6643. /* falls through */
  6644. case DONE:
  6645. ret = Z_STREAM_END;
  6646. break inf_leave;
  6647. case BAD:
  6648. ret = Z_DATA_ERROR;
  6649. break inf_leave;
  6650. case MEM:
  6651. return Z_MEM_ERROR;
  6652. case SYNC:
  6653. /* falls through */
  6654. default:
  6655. return Z_STREAM_ERROR;
  6656. }
  6657. }
  6658. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  6659. /*
  6660. Return from inflate(), updating the total counts and the check value.
  6661. If there was no progress during the inflate() call, return a buffer
  6662. error. Call updatewindow() to create and/or update the window state.
  6663. Note: a memory error from inflate() is non-recoverable.
  6664. */
  6665. //--- RESTORE() ---
  6666. strm.next_out = put;
  6667. strm.avail_out = left;
  6668. strm.next_in = next;
  6669. strm.avail_in = have;
  6670. state.hold = hold;
  6671. state.bits = bits;
  6672. //---
  6673. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  6674. (state.mode < CHECK || flush !== Z_FINISH))) {
  6675. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  6676. state.mode = MEM;
  6677. return Z_MEM_ERROR;
  6678. }
  6679. }
  6680. _in -= strm.avail_in;
  6681. _out -= strm.avail_out;
  6682. strm.total_in += _in;
  6683. strm.total_out += _out;
  6684. state.total += _out;
  6685. if (state.wrap && _out) {
  6686. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  6687. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  6688. }
  6689. strm.data_type = state.bits + (state.last ? 64 : 0) +
  6690. (state.mode === TYPE ? 128 : 0) +
  6691. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  6692. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  6693. ret = Z_BUF_ERROR;
  6694. }
  6695. return ret;
  6696. }
  6697. function inflateEnd(strm) {
  6698. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  6699. return Z_STREAM_ERROR;
  6700. }
  6701. var state = strm.state;
  6702. if (state.window) {
  6703. state.window = null;
  6704. }
  6705. strm.state = null;
  6706. return Z_OK;
  6707. }
  6708. function inflateGetHeader(strm, head) {
  6709. var state;
  6710. /* check state */
  6711. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6712. state = strm.state;
  6713. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  6714. /* save header structure */
  6715. state.head = head;
  6716. head.done = false;
  6717. return Z_OK;
  6718. }
  6719. exports.inflateReset = inflateReset;
  6720. exports.inflateReset2 = inflateReset2;
  6721. exports.inflateResetKeep = inflateResetKeep;
  6722. exports.inflateInit = inflateInit;
  6723. exports.inflateInit2 = inflateInit2;
  6724. exports.inflate = inflate;
  6725. exports.inflateEnd = inflateEnd;
  6726. exports.inflateGetHeader = inflateGetHeader;
  6727. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  6728. /* Not implemented
  6729. exports.inflateCopy = inflateCopy;
  6730. exports.inflateGetDictionary = inflateGetDictionary;
  6731. exports.inflateMark = inflateMark;
  6732. exports.inflatePrime = inflatePrime;
  6733. exports.inflateSetDictionary = inflateSetDictionary;
  6734. exports.inflateSync = inflateSync;
  6735. exports.inflateSyncPoint = inflateSyncPoint;
  6736. exports.inflateUndermine = inflateUndermine;
  6737. */
  6738. },{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(_dereq_,module,exports){
  6739. 'use strict';
  6740. var utils = _dereq_('../utils/common');
  6741. var MAXBITS = 15;
  6742. var ENOUGH_LENS = 852;
  6743. var ENOUGH_DISTS = 592;
  6744. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  6745. var CODES = 0;
  6746. var LENS = 1;
  6747. var DISTS = 2;
  6748. var lbase = [ /* Length codes 257..285 base */
  6749. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  6750. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  6751. ];
  6752. var lext = [ /* Length codes 257..285 extra */
  6753. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  6754. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  6755. ];
  6756. var dbase = [ /* Distance codes 0..29 base */
  6757. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  6758. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  6759. 8193, 12289, 16385, 24577, 0, 0
  6760. ];
  6761. var dext = [ /* Distance codes 0..29 extra */
  6762. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  6763. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  6764. 28, 28, 29, 29, 64, 64
  6765. ];
  6766. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  6767. {
  6768. var bits = opts.bits;
  6769. //here = opts.here; /* table entry for duplication */
  6770. var len = 0; /* a code's length in bits */
  6771. var sym = 0; /* index of code symbols */
  6772. var min = 0, max = 0; /* minimum and maximum code lengths */
  6773. var root = 0; /* number of index bits for root table */
  6774. var curr = 0; /* number of index bits for current table */
  6775. var drop = 0; /* code bits to drop for sub-table */
  6776. var left = 0; /* number of prefix codes available */
  6777. var used = 0; /* code entries in table used */
  6778. var huff = 0; /* Huffman code */
  6779. var incr; /* for incrementing code, index */
  6780. var fill; /* index for replicating entries */
  6781. var low; /* low bits for current root entry */
  6782. var mask; /* mask for low root bits */
  6783. var next; /* next available space in table */
  6784. var base = null; /* base value table to use */
  6785. var base_index = 0;
  6786. // var shoextra; /* extra bits table to use */
  6787. var end; /* use base and extra for symbol > end */
  6788. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  6789. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  6790. var extra = null;
  6791. var extra_index = 0;
  6792. var here_bits, here_op, here_val;
  6793. /*
  6794. Process a set of code lengths to create a canonical Huffman code. The
  6795. code lengths are lens[0..codes-1]. Each length corresponds to the
  6796. symbols 0..codes-1. The Huffman code is generated by first sorting the
  6797. symbols by length from short to long, and retaining the symbol order
  6798. for codes with equal lengths. Then the code starts with all zero bits
  6799. for the first code of the shortest length, and the codes are integer
  6800. increments for the same length, and zeros are appended as the length
  6801. increases. For the deflate format, these bits are stored backwards
  6802. from their more natural integer increment ordering, and so when the
  6803. decoding tables are built in the large loop below, the integer codes
  6804. are incremented backwards.
  6805. This routine assumes, but does not check, that all of the entries in
  6806. lens[] are in the range 0..MAXBITS. The caller must assure this.
  6807. 1..MAXBITS is interpreted as that code length. zero means that that
  6808. symbol does not occur in this code.
  6809. The codes are sorted by computing a count of codes for each length,
  6810. creating from that a table of starting indices for each length in the
  6811. sorted table, and then entering the symbols in order in the sorted
  6812. table. The sorted table is work[], with that space being provided by
  6813. the caller.
  6814. The length counts are used for other purposes as well, i.e. finding
  6815. the minimum and maximum length codes, determining if there are any
  6816. codes at all, checking for a valid set of lengths, and looking ahead
  6817. at length counts to determine sub-table sizes when building the
  6818. decoding tables.
  6819. */
  6820. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  6821. for (len = 0; len <= MAXBITS; len++) {
  6822. count[len] = 0;
  6823. }
  6824. for (sym = 0; sym < codes; sym++) {
  6825. count[lens[lens_index + sym]]++;
  6826. }
  6827. /* bound code lengths, force root to be within code lengths */
  6828. root = bits;
  6829. for (max = MAXBITS; max >= 1; max--) {
  6830. if (count[max] !== 0) { break; }
  6831. }
  6832. if (root > max) {
  6833. root = max;
  6834. }
  6835. if (max === 0) { /* no symbols to code at all */
  6836. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  6837. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  6838. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  6839. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  6840. //table.op[opts.table_index] = 64;
  6841. //table.bits[opts.table_index] = 1;
  6842. //table.val[opts.table_index++] = 0;
  6843. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  6844. opts.bits = 1;
  6845. return 0; /* no symbols, but wait for decoding to report error */
  6846. }
  6847. for (min = 1; min < max; min++) {
  6848. if (count[min] !== 0) { break; }
  6849. }
  6850. if (root < min) {
  6851. root = min;
  6852. }
  6853. /* check for an over-subscribed or incomplete set of lengths */
  6854. left = 1;
  6855. for (len = 1; len <= MAXBITS; len++) {
  6856. left <<= 1;
  6857. left -= count[len];
  6858. if (left < 0) {
  6859. return -1;
  6860. } /* over-subscribed */
  6861. }
  6862. if (left > 0 && (type === CODES || max !== 1)) {
  6863. return -1; /* incomplete set */
  6864. }
  6865. /* generate offsets into symbol table for each length for sorting */
  6866. offs[1] = 0;
  6867. for (len = 1; len < MAXBITS; len++) {
  6868. offs[len + 1] = offs[len] + count[len];
  6869. }
  6870. /* sort symbols by length, by symbol order within each length */
  6871. for (sym = 0; sym < codes; sym++) {
  6872. if (lens[lens_index + sym] !== 0) {
  6873. work[offs[lens[lens_index + sym]]++] = sym;
  6874. }
  6875. }
  6876. /*
  6877. Create and fill in decoding tables. In this loop, the table being
  6878. filled is at next and has curr index bits. The code being used is huff
  6879. with length len. That code is converted to an index by dropping drop
  6880. bits off of the bottom. For codes where len is less than drop + curr,
  6881. those top drop + curr - len bits are incremented through all values to
  6882. fill the table with replicated entries.
  6883. root is the number of index bits for the root table. When len exceeds
  6884. root, sub-tables are created pointed to by the root entry with an index
  6885. of the low root bits of huff. This is saved in low to check for when a
  6886. new sub-table should be started. drop is zero when the root table is
  6887. being filled, and drop is root when sub-tables are being filled.
  6888. When a new sub-table is needed, it is necessary to look ahead in the
  6889. code lengths to determine what size sub-table is needed. The length
  6890. counts are used for this, and so count[] is decremented as codes are
  6891. entered in the tables.
  6892. used keeps track of how many table entries have been allocated from the
  6893. provided *table space. It is checked for LENS and DIST tables against
  6894. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  6895. the initial root table size constants. See the comments in inftrees.h
  6896. for more information.
  6897. sym increments through all symbols, and the loop terminates when
  6898. all codes of length max, i.e. all codes, have been processed. This
  6899. routine permits incomplete codes, so another loop after this one fills
  6900. in the rest of the decoding tables with invalid code markers.
  6901. */
  6902. /* set up for code type */
  6903. // poor man optimization - use if-else instead of switch,
  6904. // to avoid deopts in old v8
  6905. if (type === CODES) {
  6906. base = extra = work; /* dummy value--not used */
  6907. end = 19;
  6908. } else if (type === LENS) {
  6909. base = lbase;
  6910. base_index -= 257;
  6911. extra = lext;
  6912. extra_index -= 257;
  6913. end = 256;
  6914. } else { /* DISTS */
  6915. base = dbase;
  6916. extra = dext;
  6917. end = -1;
  6918. }
  6919. /* initialize opts for loop */
  6920. huff = 0; /* starting code */
  6921. sym = 0; /* starting code symbol */
  6922. len = min; /* starting code length */
  6923. next = table_index; /* current table to fill in */
  6924. curr = root; /* current table index bits */
  6925. drop = 0; /* current bits to drop from code for index */
  6926. low = -1; /* trigger new sub-table when len > root */
  6927. used = 1 << root; /* use root table entries */
  6928. mask = used - 1; /* mask for comparing low */
  6929. /* check available table space */
  6930. if ((type === LENS && used > ENOUGH_LENS) ||
  6931. (type === DISTS && used > ENOUGH_DISTS)) {
  6932. return 1;
  6933. }
  6934. var i=0;
  6935. /* process all codes and make table entries */
  6936. for (;;) {
  6937. i++;
  6938. /* create table entry */
  6939. here_bits = len - drop;
  6940. if (work[sym] < end) {
  6941. here_op = 0;
  6942. here_val = work[sym];
  6943. }
  6944. else if (work[sym] > end) {
  6945. here_op = extra[extra_index + work[sym]];
  6946. here_val = base[base_index + work[sym]];
  6947. }
  6948. else {
  6949. here_op = 32 + 64; /* end of block */
  6950. here_val = 0;
  6951. }
  6952. /* replicate for those indices with low len bits equal to huff */
  6953. incr = 1 << (len - drop);
  6954. fill = 1 << curr;
  6955. min = fill; /* save offset to next table */
  6956. do {
  6957. fill -= incr;
  6958. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  6959. } while (fill !== 0);
  6960. /* backwards increment the len-bit code huff */
  6961. incr = 1 << (len - 1);
  6962. while (huff & incr) {
  6963. incr >>= 1;
  6964. }
  6965. if (incr !== 0) {
  6966. huff &= incr - 1;
  6967. huff += incr;
  6968. } else {
  6969. huff = 0;
  6970. }
  6971. /* go to next symbol, update count, len */
  6972. sym++;
  6973. if (--count[len] === 0) {
  6974. if (len === max) { break; }
  6975. len = lens[lens_index + work[sym]];
  6976. }
  6977. /* create new sub-table if needed */
  6978. if (len > root && (huff & mask) !== low) {
  6979. /* if first time, transition to sub-tables */
  6980. if (drop === 0) {
  6981. drop = root;
  6982. }
  6983. /* increment past last table */
  6984. next += min; /* here min is 1 << curr */
  6985. /* determine length of next table */
  6986. curr = len - drop;
  6987. left = 1 << curr;
  6988. while (curr + drop < max) {
  6989. left -= count[curr + drop];
  6990. if (left <= 0) { break; }
  6991. curr++;
  6992. left <<= 1;
  6993. }
  6994. /* check for enough space */
  6995. used += 1 << curr;
  6996. if ((type === LENS && used > ENOUGH_LENS) ||
  6997. (type === DISTS && used > ENOUGH_DISTS)) {
  6998. return 1;
  6999. }
  7000. /* point entry in root table to sub-table */
  7001. low = huff & mask;
  7002. /*table.op[low] = curr;
  7003. table.bits[low] = root;
  7004. table.val[low] = next - opts.table_index;*/
  7005. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  7006. }
  7007. }
  7008. /* fill in remaining table entry if code is incomplete (guaranteed to have
  7009. at most one remaining entry, since if the code is incomplete, the
  7010. maximum code length that was allowed to get this far is one bit) */
  7011. if (huff !== 0) {
  7012. //table.op[next + huff] = 64; /* invalid code marker */
  7013. //table.bits[next + huff] = len - drop;
  7014. //table.val[next + huff] = 0;
  7015. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  7016. }
  7017. /* set return parameters */
  7018. //opts.table_index += used;
  7019. opts.bits = root;
  7020. return 0;
  7021. };
  7022. },{"../utils/common":27}],37:[function(_dereq_,module,exports){
  7023. 'use strict';
  7024. module.exports = {
  7025. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  7026. '1': 'stream end', /* Z_STREAM_END 1 */
  7027. '0': '', /* Z_OK 0 */
  7028. '-1': 'file error', /* Z_ERRNO (-1) */
  7029. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  7030. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  7031. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  7032. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  7033. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  7034. };
  7035. },{}],38:[function(_dereq_,module,exports){
  7036. 'use strict';
  7037. var utils = _dereq_('../utils/common');
  7038. /* Public constants ==========================================================*/
  7039. /* ===========================================================================*/
  7040. //var Z_FILTERED = 1;
  7041. //var Z_HUFFMAN_ONLY = 2;
  7042. //var Z_RLE = 3;
  7043. var Z_FIXED = 4;
  7044. //var Z_DEFAULT_STRATEGY = 0;
  7045. /* Possible values of the data_type field (though see inflate()) */
  7046. var Z_BINARY = 0;
  7047. var Z_TEXT = 1;
  7048. //var Z_ASCII = 1; // = Z_TEXT
  7049. var Z_UNKNOWN = 2;
  7050. /*============================================================================*/
  7051. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  7052. // From zutil.h
  7053. var STORED_BLOCK = 0;
  7054. var STATIC_TREES = 1;
  7055. var DYN_TREES = 2;
  7056. /* The three kinds of block type */
  7057. var MIN_MATCH = 3;
  7058. var MAX_MATCH = 258;
  7059. /* The minimum and maximum match lengths */
  7060. // From deflate.h
  7061. /* ===========================================================================
  7062. * Internal compression state.
  7063. */
  7064. var LENGTH_CODES = 29;
  7065. /* number of length codes, not counting the special END_BLOCK code */
  7066. var LITERALS = 256;
  7067. /* number of literal bytes 0..255 */
  7068. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  7069. /* number of Literal or Length codes, including the END_BLOCK code */
  7070. var D_CODES = 30;
  7071. /* number of distance codes */
  7072. var BL_CODES = 19;
  7073. /* number of codes used to transfer the bit lengths */
  7074. var HEAP_SIZE = 2*L_CODES + 1;
  7075. /* maximum heap size */
  7076. var MAX_BITS = 15;
  7077. /* All codes must not exceed MAX_BITS bits */
  7078. var Buf_size = 16;
  7079. /* size of bit buffer in bi_buf */
  7080. /* ===========================================================================
  7081. * Constants
  7082. */
  7083. var MAX_BL_BITS = 7;
  7084. /* Bit length codes must not exceed MAX_BL_BITS bits */
  7085. var END_BLOCK = 256;
  7086. /* end of block literal code */
  7087. var REP_3_6 = 16;
  7088. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  7089. var REPZ_3_10 = 17;
  7090. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  7091. var REPZ_11_138 = 18;
  7092. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  7093. var extra_lbits = /* extra bits for each length code */
  7094. [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];
  7095. var extra_dbits = /* extra bits for each distance code */
  7096. [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];
  7097. var extra_blbits = /* extra bits for each bit length code */
  7098. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  7099. var bl_order =
  7100. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  7101. /* The lengths of the bit length codes are sent in order of decreasing
  7102. * probability, to avoid transmitting the lengths for unused bit length codes.
  7103. */
  7104. /* ===========================================================================
  7105. * Local data. These are initialized only once.
  7106. */
  7107. // We pre-fill arrays with 0 to avoid uninitialized gaps
  7108. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  7109. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  7110. var static_ltree = new Array((L_CODES+2) * 2);
  7111. zero(static_ltree);
  7112. /* The static literal tree. Since the bit lengths are imposed, there is no
  7113. * need for the L_CODES extra codes used during heap construction. However
  7114. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  7115. * below).
  7116. */
  7117. var static_dtree = new Array(D_CODES * 2);
  7118. zero(static_dtree);
  7119. /* The static distance tree. (Actually a trivial tree since all codes use
  7120. * 5 bits.)
  7121. */
  7122. var _dist_code = new Array(DIST_CODE_LEN);
  7123. zero(_dist_code);
  7124. /* Distance codes. The first 256 values correspond to the distances
  7125. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  7126. * the 15 bit distances.
  7127. */
  7128. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  7129. zero(_length_code);
  7130. /* length code for each normalized match length (0 == MIN_MATCH) */
  7131. var base_length = new Array(LENGTH_CODES);
  7132. zero(base_length);
  7133. /* First normalized length for each code (0 = MIN_MATCH) */
  7134. var base_dist = new Array(D_CODES);
  7135. zero(base_dist);
  7136. /* First normalized distance for each code (0 = distance of 1) */
  7137. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  7138. this.static_tree = static_tree; /* static tree or NULL */
  7139. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  7140. this.extra_base = extra_base; /* base index for extra_bits */
  7141. this.elems = elems; /* max number of elements in the tree */
  7142. this.max_length = max_length; /* max bit length for the codes */
  7143. // show if `static_tree` has data or dummy - needed for monomorphic objects
  7144. this.has_stree = static_tree && static_tree.length;
  7145. };
  7146. var static_l_desc;
  7147. var static_d_desc;
  7148. var static_bl_desc;
  7149. var TreeDesc = function(dyn_tree, stat_desc) {
  7150. this.dyn_tree = dyn_tree; /* the dynamic tree */
  7151. this.max_code = 0; /* largest code with non zero frequency */
  7152. this.stat_desc = stat_desc; /* the corresponding static tree */
  7153. };
  7154. function d_code(dist) {
  7155. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  7156. }
  7157. /* ===========================================================================
  7158. * Output a short LSB first on the stream.
  7159. * IN assertion: there is enough room in pendingBuf.
  7160. */
  7161. function put_short (s, w) {
  7162. // put_byte(s, (uch)((w) & 0xff));
  7163. // put_byte(s, (uch)((ush)(w) >> 8));
  7164. s.pending_buf[s.pending++] = (w) & 0xff;
  7165. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  7166. }
  7167. /* ===========================================================================
  7168. * Send a value on a given number of bits.
  7169. * IN assertion: length <= 16 and value fits in length bits.
  7170. */
  7171. function send_bits(s, value, length) {
  7172. if (s.bi_valid > (Buf_size - length)) {
  7173. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  7174. put_short(s, s.bi_buf);
  7175. s.bi_buf = value >> (Buf_size - s.bi_valid);
  7176. s.bi_valid += length - Buf_size;
  7177. } else {
  7178. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  7179. s.bi_valid += length;
  7180. }
  7181. }
  7182. function send_code(s, c, tree) {
  7183. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  7184. }
  7185. /* ===========================================================================
  7186. * Reverse the first len bits of a code, using straightforward code (a faster
  7187. * method would use a table)
  7188. * IN assertion: 1 <= len <= 15
  7189. */
  7190. function bi_reverse(code, len) {
  7191. var res = 0;
  7192. do {
  7193. res |= code & 1;
  7194. code >>>= 1;
  7195. res <<= 1;
  7196. } while (--len > 0);
  7197. return res >>> 1;
  7198. }
  7199. /* ===========================================================================
  7200. * Flush the bit buffer, keeping at most 7 bits in it.
  7201. */
  7202. function bi_flush(s) {
  7203. if (s.bi_valid === 16) {
  7204. put_short(s, s.bi_buf);
  7205. s.bi_buf = 0;
  7206. s.bi_valid = 0;
  7207. } else if (s.bi_valid >= 8) {
  7208. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  7209. s.bi_buf >>= 8;
  7210. s.bi_valid -= 8;
  7211. }
  7212. }
  7213. /* ===========================================================================
  7214. * Compute the optimal bit lengths for a tree and update the total bit length
  7215. * for the current block.
  7216. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  7217. * above are the tree nodes sorted by increasing frequency.
  7218. * OUT assertions: the field len is set to the optimal bit length, the
  7219. * array bl_count contains the frequencies for each bit length.
  7220. * The length opt_len is updated; static_len is also updated if stree is
  7221. * not null.
  7222. */
  7223. function gen_bitlen(s, desc)
  7224. // deflate_state *s;
  7225. // tree_desc *desc; /* the tree descriptor */
  7226. {
  7227. var tree = desc.dyn_tree;
  7228. var max_code = desc.max_code;
  7229. var stree = desc.stat_desc.static_tree;
  7230. var has_stree = desc.stat_desc.has_stree;
  7231. var extra = desc.stat_desc.extra_bits;
  7232. var base = desc.stat_desc.extra_base;
  7233. var max_length = desc.stat_desc.max_length;
  7234. var h; /* heap index */
  7235. var n, m; /* iterate over the tree elements */
  7236. var bits; /* bit length */
  7237. var xbits; /* extra bits */
  7238. var f; /* frequency */
  7239. var overflow = 0; /* number of elements with bit length too large */
  7240. for (bits = 0; bits <= MAX_BITS; bits++) {
  7241. s.bl_count[bits] = 0;
  7242. }
  7243. /* In a first pass, compute the optimal bit lengths (which may
  7244. * overflow in the case of the bit length tree).
  7245. */
  7246. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  7247. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  7248. n = s.heap[h];
  7249. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  7250. if (bits > max_length) {
  7251. bits = max_length;
  7252. overflow++;
  7253. }
  7254. tree[n*2 + 1]/*.Len*/ = bits;
  7255. /* We overwrite tree[n].Dad which is no longer needed */
  7256. if (n > max_code) { continue; } /* not a leaf node */
  7257. s.bl_count[bits]++;
  7258. xbits = 0;
  7259. if (n >= base) {
  7260. xbits = extra[n-base];
  7261. }
  7262. f = tree[n * 2]/*.Freq*/;
  7263. s.opt_len += f * (bits + xbits);
  7264. if (has_stree) {
  7265. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  7266. }
  7267. }
  7268. if (overflow === 0) { return; }
  7269. // Trace((stderr,"\nbit length overflow\n"));
  7270. /* This happens for example on obj2 and pic of the Calgary corpus */
  7271. /* Find the first bit length which could increase: */
  7272. do {
  7273. bits = max_length-1;
  7274. while (s.bl_count[bits] === 0) { bits--; }
  7275. s.bl_count[bits]--; /* move one leaf down the tree */
  7276. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  7277. s.bl_count[max_length]--;
  7278. /* The brother of the overflow item also moves one step up,
  7279. * but this does not affect bl_count[max_length]
  7280. */
  7281. overflow -= 2;
  7282. } while (overflow > 0);
  7283. /* Now recompute all bit lengths, scanning in increasing frequency.
  7284. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  7285. * lengths instead of fixing only the wrong ones. This idea is taken
  7286. * from 'ar' written by Haruhiko Okumura.)
  7287. */
  7288. for (bits = max_length; bits !== 0; bits--) {
  7289. n = s.bl_count[bits];
  7290. while (n !== 0) {
  7291. m = s.heap[--h];
  7292. if (m > max_code) { continue; }
  7293. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  7294. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  7295. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  7296. tree[m*2 + 1]/*.Len*/ = bits;
  7297. }
  7298. n--;
  7299. }
  7300. }
  7301. }
  7302. /* ===========================================================================
  7303. * Generate the codes for a given tree and bit counts (which need not be
  7304. * optimal).
  7305. * IN assertion: the array bl_count contains the bit length statistics for
  7306. * the given tree and the field len is set for all tree elements.
  7307. * OUT assertion: the field code is set for all tree elements of non
  7308. * zero code length.
  7309. */
  7310. function gen_codes(tree, max_code, bl_count)
  7311. // ct_data *tree; /* the tree to decorate */
  7312. // int max_code; /* largest code with non zero frequency */
  7313. // ushf *bl_count; /* number of codes at each bit length */
  7314. {
  7315. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  7316. var code = 0; /* running code value */
  7317. var bits; /* bit index */
  7318. var n; /* code index */
  7319. /* The distribution counts are first used to generate the code values
  7320. * without bit reversal.
  7321. */
  7322. for (bits = 1; bits <= MAX_BITS; bits++) {
  7323. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  7324. }
  7325. /* Check that the bit counts in bl_count are consistent. The last code
  7326. * must be all ones.
  7327. */
  7328. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  7329. // "inconsistent bit counts");
  7330. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  7331. for (n = 0; n <= max_code; n++) {
  7332. var len = tree[n*2 + 1]/*.Len*/;
  7333. if (len === 0) { continue; }
  7334. /* Now reverse the bits */
  7335. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  7336. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  7337. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  7338. }
  7339. }
  7340. /* ===========================================================================
  7341. * Initialize the various 'constant' tables.
  7342. */
  7343. function tr_static_init() {
  7344. var n; /* iterates over tree elements */
  7345. var bits; /* bit counter */
  7346. var length; /* length value */
  7347. var code; /* code value */
  7348. var dist; /* distance index */
  7349. var bl_count = new Array(MAX_BITS+1);
  7350. /* number of codes at each bit length for an optimal tree */
  7351. // do check in _tr_init()
  7352. //if (static_init_done) return;
  7353. /* For some embedded targets, global variables are not initialized: */
  7354. /*#ifdef NO_INIT_GLOBAL_POINTERS
  7355. static_l_desc.static_tree = static_ltree;
  7356. static_l_desc.extra_bits = extra_lbits;
  7357. static_d_desc.static_tree = static_dtree;
  7358. static_d_desc.extra_bits = extra_dbits;
  7359. static_bl_desc.extra_bits = extra_blbits;
  7360. #endif*/
  7361. /* Initialize the mapping length (0..255) -> length code (0..28) */
  7362. length = 0;
  7363. for (code = 0; code < LENGTH_CODES-1; code++) {
  7364. base_length[code] = length;
  7365. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  7366. _length_code[length++] = code;
  7367. }
  7368. }
  7369. //Assert (length == 256, "tr_static_init: length != 256");
  7370. /* Note that the length 255 (match length 258) can be represented
  7371. * in two different ways: code 284 + 5 bits or code 285, so we
  7372. * overwrite length_code[255] to use the best encoding:
  7373. */
  7374. _length_code[length-1] = code;
  7375. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  7376. dist = 0;
  7377. for (code = 0 ; code < 16; code++) {
  7378. base_dist[code] = dist;
  7379. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  7380. _dist_code[dist++] = code;
  7381. }
  7382. }
  7383. //Assert (dist == 256, "tr_static_init: dist != 256");
  7384. dist >>= 7; /* from now on, all distances are divided by 128 */
  7385. for ( ; code < D_CODES; code++) {
  7386. base_dist[code] = dist << 7;
  7387. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  7388. _dist_code[256 + dist++] = code;
  7389. }
  7390. }
  7391. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  7392. /* Construct the codes of the static literal tree */
  7393. for (bits = 0; bits <= MAX_BITS; bits++) {
  7394. bl_count[bits] = 0;
  7395. }
  7396. n = 0;
  7397. while (n <= 143) {
  7398. static_ltree[n*2 + 1]/*.Len*/ = 8;
  7399. n++;
  7400. bl_count[8]++;
  7401. }
  7402. while (n <= 255) {
  7403. static_ltree[n*2 + 1]/*.Len*/ = 9;
  7404. n++;
  7405. bl_count[9]++;
  7406. }
  7407. while (n <= 279) {
  7408. static_ltree[n*2 + 1]/*.Len*/ = 7;
  7409. n++;
  7410. bl_count[7]++;
  7411. }
  7412. while (n <= 287) {
  7413. static_ltree[n*2 + 1]/*.Len*/ = 8;
  7414. n++;
  7415. bl_count[8]++;
  7416. }
  7417. /* Codes 286 and 287 do not exist, but we must include them in the
  7418. * tree construction to get a canonical Huffman tree (longest code
  7419. * all ones)
  7420. */
  7421. gen_codes(static_ltree, L_CODES+1, bl_count);
  7422. /* The static distance tree is trivial: */
  7423. for (n = 0; n < D_CODES; n++) {
  7424. static_dtree[n*2 + 1]/*.Len*/ = 5;
  7425. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  7426. }
  7427. // Now data ready and we can init static trees
  7428. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  7429. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  7430. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  7431. //static_init_done = true;
  7432. }
  7433. /* ===========================================================================
  7434. * Initialize a new block.
  7435. */
  7436. function init_block(s) {
  7437. var n; /* iterates over tree elements */
  7438. /* Initialize the trees. */
  7439. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  7440. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  7441. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  7442. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  7443. s.opt_len = s.static_len = 0;
  7444. s.last_lit = s.matches = 0;
  7445. }
  7446. /* ===========================================================================
  7447. * Flush the bit buffer and align the output on a byte boundary
  7448. */
  7449. function bi_windup(s)
  7450. {
  7451. if (s.bi_valid > 8) {
  7452. put_short(s, s.bi_buf);
  7453. } else if (s.bi_valid > 0) {
  7454. //put_byte(s, (Byte)s->bi_buf);
  7455. s.pending_buf[s.pending++] = s.bi_buf;
  7456. }
  7457. s.bi_buf = 0;
  7458. s.bi_valid = 0;
  7459. }
  7460. /* ===========================================================================
  7461. * Copy a stored block, storing first the length and its
  7462. * one's complement if requested.
  7463. */
  7464. function copy_block(s, buf, len, header)
  7465. //DeflateState *s;
  7466. //charf *buf; /* the input data */
  7467. //unsigned len; /* its length */
  7468. //int header; /* true if block header must be written */
  7469. {
  7470. bi_windup(s); /* align on byte boundary */
  7471. if (header) {
  7472. put_short(s, len);
  7473. put_short(s, ~len);
  7474. }
  7475. // while (len--) {
  7476. // put_byte(s, *buf++);
  7477. // }
  7478. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  7479. s.pending += len;
  7480. }
  7481. /* ===========================================================================
  7482. * Compares to subtrees, using the tree depth as tie breaker when
  7483. * the subtrees have equal frequency. This minimizes the worst case length.
  7484. */
  7485. function smaller(tree, n, m, depth) {
  7486. var _n2 = n*2;
  7487. var _m2 = m*2;
  7488. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  7489. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  7490. }
  7491. /* ===========================================================================
  7492. * Restore the heap property by moving down the tree starting at node k,
  7493. * exchanging a node with the smallest of its two sons if necessary, stopping
  7494. * when the heap property is re-established (each father smaller than its
  7495. * two sons).
  7496. */
  7497. function pqdownheap(s, tree, k)
  7498. // deflate_state *s;
  7499. // ct_data *tree; /* the tree to restore */
  7500. // int k; /* node to move down */
  7501. {
  7502. var v = s.heap[k];
  7503. var j = k << 1; /* left son of k */
  7504. while (j <= s.heap_len) {
  7505. /* Set j to the smallest of the two sons: */
  7506. if (j < s.heap_len &&
  7507. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  7508. j++;
  7509. }
  7510. /* Exit if v is smaller than both sons */
  7511. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  7512. /* Exchange v with the smallest son */
  7513. s.heap[k] = s.heap[j];
  7514. k = j;
  7515. /* And continue down the tree, setting j to the left son of k */
  7516. j <<= 1;
  7517. }
  7518. s.heap[k] = v;
  7519. }
  7520. // inlined manually
  7521. // var SMALLEST = 1;
  7522. /* ===========================================================================
  7523. * Send the block data compressed using the given Huffman trees
  7524. */
  7525. function compress_block(s, ltree, dtree)
  7526. // deflate_state *s;
  7527. // const ct_data *ltree; /* literal tree */
  7528. // const ct_data *dtree; /* distance tree */
  7529. {
  7530. var dist; /* distance of matched string */
  7531. var lc; /* match length or unmatched char (if dist == 0) */
  7532. var lx = 0; /* running index in l_buf */
  7533. var code; /* the code to send */
  7534. var extra; /* number of extra bits to send */
  7535. if (s.last_lit !== 0) {
  7536. do {
  7537. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  7538. lc = s.pending_buf[s.l_buf + lx];
  7539. lx++;
  7540. if (dist === 0) {
  7541. send_code(s, lc, ltree); /* send a literal byte */
  7542. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  7543. } else {
  7544. /* Here, lc is the match length - MIN_MATCH */
  7545. code = _length_code[lc];
  7546. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  7547. extra = extra_lbits[code];
  7548. if (extra !== 0) {
  7549. lc -= base_length[code];
  7550. send_bits(s, lc, extra); /* send the extra length bits */
  7551. }
  7552. dist--; /* dist is now the match distance - 1 */
  7553. code = d_code(dist);
  7554. //Assert (code < D_CODES, "bad d_code");
  7555. send_code(s, code, dtree); /* send the distance code */
  7556. extra = extra_dbits[code];
  7557. if (extra !== 0) {
  7558. dist -= base_dist[code];
  7559. send_bits(s, dist, extra); /* send the extra distance bits */
  7560. }
  7561. } /* literal or match pair ? */
  7562. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  7563. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  7564. // "pendingBuf overflow");
  7565. } while (lx < s.last_lit);
  7566. }
  7567. send_code(s, END_BLOCK, ltree);
  7568. }
  7569. /* ===========================================================================
  7570. * Construct one Huffman tree and assigns the code bit strings and lengths.
  7571. * Update the total bit length for the current block.
  7572. * IN assertion: the field freq is set for all tree elements.
  7573. * OUT assertions: the fields len and code are set to the optimal bit length
  7574. * and corresponding code. The length opt_len is updated; static_len is
  7575. * also updated if stree is not null. The field max_code is set.
  7576. */
  7577. function build_tree(s, desc)
  7578. // deflate_state *s;
  7579. // tree_desc *desc; /* the tree descriptor */
  7580. {
  7581. var tree = desc.dyn_tree;
  7582. var stree = desc.stat_desc.static_tree;
  7583. var has_stree = desc.stat_desc.has_stree;
  7584. var elems = desc.stat_desc.elems;
  7585. var n, m; /* iterate over heap elements */
  7586. var max_code = -1; /* largest code with non zero frequency */
  7587. var node; /* new node being created */
  7588. /* Construct the initial heap, with least frequent element in
  7589. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  7590. * heap[0] is not used.
  7591. */
  7592. s.heap_len = 0;
  7593. s.heap_max = HEAP_SIZE;
  7594. for (n = 0; n < elems; n++) {
  7595. if (tree[n * 2]/*.Freq*/ !== 0) {
  7596. s.heap[++s.heap_len] = max_code = n;
  7597. s.depth[n] = 0;
  7598. } else {
  7599. tree[n*2 + 1]/*.Len*/ = 0;
  7600. }
  7601. }
  7602. /* The pkzip format requires that at least one distance code exists,
  7603. * and that at least one bit should be sent even if there is only one
  7604. * possible code. So to avoid special checks later on we force at least
  7605. * two codes of non zero frequency.
  7606. */
  7607. while (s.heap_len < 2) {
  7608. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  7609. tree[node * 2]/*.Freq*/ = 1;
  7610. s.depth[node] = 0;
  7611. s.opt_len--;
  7612. if (has_stree) {
  7613. s.static_len -= stree[node*2 + 1]/*.Len*/;
  7614. }
  7615. /* node is 0 or 1 so it does not have extra bits */
  7616. }
  7617. desc.max_code = max_code;
  7618. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  7619. * establish sub-heaps of increasing lengths:
  7620. */
  7621. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  7622. /* Construct the Huffman tree by repeatedly combining the least two
  7623. * frequent nodes.
  7624. */
  7625. node = elems; /* next internal node of the tree */
  7626. do {
  7627. //pqremove(s, tree, n); /* n = node of least frequency */
  7628. /*** pqremove ***/
  7629. n = s.heap[1/*SMALLEST*/];
  7630. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  7631. pqdownheap(s, tree, 1/*SMALLEST*/);
  7632. /***/
  7633. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  7634. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  7635. s.heap[--s.heap_max] = m;
  7636. /* Create a new node father of n and m */
  7637. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  7638. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  7639. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  7640. /* and insert the new node in the heap */
  7641. s.heap[1/*SMALLEST*/] = node++;
  7642. pqdownheap(s, tree, 1/*SMALLEST*/);
  7643. } while (s.heap_len >= 2);
  7644. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  7645. /* At this point, the fields freq and dad are set. We can now
  7646. * generate the bit lengths.
  7647. */
  7648. gen_bitlen(s, desc);
  7649. /* The field len is now set, we can generate the bit codes */
  7650. gen_codes(tree, max_code, s.bl_count);
  7651. }
  7652. /* ===========================================================================
  7653. * Scan a literal or distance tree to determine the frequencies of the codes
  7654. * in the bit length tree.
  7655. */
  7656. function scan_tree(s, tree, max_code)
  7657. // deflate_state *s;
  7658. // ct_data *tree; /* the tree to be scanned */
  7659. // int max_code; /* and its largest code of non zero frequency */
  7660. {
  7661. var n; /* iterates over all tree elements */
  7662. var prevlen = -1; /* last emitted length */
  7663. var curlen; /* length of current code */
  7664. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  7665. var count = 0; /* repeat count of the current code */
  7666. var max_count = 7; /* max repeat count */
  7667. var min_count = 4; /* min repeat count */
  7668. if (nextlen === 0) {
  7669. max_count = 138;
  7670. min_count = 3;
  7671. }
  7672. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  7673. for (n = 0; n <= max_code; n++) {
  7674. curlen = nextlen;
  7675. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  7676. if (++count < max_count && curlen === nextlen) {
  7677. continue;
  7678. } else if (count < min_count) {
  7679. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  7680. } else if (curlen !== 0) {
  7681. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  7682. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  7683. } else if (count <= 10) {
  7684. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  7685. } else {
  7686. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  7687. }
  7688. count = 0;
  7689. prevlen = curlen;
  7690. if (nextlen === 0) {
  7691. max_count = 138;
  7692. min_count = 3;
  7693. } else if (curlen === nextlen) {
  7694. max_count = 6;
  7695. min_count = 3;
  7696. } else {
  7697. max_count = 7;
  7698. min_count = 4;
  7699. }
  7700. }
  7701. }
  7702. /* ===========================================================================
  7703. * Send a literal or distance tree in compressed form, using the codes in
  7704. * bl_tree.
  7705. */
  7706. function send_tree(s, tree, max_code)
  7707. // deflate_state *s;
  7708. // ct_data *tree; /* the tree to be scanned */
  7709. // int max_code; /* and its largest code of non zero frequency */
  7710. {
  7711. var n; /* iterates over all tree elements */
  7712. var prevlen = -1; /* last emitted length */
  7713. var curlen; /* length of current code */
  7714. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  7715. var count = 0; /* repeat count of the current code */
  7716. var max_count = 7; /* max repeat count */
  7717. var min_count = 4; /* min repeat count */
  7718. /* tree[max_code+1].Len = -1; */ /* guard already set */
  7719. if (nextlen === 0) {
  7720. max_count = 138;
  7721. min_count = 3;
  7722. }
  7723. for (n = 0; n <= max_code; n++) {
  7724. curlen = nextlen;
  7725. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  7726. if (++count < max_count && curlen === nextlen) {
  7727. continue;
  7728. } else if (count < min_count) {
  7729. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  7730. } else if (curlen !== 0) {
  7731. if (curlen !== prevlen) {
  7732. send_code(s, curlen, s.bl_tree);
  7733. count--;
  7734. }
  7735. //Assert(count >= 3 && count <= 6, " 3_6?");
  7736. send_code(s, REP_3_6, s.bl_tree);
  7737. send_bits(s, count-3, 2);
  7738. } else if (count <= 10) {
  7739. send_code(s, REPZ_3_10, s.bl_tree);
  7740. send_bits(s, count-3, 3);
  7741. } else {
  7742. send_code(s, REPZ_11_138, s.bl_tree);
  7743. send_bits(s, count-11, 7);
  7744. }
  7745. count = 0;
  7746. prevlen = curlen;
  7747. if (nextlen === 0) {
  7748. max_count = 138;
  7749. min_count = 3;
  7750. } else if (curlen === nextlen) {
  7751. max_count = 6;
  7752. min_count = 3;
  7753. } else {
  7754. max_count = 7;
  7755. min_count = 4;
  7756. }
  7757. }
  7758. }
  7759. /* ===========================================================================
  7760. * Construct the Huffman tree for the bit lengths and return the index in
  7761. * bl_order of the last bit length code to send.
  7762. */
  7763. function build_bl_tree(s) {
  7764. var max_blindex; /* index of last bit length code of non zero freq */
  7765. /* Determine the bit length frequencies for literal and distance trees */
  7766. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  7767. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  7768. /* Build the bit length tree: */
  7769. build_tree(s, s.bl_desc);
  7770. /* opt_len now includes the length of the tree representations, except
  7771. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  7772. */
  7773. /* Determine the number of bit length codes to send. The pkzip format
  7774. * requires that at least 4 bit length codes be sent. (appnote.txt says
  7775. * 3 but the actual value used is 4.)
  7776. */
  7777. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  7778. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  7779. break;
  7780. }
  7781. }
  7782. /* Update opt_len to include the bit length tree and counts */
  7783. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  7784. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  7785. // s->opt_len, s->static_len));
  7786. return max_blindex;
  7787. }
  7788. /* ===========================================================================
  7789. * Send the header for a block using dynamic Huffman trees: the counts, the
  7790. * lengths of the bit length codes, the literal tree and the distance tree.
  7791. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  7792. */
  7793. function send_all_trees(s, lcodes, dcodes, blcodes)
  7794. // deflate_state *s;
  7795. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  7796. {
  7797. var rank; /* index in bl_order */
  7798. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  7799. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  7800. // "too many codes");
  7801. //Tracev((stderr, "\nbl counts: "));
  7802. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  7803. send_bits(s, dcodes-1, 5);
  7804. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  7805. for (rank = 0; rank < blcodes; rank++) {
  7806. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  7807. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  7808. }
  7809. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  7810. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  7811. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  7812. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  7813. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  7814. }
  7815. /* ===========================================================================
  7816. * Check if the data type is TEXT or BINARY, using the following algorithm:
  7817. * - TEXT if the two conditions below are satisfied:
  7818. * a) There are no non-portable control characters belonging to the
  7819. * "black list" (0..6, 14..25, 28..31).
  7820. * b) There is at least one printable character belonging to the
  7821. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  7822. * - BINARY otherwise.
  7823. * - The following partially-portable control characters form a
  7824. * "gray list" that is ignored in this detection algorithm:
  7825. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  7826. * IN assertion: the fields Freq of dyn_ltree are set.
  7827. */
  7828. function detect_data_type(s) {
  7829. /* black_mask is the bit mask of black-listed bytes
  7830. * set bits 0..6, 14..25, and 28..31
  7831. * 0xf3ffc07f = binary 11110011111111111100000001111111
  7832. */
  7833. var black_mask = 0xf3ffc07f;
  7834. var n;
  7835. /* Check for non-textual ("black-listed") bytes. */
  7836. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  7837. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  7838. return Z_BINARY;
  7839. }
  7840. }
  7841. /* Check for textual ("white-listed") bytes. */
  7842. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  7843. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  7844. return Z_TEXT;
  7845. }
  7846. for (n = 32; n < LITERALS; n++) {
  7847. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  7848. return Z_TEXT;
  7849. }
  7850. }
  7851. /* There are no "black-listed" or "white-listed" bytes:
  7852. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  7853. */
  7854. return Z_BINARY;
  7855. }
  7856. var static_init_done = false;
  7857. /* ===========================================================================
  7858. * Initialize the tree data structures for a new zlib stream.
  7859. */
  7860. function _tr_init(s)
  7861. {
  7862. if (!static_init_done) {
  7863. tr_static_init();
  7864. static_init_done = true;
  7865. }
  7866. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  7867. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  7868. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  7869. s.bi_buf = 0;
  7870. s.bi_valid = 0;
  7871. /* Initialize the first block of the first file: */
  7872. init_block(s);
  7873. }
  7874. /* ===========================================================================
  7875. * Send a stored block
  7876. */
  7877. function _tr_stored_block(s, buf, stored_len, last)
  7878. //DeflateState *s;
  7879. //charf *buf; /* input block */
  7880. //ulg stored_len; /* length of input block */
  7881. //int last; /* one if this is the last block for a file */
  7882. {
  7883. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  7884. copy_block(s, buf, stored_len, true); /* with header */
  7885. }
  7886. /* ===========================================================================
  7887. * Send one empty static block to give enough lookahead for inflate.
  7888. * This takes 10 bits, of which 7 may remain in the bit buffer.
  7889. */
  7890. function _tr_align(s) {
  7891. send_bits(s, STATIC_TREES<<1, 3);
  7892. send_code(s, END_BLOCK, static_ltree);
  7893. bi_flush(s);
  7894. }
  7895. /* ===========================================================================
  7896. * Determine the best encoding for the current block: dynamic trees, static
  7897. * trees or store, and output the encoded block to the zip file.
  7898. */
  7899. function _tr_flush_block(s, buf, stored_len, last)
  7900. //DeflateState *s;
  7901. //charf *buf; /* input block, or NULL if too old */
  7902. //ulg stored_len; /* length of input block */
  7903. //int last; /* one if this is the last block for a file */
  7904. {
  7905. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  7906. var max_blindex = 0; /* index of last bit length code of non zero freq */
  7907. /* Build the Huffman trees unless a stored block is forced */
  7908. if (s.level > 0) {
  7909. /* Check if the file is binary or text */
  7910. if (s.strm.data_type === Z_UNKNOWN) {
  7911. s.strm.data_type = detect_data_type(s);
  7912. }
  7913. /* Construct the literal and distance trees */
  7914. build_tree(s, s.l_desc);
  7915. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  7916. // s->static_len));
  7917. build_tree(s, s.d_desc);
  7918. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  7919. // s->static_len));
  7920. /* At this point, opt_len and static_len are the total bit lengths of
  7921. * the compressed block data, excluding the tree representations.
  7922. */
  7923. /* Build the bit length tree for the above two trees, and get the index
  7924. * in bl_order of the last bit length code to send.
  7925. */
  7926. max_blindex = build_bl_tree(s);
  7927. /* Determine the best encoding. Compute the block lengths in bytes. */
  7928. opt_lenb = (s.opt_len+3+7) >>> 3;
  7929. static_lenb = (s.static_len+3+7) >>> 3;
  7930. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  7931. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  7932. // s->last_lit));
  7933. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  7934. } else {
  7935. // Assert(buf != (char*)0, "lost buf");
  7936. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  7937. }
  7938. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  7939. /* 4: two words for the lengths */
  7940. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  7941. * Otherwise we can't have processed more than WSIZE input bytes since
  7942. * the last block flush, because compression would have been
  7943. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  7944. * transform a block into a stored block.
  7945. */
  7946. _tr_stored_block(s, buf, stored_len, last);
  7947. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  7948. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  7949. compress_block(s, static_ltree, static_dtree);
  7950. } else {
  7951. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  7952. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  7953. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  7954. }
  7955. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  7956. /* The above check is made mod 2^32, for files larger than 512 MB
  7957. * and uLong implemented on 32 bits.
  7958. */
  7959. init_block(s);
  7960. if (last) {
  7961. bi_windup(s);
  7962. }
  7963. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  7964. // s->compressed_len-7*last));
  7965. }
  7966. /* ===========================================================================
  7967. * Save the match info and tally the frequency counts. Return true if
  7968. * the current block must be flushed.
  7969. */
  7970. function _tr_tally(s, dist, lc)
  7971. // deflate_state *s;
  7972. // unsigned dist; /* distance of matched string */
  7973. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  7974. {
  7975. //var out_length, in_length, dcode;
  7976. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  7977. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  7978. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  7979. s.last_lit++;
  7980. if (dist === 0) {
  7981. /* lc is the unmatched char */
  7982. s.dyn_ltree[lc*2]/*.Freq*/++;
  7983. } else {
  7984. s.matches++;
  7985. /* Here, lc is the match length - MIN_MATCH */
  7986. dist--; /* dist = match distance - 1 */
  7987. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  7988. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  7989. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  7990. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  7991. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  7992. }
  7993. // (!) This block is disabled in zlib defailts,
  7994. // don't enable it for binary compatibility
  7995. //#ifdef TRUNCATE_BLOCK
  7996. // /* Try to guess if it is profitable to stop the current block here */
  7997. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  7998. // /* Compute an upper bound for the compressed length */
  7999. // out_length = s.last_lit*8;
  8000. // in_length = s.strstart - s.block_start;
  8001. //
  8002. // for (dcode = 0; dcode < D_CODES; dcode++) {
  8003. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  8004. // }
  8005. // out_length >>>= 3;
  8006. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  8007. // // s->last_lit, in_length, out_length,
  8008. // // 100L - out_length*100L/in_length));
  8009. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  8010. // return true;
  8011. // }
  8012. // }
  8013. //#endif
  8014. return (s.last_lit === s.lit_bufsize-1);
  8015. /* We avoid equality with lit_bufsize because of wraparound at 64K
  8016. * on 16 bit machines and because stored blocks are restricted to
  8017. * 64K-1 bytes.
  8018. */
  8019. }
  8020. exports._tr_init = _tr_init;
  8021. exports._tr_stored_block = _tr_stored_block;
  8022. exports._tr_flush_block = _tr_flush_block;
  8023. exports._tr_tally = _tr_tally;
  8024. exports._tr_align = _tr_align;
  8025. },{"../utils/common":27}],39:[function(_dereq_,module,exports){
  8026. 'use strict';
  8027. function ZStream() {
  8028. /* next input byte */
  8029. this.input = null; // JS specific, because we have no pointers
  8030. this.next_in = 0;
  8031. /* number of bytes available at input */
  8032. this.avail_in = 0;
  8033. /* total number of input bytes read so far */
  8034. this.total_in = 0;
  8035. /* next output byte should be put there */
  8036. this.output = null; // JS specific, because we have no pointers
  8037. this.next_out = 0;
  8038. /* remaining free space at output */
  8039. this.avail_out = 0;
  8040. /* total number of bytes output so far */
  8041. this.total_out = 0;
  8042. /* last error message, NULL if no error */
  8043. this.msg = ''/*Z_NULL*/;
  8044. /* not visible by applications */
  8045. this.state = null;
  8046. /* best guess about the data type: binary or text */
  8047. this.data_type = 2/*Z_UNKNOWN*/;
  8048. /* adler32 value of the uncompressed data */
  8049. this.adler = 0;
  8050. }
  8051. module.exports = ZStream;
  8052. },{}]},{},[9])
  8053. (9)
  8054. }));
  8055. /*! xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
  8056. /* vim: set ts=2: */
  8057. /*exported XLSX */
  8058. /*global global, exports, module, require:false, process:false, Buffer:false, ArrayBuffer:false */
  8059. var XLSX = {};
  8060. function make_xlsx_lib(XLSX){
  8061. XLSX.version = '0.16.9';
  8062. var current_codepage = 1200, current_ansi = 1252;
  8063. /*global cptable:true, window */
  8064. if(typeof module !== "undefined" && typeof require !== 'undefined') {
  8065. if(typeof cptable === 'undefined') {
  8066. if(typeof global !== 'undefined') global.cptable = undefined;
  8067. else if(typeof window !== 'undefined') window.cptable = undefined;
  8068. }
  8069. }
  8070. var VALID_ANSI = [ 874, 932, 936, 949, 950 ];
  8071. for(var i = 0; i <= 8; ++i) VALID_ANSI.push(1250 + i);
  8072. /* ECMA-376 Part I 18.4.1 charset to codepage mapping */
  8073. var CS2CP = ({
  8074. 0: 1252, /* ANSI */
  8075. 1: 65001, /* DEFAULT */
  8076. 2: 65001, /* SYMBOL */
  8077. 77: 10000, /* MAC */
  8078. 128: 932, /* SHIFTJIS */
  8079. 129: 949, /* HANGUL */
  8080. 130: 1361, /* JOHAB */
  8081. 134: 936, /* GB2312 */
  8082. 136: 950, /* CHINESEBIG5 */
  8083. 161: 1253, /* GREEK */
  8084. 162: 1254, /* TURKISH */
  8085. 163: 1258, /* VIETNAMESE */
  8086. 177: 1255, /* HEBREW */
  8087. 178: 1256, /* ARABIC */
  8088. 186: 1257, /* BALTIC */
  8089. 204: 1251, /* RUSSIAN */
  8090. 222: 874, /* THAI */
  8091. 238: 1250, /* EASTEUROPE */
  8092. 255: 1252, /* OEM */
  8093. 69: 6969 /* MISC */
  8094. });
  8095. var set_ansi = function(cp) { if(VALID_ANSI.indexOf(cp) == -1) return; current_ansi = CS2CP[0] = cp; };
  8096. function reset_ansi() { set_ansi(1252); }
  8097. var set_cp = function(cp) { current_codepage = cp; set_ansi(cp); };
  8098. function reset_cp() { set_cp(1200); reset_ansi(); }
  8099. function char_codes(data) { var o = []; for(var i = 0, len = data.length; i < len; ++i) o[i] = data.charCodeAt(i); return o; }
  8100. function utf16leread(data) {
  8101. var o = [];
  8102. for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i) + (data.charCodeAt(2*i+1)<<8));
  8103. return o.join("");
  8104. }
  8105. function utf16beread(data) {
  8106. var o = [];
  8107. for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i+1) + (data.charCodeAt(2*i)<<8));
  8108. return o.join("");
  8109. }
  8110. var debom = function(data) {
  8111. var c1 = data.charCodeAt(0), c2 = data.charCodeAt(1);
  8112. if(c1 == 0xFF && c2 == 0xFE) return utf16leread(data.slice(2));
  8113. if(c1 == 0xFE && c2 == 0xFF) return utf16beread(data.slice(2));
  8114. if(c1 == 0xFEFF) return data.slice(1);
  8115. return data;
  8116. };
  8117. var _getchar = function _gc1(x) { return String.fromCharCode(x); };
  8118. var _getansi = function _ga1(x) { return String.fromCharCode(x); };
  8119. if(typeof cptable !== 'undefined') {
  8120. set_cp = function(cp) { current_codepage = cp; set_ansi(cp); };
  8121. debom = function(data) {
  8122. if(data.charCodeAt(0) === 0xFF && data.charCodeAt(1) === 0xFE) { return cptable.utils.decode(1200, char_codes(data.slice(2))); }
  8123. return data;
  8124. };
  8125. _getchar = function _gc2(x) {
  8126. if(current_codepage === 1200) return String.fromCharCode(x);
  8127. return cptable.utils.decode(current_codepage, [x&255,x>>8])[0];
  8128. };
  8129. _getansi = function _ga2(x) {
  8130. return cptable.utils.decode(current_ansi, [x])[0];
  8131. };
  8132. }
  8133. var DENSE = null;
  8134. var DIF_XL = true;
  8135. var Base64 = (function make_b64(){
  8136. var map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8137. return {
  8138. encode: function(input) {
  8139. var o = "";
  8140. var c1=0, c2=0, c3=0, e1=0, e2=0, e3=0, e4=0;
  8141. for(var i = 0; i < input.length; ) {
  8142. c1 = input.charCodeAt(i++);
  8143. e1 = (c1 >> 2);
  8144. c2 = input.charCodeAt(i++);
  8145. e2 = ((c1 & 3) << 4) | (c2 >> 4);
  8146. c3 = input.charCodeAt(i++);
  8147. e3 = ((c2 & 15) << 2) | (c3 >> 6);
  8148. e4 = (c3 & 63);
  8149. if (isNaN(c2)) { e3 = e4 = 64; }
  8150. else if (isNaN(c3)) { e4 = 64; }
  8151. o += map.charAt(e1) + map.charAt(e2) + map.charAt(e3) + map.charAt(e4);
  8152. }
  8153. return o;
  8154. },
  8155. decode: function b64_decode(input) {
  8156. var o = "";
  8157. var c1=0, c2=0, c3=0, e1=0, e2=0, e3=0, e4=0;
  8158. input = input.replace(/[^\w\+\/\=]/g, "");
  8159. for(var i = 0; i < input.length;) {
  8160. e1 = map.indexOf(input.charAt(i++));
  8161. e2 = map.indexOf(input.charAt(i++));
  8162. c1 = (e1 << 2) | (e2 >> 4);
  8163. o += String.fromCharCode(c1);
  8164. e3 = map.indexOf(input.charAt(i++));
  8165. c2 = ((e2 & 15) << 4) | (e3 >> 2);
  8166. if (e3 !== 64) { o += String.fromCharCode(c2); }
  8167. e4 = map.indexOf(input.charAt(i++));
  8168. c3 = ((e3 & 3) << 6) | e4;
  8169. if (e4 !== 64) { o += String.fromCharCode(c3); }
  8170. }
  8171. return o;
  8172. }
  8173. };
  8174. })();
  8175. var has_buf = (typeof Buffer !== 'undefined' && typeof process !== 'undefined' && typeof process.versions !== 'undefined' && !!process.versions.node);
  8176. var Buffer_from = function(){};
  8177. if(typeof Buffer !== 'undefined') {
  8178. var nbfs = !Buffer.from;
  8179. if(!nbfs) try { Buffer.from("foo", "utf8"); } catch(e) { nbfs = true; }
  8180. Buffer_from = nbfs ? function(buf, enc) { return (enc) ? new Buffer(buf, enc) : new Buffer(buf); } : Buffer.from.bind(Buffer);
  8181. // $FlowIgnore
  8182. if(!Buffer.alloc) Buffer.alloc = function(n) { return new Buffer(n); };
  8183. // $FlowIgnore
  8184. if(!Buffer.allocUnsafe) Buffer.allocUnsafe = function(n) { return new Buffer(n); };
  8185. }
  8186. function new_raw_buf(len) {
  8187. /* jshint -W056 */
  8188. return has_buf ? Buffer.alloc(len) : new Array(len);
  8189. /* jshint +W056 */
  8190. }
  8191. function new_unsafe_buf(len) {
  8192. /* jshint -W056 */
  8193. return has_buf ? Buffer.allocUnsafe(len) : new Array(len);
  8194. /* jshint +W056 */
  8195. }
  8196. var s2a = function s2a(s) {
  8197. if(has_buf) return Buffer_from(s, "binary");
  8198. return s.split("").map(function(x){ return x.charCodeAt(0) & 0xff; });
  8199. };
  8200. function s2ab(s) {
  8201. if(typeof ArrayBuffer === 'undefined') return s2a(s);
  8202. var buf = new ArrayBuffer(s.length), view = new Uint8Array(buf);
  8203. for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  8204. return buf;
  8205. }
  8206. function a2s(data) {
  8207. if(Array.isArray(data)) return data.map(function(c) { return String.fromCharCode(c); }).join("");
  8208. var o = []; for(var i = 0; i < data.length; ++i) o[i] = String.fromCharCode(data[i]); return o.join("");
  8209. }
  8210. function a2u(data) {
  8211. if(typeof Uint8Array === 'undefined') throw new Error("Unsupported");
  8212. return new Uint8Array(data);
  8213. }
  8214. function ab2a(data) {
  8215. if(typeof ArrayBuffer == 'undefined') throw new Error("Unsupported");
  8216. if(data instanceof ArrayBuffer) return ab2a(new Uint8Array(data));
  8217. var o = new Array(data.length);
  8218. for(var i = 0; i < data.length; ++i) o[i] = data[i];
  8219. return o;
  8220. }
  8221. var bconcat = function(bufs) { return [].concat.apply([], bufs); };
  8222. var chr0 = /\u0000/g, chr1 = /[\u0001-\u0006]/g;
  8223. /* ssf.js (C) 2013-present SheetJS -- http://sheetjs.com */
  8224. /*jshint -W041 */
  8225. var SSF = ({});
  8226. var make_ssf = function make_ssf(SSF){
  8227. SSF.version = '0.11.2';
  8228. function _strrev(x) { var o = "", i = x.length-1; while(i>=0) o += x.charAt(i--); return o; }
  8229. function fill(c,l) { var o = ""; while(o.length < l) o+=c; return o; }
  8230. function pad0(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
  8231. function pad_(v,d){var t=""+v;return t.length>=d?t:fill(' ',d-t.length)+t;}
  8232. function rpad_(v,d){var t=""+v; return t.length>=d?t:t+fill(' ',d-t.length);}
  8233. function pad0r1(v,d){var t=""+Math.round(v); return t.length>=d?t:fill('0',d-t.length)+t;}
  8234. function pad0r2(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
  8235. var p2_32 = Math.pow(2,32);
  8236. function pad0r(v,d){if(v>p2_32||v<-p2_32) return pad0r1(v,d); var i = Math.round(v); return pad0r2(i,d); }
  8237. function isgeneral(s, i) { i = i || 0; return s.length >= 7 + i && (s.charCodeAt(i)|32) === 103 && (s.charCodeAt(i+1)|32) === 101 && (s.charCodeAt(i+2)|32) === 110 && (s.charCodeAt(i+3)|32) === 101 && (s.charCodeAt(i+4)|32) === 114 && (s.charCodeAt(i+5)|32) === 97 && (s.charCodeAt(i+6)|32) === 108; }
  8238. var days = [
  8239. ['Sun', 'Sunday'],
  8240. ['Mon', 'Monday'],
  8241. ['Tue', 'Tuesday'],
  8242. ['Wed', 'Wednesday'],
  8243. ['Thu', 'Thursday'],
  8244. ['Fri', 'Friday'],
  8245. ['Sat', 'Saturday']
  8246. ];
  8247. var months = [
  8248. ['J', 'Jan', 'January'],
  8249. ['F', 'Feb', 'February'],
  8250. ['M', 'Mar', 'March'],
  8251. ['A', 'Apr', 'April'],
  8252. ['M', 'May', 'May'],
  8253. ['J', 'Jun', 'June'],
  8254. ['J', 'Jul', 'July'],
  8255. ['A', 'Aug', 'August'],
  8256. ['S', 'Sep', 'September'],
  8257. ['O', 'Oct', 'October'],
  8258. ['N', 'Nov', 'November'],
  8259. ['D', 'Dec', 'December']
  8260. ];
  8261. function init_table(t) {
  8262. t[0]= 'General';
  8263. t[1]= '0';
  8264. t[2]= '0.00';
  8265. t[3]= '#,##0';
  8266. t[4]= '#,##0.00';
  8267. t[9]= '0%';
  8268. t[10]= '0.00%';
  8269. t[11]= '0.00E+00';
  8270. t[12]= '# ?/?';
  8271. t[13]= '# ??/??';
  8272. t[14]= 'm/d/yy';
  8273. t[15]= 'd-mmm-yy';
  8274. t[16]= 'd-mmm';
  8275. t[17]= 'mmm-yy';
  8276. t[18]= 'h:mm AM/PM';
  8277. t[19]= 'h:mm:ss AM/PM';
  8278. t[20]= 'h:mm';
  8279. t[21]= 'h:mm:ss';
  8280. t[22]= 'm/d/yy h:mm';
  8281. t[37]= '#,##0 ;(#,##0)';
  8282. t[38]= '#,##0 ;[Red](#,##0)';
  8283. t[39]= '#,##0.00;(#,##0.00)';
  8284. t[40]= '#,##0.00;[Red](#,##0.00)';
  8285. t[45]= 'mm:ss';
  8286. t[46]= '[h]:mm:ss';
  8287. t[47]= 'mmss.0';
  8288. t[48]= '##0.0E+0';
  8289. t[49]= '@';
  8290. t[56]= '"上午/下午 "hh"時"mm"分"ss"秒 "';
  8291. }
  8292. var table_fmt = {};
  8293. init_table(table_fmt);
  8294. /* Defaults determined by systematically testing in Excel 2019 */
  8295. /* These formats appear to default to other formats in the table */
  8296. var default_map = [];
  8297. var defi = 0;
  8298. // 5 -> 37 ... 8 -> 40
  8299. for(defi = 5; defi <= 8; ++defi) default_map[defi] = 32 + defi;
  8300. // 23 -> 0 ... 26 -> 0
  8301. for(defi = 23; defi <= 26; ++defi) default_map[defi] = 0;
  8302. // 27 -> 14 ... 31 -> 14
  8303. for(defi = 27; defi <= 31; ++defi) default_map[defi] = 14;
  8304. // 50 -> 14 ... 58 -> 14
  8305. for(defi = 50; defi <= 58; ++defi) default_map[defi] = 14;
  8306. // 59 -> 1 ... 62 -> 4
  8307. for(defi = 59; defi <= 62; ++defi) default_map[defi] = defi - 58;
  8308. // 67 -> 9 ... 68 -> 10
  8309. for(defi = 67; defi <= 68; ++defi) default_map[defi] = defi - 58;
  8310. // 72 -> 14 ... 75 -> 17
  8311. for(defi = 72; defi <= 75; ++defi) default_map[defi] = defi - 58;
  8312. // 69 -> 12 ... 71 -> 14
  8313. for(defi = 67; defi <= 68; ++defi) default_map[defi] = defi - 57;
  8314. // 76 -> 20 ... 78 -> 22
  8315. for(defi = 76; defi <= 78; ++defi) default_map[defi] = defi - 56;
  8316. // 79 -> 45 ... 81 -> 47
  8317. for(defi = 79; defi <= 81; ++defi) default_map[defi] = defi - 34;
  8318. // 82 -> 0 ... 65536 -> 0 (omitted)
  8319. /* These formats technically refer to Accounting formats with no equivalent */
  8320. var default_str = [];
  8321. // 5 -- Currency, 0 decimal, black negative
  8322. default_str[5] = default_str[63] = '"$"#,##0_);\\("$"#,##0\\)';
  8323. // 6 -- Currency, 0 decimal, red negative
  8324. default_str[6] = default_str[64] = '"$"#,##0_);[Red]\\("$"#,##0\\)';
  8325. // 7 -- Currency, 2 decimal, black negative
  8326. default_str[7] = default_str[65] = '"$"#,##0.00_);\\("$"#,##0.00\\)';
  8327. // 8 -- Currency, 2 decimal, red negative
  8328. default_str[8] = default_str[66] = '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)';
  8329. // 41 -- Accounting, 0 decimal, No Symbol
  8330. default_str[41] = '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)';
  8331. // 42 -- Accounting, 0 decimal, $ Symbol
  8332. default_str[42] = '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)';
  8333. // 43 -- Accounting, 2 decimal, No Symbol
  8334. default_str[43] = '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)';
  8335. // 44 -- Accounting, 2 decimal, $ Symbol
  8336. default_str[44] = '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)';
  8337. function frac(x, D, mixed) {
  8338. var sgn = x < 0 ? -1 : 1;
  8339. var B = x * sgn;
  8340. var P_2 = 0, P_1 = 1, P = 0;
  8341. var Q_2 = 1, Q_1 = 0, Q = 0;
  8342. var A = Math.floor(B);
  8343. while(Q_1 < D) {
  8344. A = Math.floor(B);
  8345. P = A * P_1 + P_2;
  8346. Q = A * Q_1 + Q_2;
  8347. if((B - A) < 0.00000005) break;
  8348. B = 1 / (B - A);
  8349. P_2 = P_1; P_1 = P;
  8350. Q_2 = Q_1; Q_1 = Q;
  8351. }
  8352. if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
  8353. if(!mixed) return [0, sgn * P, Q];
  8354. var q = Math.floor(sgn * P/Q);
  8355. return [q, sgn*P - q*Q, Q];
  8356. }
  8357. function parse_date_code(v,opts,b2) {
  8358. if(v > 2958465 || v < 0) return null;
  8359. var date = (v|0), time = Math.floor(86400 * (v - date)), dow=0;
  8360. var dout=[];
  8361. var out={D:date, T:time, u:86400*(v-date)-time,y:0,m:0,d:0,H:0,M:0,S:0,q:0};
  8362. if(Math.abs(out.u) < 1e-6) out.u = 0;
  8363. if(opts && opts.date1904) date += 1462;
  8364. if(out.u > 0.9999) {
  8365. out.u = 0;
  8366. if(++time == 86400) { out.T = time = 0; ++date; ++out.D; }
  8367. }
  8368. if(date === 60) {dout = b2 ? [1317,10,29] : [1900,2,29]; dow=3;}
  8369. else if(date === 0) {dout = b2 ? [1317,8,29] : [1900,1,0]; dow=6;}
  8370. else {
  8371. if(date > 60) --date;
  8372. /* 1 = Jan 1 1900 in Gregorian */
  8373. var d = new Date(1900, 0, 1);
  8374. d.setDate(d.getDate() + date - 1);
  8375. dout = [d.getFullYear(), d.getMonth()+1,d.getDate()];
  8376. dow = d.getDay();
  8377. if(date < 60) dow = (dow + 6) % 7;
  8378. if(b2) dow = fix_hijri(d, dout);
  8379. }
  8380. out.y = dout[0]; out.m = dout[1]; out.d = dout[2];
  8381. out.S = time % 60; time = Math.floor(time / 60);
  8382. out.M = time % 60; time = Math.floor(time / 60);
  8383. out.H = time;
  8384. out.q = dow;
  8385. return out;
  8386. }
  8387. SSF.parse_date_code = parse_date_code;
  8388. var basedate = new Date(1899, 11, 31, 0, 0, 0);
  8389. var dnthresh = basedate.getTime();
  8390. var base1904 = new Date(1900, 2, 1, 0, 0, 0);
  8391. function datenum_local(v, date1904) {
  8392. var epoch = v.getTime();
  8393. if(date1904) epoch -= 1461*24*60*60*1000;
  8394. else if(v >= base1904) epoch += 24*60*60*1000;
  8395. return (epoch - (dnthresh + (v.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000)) / (24 * 60 * 60 * 1000);
  8396. }
  8397. /* The longest 32-bit integer text is "-4294967296", exactly 11 chars */
  8398. function general_fmt_int(v) { return v.toString(10); }
  8399. SSF._general_int = general_fmt_int;
  8400. /* ECMA-376 18.8.30 numFmt*/
  8401. /* Note: `toPrecision` uses standard form when prec > E and E >= -6 */
  8402. var general_fmt_num = (function make_general_fmt_num() {
  8403. var trailing_zeroes_and_decimal = /(?:\.0*|(\.\d*[1-9])0+)$/;
  8404. function strip_decimal(o) {
  8405. return (o.indexOf(".") == -1) ? o : o.replace(trailing_zeroes_and_decimal, "$1");
  8406. }
  8407. /* General Exponential always shows 2 digits exp and trims the mantissa */
  8408. var mantissa_zeroes_and_decimal = /(?:\.0*|(\.\d*[1-9])0+)[Ee]/;
  8409. var exp_with_single_digit = /(E[+-])(\d)$/;
  8410. function normalize_exp(o) {
  8411. if(o.indexOf("E") == -1) return o;
  8412. return o.replace(mantissa_zeroes_and_decimal,"$1E").replace(exp_with_single_digit,"$10$2");
  8413. }
  8414. /* exponent >= -9 and <= 9 */
  8415. function small_exp(v) {
  8416. var w = (v<0?12:11);
  8417. var o = strip_decimal(v.toFixed(12)); if(o.length <= w) return o;
  8418. o = v.toPrecision(10); if(o.length <= w) return o;
  8419. return v.toExponential(5);
  8420. }
  8421. /* exponent >= 11 or <= -10 likely exponential */
  8422. function large_exp(v) {
  8423. var o = strip_decimal(v.toFixed(11));
  8424. return (o.length > (v<0?12:11) || o === "0" || o === "-0") ? v.toPrecision(6) : o;
  8425. }
  8426. function general_fmt_num_base(v) {
  8427. var V = Math.floor(Math.log(Math.abs(v))*Math.LOG10E), o;
  8428. if(V >= -4 && V <= -1) o = v.toPrecision(10+V);
  8429. else if(Math.abs(V) <= 9) o = small_exp(v);
  8430. else if(V === 10) o = v.toFixed(10).substr(0,12);
  8431. else o = large_exp(v);
  8432. return strip_decimal(normalize_exp(o.toUpperCase()));
  8433. }
  8434. return general_fmt_num_base;
  8435. })();
  8436. SSF._general_num = general_fmt_num;
  8437. /*
  8438. "General" rules:
  8439. - text is passed through ("@")
  8440. - booleans are rendered as TRUE/FALSE
  8441. - "up to 11 characters" displayed for numbers
  8442. - Default date format (code 14) used for Dates
  8443. TODO: technically the display depends on the width of the cell
  8444. */
  8445. function general_fmt(v, opts) {
  8446. switch(typeof v) {
  8447. case 'string': return v;
  8448. case 'boolean': return v ? "TRUE" : "FALSE";
  8449. case 'number': return (v|0) === v ? v.toString(10) : general_fmt_num(v);
  8450. case 'undefined': return "";
  8451. case 'object':
  8452. if(v == null) return "";
  8453. if(v instanceof Date) return format(14, datenum_local(v, opts && opts.date1904), opts);
  8454. }
  8455. throw new Error("unsupported value in General format: " + v);
  8456. }
  8457. SSF._general = general_fmt;
  8458. function fix_hijri(date, o) {
  8459. /* TODO: properly adjust y/m/d and */
  8460. o[0] -= 581;
  8461. var dow = date.getDay();
  8462. if(date < 60) dow = (dow + 6) % 7;
  8463. return dow;
  8464. }
  8465. //var THAI_DIGITS = "\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59".split("");
  8466. /*jshint -W086 */
  8467. function write_date(type, fmt, val, ss0) {
  8468. var o="", ss=0, tt=0, y = val.y, out, outl = 0;
  8469. switch(type) {
  8470. case 98: /* 'b' buddhist year */
  8471. y = val.y + 543;
  8472. /* falls through */
  8473. case 121: /* 'y' year */
  8474. switch(fmt.length) {
  8475. case 1: case 2: out = y % 100; outl = 2; break;
  8476. default: out = y % 10000; outl = 4; break;
  8477. } break;
  8478. case 109: /* 'm' month */
  8479. switch(fmt.length) {
  8480. case 1: case 2: out = val.m; outl = fmt.length; break;
  8481. case 3: return months[val.m-1][1];
  8482. case 5: return months[val.m-1][0];
  8483. default: return months[val.m-1][2];
  8484. } break;
  8485. case 100: /* 'd' day */
  8486. switch(fmt.length) {
  8487. case 1: case 2: out = val.d; outl = fmt.length; break;
  8488. case 3: return days[val.q][0];
  8489. default: return days[val.q][1];
  8490. } break;
  8491. case 104: /* 'h' 12-hour */
  8492. switch(fmt.length) {
  8493. case 1: case 2: out = 1+(val.H+11)%12; outl = fmt.length; break;
  8494. default: throw 'bad hour format: ' + fmt;
  8495. } break;
  8496. case 72: /* 'H' 24-hour */
  8497. switch(fmt.length) {
  8498. case 1: case 2: out = val.H; outl = fmt.length; break;
  8499. default: throw 'bad hour format: ' + fmt;
  8500. } break;
  8501. case 77: /* 'M' minutes */
  8502. switch(fmt.length) {
  8503. case 1: case 2: out = val.M; outl = fmt.length; break;
  8504. default: throw 'bad minute format: ' + fmt;
  8505. } break;
  8506. case 115: /* 's' seconds */
  8507. if(fmt != 's' && fmt != 'ss' && fmt != '.0' && fmt != '.00' && fmt != '.000') throw 'bad second format: ' + fmt;
  8508. if(val.u === 0 && (fmt == "s" || fmt == "ss")) return pad0(val.S, fmt.length);
  8509. if(ss0 >= 2) tt = ss0 === 3 ? 1000 : 100;
  8510. else tt = ss0 === 1 ? 10 : 1;
  8511. ss = Math.round((tt)*(val.S + val.u));
  8512. if(ss >= 60*tt) ss = 0;
  8513. if(fmt === 's') return ss === 0 ? "0" : ""+ss/tt;
  8514. o = pad0(ss,2 + ss0);
  8515. if(fmt === 'ss') return o.substr(0,2);
  8516. return "." + o.substr(2,fmt.length-1);
  8517. case 90: /* 'Z' absolute time */
  8518. switch(fmt) {
  8519. case '[h]': case '[hh]': out = val.D*24+val.H; break;
  8520. case '[m]': case '[mm]': out = (val.D*24+val.H)*60+val.M; break;
  8521. case '[s]': case '[ss]': out = ((val.D*24+val.H)*60+val.M)*60+Math.round(val.S+val.u); break;
  8522. default: throw 'bad abstime format: ' + fmt;
  8523. } outl = fmt.length === 3 ? 1 : 2; break;
  8524. case 101: /* 'e' era */
  8525. out = y; outl = 1; break;
  8526. }
  8527. var outstr = outl > 0 ? pad0(out, outl) : "";
  8528. return outstr;
  8529. }
  8530. /*jshint +W086 */
  8531. function commaify(s) {
  8532. var w = 3;
  8533. if(s.length <= w) return s;
  8534. var j = (s.length % w), o = s.substr(0,j);
  8535. for(; j!=s.length; j+=w) o+=(o.length > 0 ? "," : "") + s.substr(j,w);
  8536. return o;
  8537. }
  8538. var write_num = (function make_write_num(){
  8539. var pct1 = /%/g;
  8540. function write_num_pct(type, fmt, val){
  8541. var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
  8542. return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
  8543. }
  8544. function write_num_cm(type, fmt, val){
  8545. var idx = fmt.length - 1;
  8546. while(fmt.charCodeAt(idx-1) === 44) --idx;
  8547. return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
  8548. }
  8549. function write_num_exp(fmt, val){
  8550. var o;
  8551. var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  8552. if(fmt.match(/^#+0.0E\+0$/)) {
  8553. if(val == 0) return "0.0E+0";
  8554. else if(val < 0) return "-" + write_num_exp(fmt, -val);
  8555. var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
  8556. var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
  8557. if(ee < 0) ee += period;
  8558. o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
  8559. if(o.indexOf("e") === -1) {
  8560. var fakee = Math.floor(Math.log(val)*Math.LOG10E);
  8561. if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
  8562. else o += "E+" + (fakee - ee);
  8563. while(o.substr(0,2) === "0.") {
  8564. o = o.charAt(0) + o.substr(2,period) + "." + o.substr(2+period);
  8565. o = o.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0.");
  8566. }
  8567. o = o.replace(/\+-/,"-");
  8568. }
  8569. o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
  8570. } else o = val.toExponential(idx);
  8571. if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
  8572. if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
  8573. return o.replace("e","E");
  8574. }
  8575. var frac1 = /# (\?+)( ?)\/( ?)(\d+)/;
  8576. function write_num_f1(r, aval, sign) {
  8577. var den = parseInt(r[4],10), rr = Math.round(aval * den), base = Math.floor(rr/den);
  8578. var myn = (rr - base*den), myd = den;
  8579. return sign + (base === 0 ? "" : ""+base) + " " + (myn === 0 ? fill(" ", r[1].length + 1 + r[4].length) : pad_(myn,r[1].length) + r[2] + "/" + r[3] + pad0(myd,r[4].length));
  8580. }
  8581. function write_num_f2(r, aval, sign) {
  8582. return sign + (aval === 0 ? "" : ""+aval) + fill(" ", r[1].length + 2 + r[4].length);
  8583. }
  8584. var dec1 = /^#*0*\.([0#]+)/;
  8585. var closeparen = /\).*[0#]/;
  8586. var phone = /\(###\) ###\\?-####/;
  8587. function hashq(str) {
  8588. var o = "", cc;
  8589. for(var i = 0; i != str.length; ++i) switch((cc=str.charCodeAt(i))) {
  8590. case 35: break;
  8591. case 63: o+= " "; break;
  8592. case 48: o+= "0"; break;
  8593. default: o+= String.fromCharCode(cc);
  8594. }
  8595. return o;
  8596. }
  8597. function rnd(val, d) { var dd = Math.pow(10,d); return ""+(Math.round(val * dd)/dd); }
  8598. function dec(val, d) {
  8599. var _frac = val - Math.floor(val), dd = Math.pow(10,d);
  8600. if (d < ('' + Math.round(_frac * dd)).length) return 0;
  8601. return Math.round(_frac * dd);
  8602. }
  8603. function carry(val, d) {
  8604. if (d < ('' + Math.round((val-Math.floor(val))*Math.pow(10,d))).length) {
  8605. return 1;
  8606. }
  8607. return 0;
  8608. }
  8609. function flr(val) {
  8610. if(val < 2147483647 && val > -2147483648) return ""+(val >= 0 ? (val|0) : (val-1|0));
  8611. return ""+Math.floor(val);
  8612. }
  8613. function write_num_flt(type, fmt, val) {
  8614. if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
  8615. var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
  8616. if(val >= 0) return write_num_flt('n', ffmt, val);
  8617. return '(' + write_num_flt('n', ffmt, -val) + ')';
  8618. }
  8619. if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val);
  8620. if(fmt.indexOf('%') !== -1) return write_num_pct(type, fmt, val);
  8621. if(fmt.indexOf('E') !== -1) return write_num_exp(fmt, val);
  8622. if(fmt.charCodeAt(0) === 36) return "$"+write_num_flt(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
  8623. var o;
  8624. var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
  8625. if(fmt.match(/^00+$/)) return sign + pad0r(aval,fmt.length);
  8626. if(fmt.match(/^[#?]+$/)) {
  8627. o = pad0r(val,0); if(o === "0") o = "";
  8628. return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
  8629. }
  8630. if((r = fmt.match(frac1))) return write_num_f1(r, aval, sign);
  8631. if(fmt.match(/^#+0+$/)) return sign + pad0r(aval,fmt.length - fmt.indexOf("0"));
  8632. if((r = fmt.match(dec1))) {
  8633. o = rnd(val, r[1].length).replace(/^([^\.]+)$/,"$1."+hashq(r[1])).replace(/\.$/,"."+hashq(r[1])).replace(/\.(\d*)$/,function($$, $1) { return "." + $1 + fill("0", hashq(r[1]).length-$1.length); });
  8634. return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
  8635. }
  8636. fmt = fmt.replace(/^#+([0.])/, "$1");
  8637. if((r = fmt.match(/^(0*)\.(#*)$/))) {
  8638. return sign + rnd(aval, r[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
  8639. }
  8640. if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify(pad0r(aval,0));
  8641. if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
  8642. return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(""+(Math.floor(val) + carry(val, r[1].length))) + "." + pad0(dec(val, r[1].length),r[1].length);
  8643. }
  8644. if((r = fmt.match(/^#,#*,#0/))) return write_num_flt(type,fmt.replace(/^#,#*,/,""),val);
  8645. if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
  8646. o = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g,""), val));
  8647. ri = 0;
  8648. return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
  8649. }
  8650. if(fmt.match(phone)) {
  8651. o = write_num_flt(type, "##########", val);
  8652. return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
  8653. }
  8654. var oa = "";
  8655. if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  8656. ri = Math.min(r[4].length,7);
  8657. ff = frac(aval, Math.pow(10,ri)-1, false);
  8658. o = "" + sign;
  8659. oa = write_num("n", r[1], ff[1]);
  8660. if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
  8661. o += oa + r[2] + "/" + r[3];
  8662. oa = rpad_(ff[2],ri);
  8663. if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
  8664. o += oa;
  8665. return o;
  8666. }
  8667. if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  8668. ri = Math.min(Math.max(r[1].length, r[4].length),7);
  8669. ff = frac(aval, Math.pow(10,ri)-1, true);
  8670. return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill(" ", 2*ri+1 + r[2].length + r[3].length));
  8671. }
  8672. if((r = fmt.match(/^[#0?]+$/))) {
  8673. o = pad0r(val, 0);
  8674. if(fmt.length <= o.length) return o;
  8675. return hashq(fmt.substr(0,fmt.length-o.length)) + o;
  8676. }
  8677. if((r = fmt.match(/^([#0?]+)\.([#0]+)$/))) {
  8678. o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
  8679. ri = o.indexOf(".");
  8680. var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
  8681. return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
  8682. }
  8683. if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
  8684. ri = dec(val, r[1].length);
  8685. return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(flr(val)).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(ri,r[1].length);
  8686. }
  8687. switch(fmt) {
  8688. case "###,##0.00": return write_num_flt(type, "#,##0.00", val);
  8689. case "###,###":
  8690. case "##,###":
  8691. case "#,###": var x = commaify(pad0r(aval,0)); return x !== "0" ? sign + x : "";
  8692. case "###,###.00": return write_num_flt(type, "###,##0.00",val).replace(/^0\./,".");
  8693. case "#,###.00": return write_num_flt(type, "#,##0.00",val).replace(/^0\./,".");
  8694. default:
  8695. }
  8696. throw new Error("unsupported format |" + fmt + "|");
  8697. }
  8698. function write_num_cm2(type, fmt, val){
  8699. var idx = fmt.length - 1;
  8700. while(fmt.charCodeAt(idx-1) === 44) --idx;
  8701. return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
  8702. }
  8703. function write_num_pct2(type, fmt, val){
  8704. var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
  8705. return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
  8706. }
  8707. function write_num_exp2(fmt, val){
  8708. var o;
  8709. var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  8710. if(fmt.match(/^#+0.0E\+0$/)) {
  8711. if(val == 0) return "0.0E+0";
  8712. else if(val < 0) return "-" + write_num_exp2(fmt, -val);
  8713. var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
  8714. var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
  8715. if(ee < 0) ee += period;
  8716. o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
  8717. if(!o.match(/[Ee]/)) {
  8718. var fakee = Math.floor(Math.log(val)*Math.LOG10E);
  8719. if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
  8720. else o += "E+" + (fakee - ee);
  8721. o = o.replace(/\+-/,"-");
  8722. }
  8723. o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
  8724. } else o = val.toExponential(idx);
  8725. if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
  8726. if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
  8727. return o.replace("e","E");
  8728. }
  8729. function write_num_int(type, fmt, val) {
  8730. if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
  8731. var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
  8732. if(val >= 0) return write_num_int('n', ffmt, val);
  8733. return '(' + write_num_int('n', ffmt, -val) + ')';
  8734. }
  8735. if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val);
  8736. if(fmt.indexOf('%') !== -1) return write_num_pct2(type, fmt, val);
  8737. if(fmt.indexOf('E') !== -1) return write_num_exp2(fmt, val);
  8738. if(fmt.charCodeAt(0) === 36) return "$"+write_num_int(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
  8739. var o;
  8740. var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
  8741. if(fmt.match(/^00+$/)) return sign + pad0(aval,fmt.length);
  8742. if(fmt.match(/^[#?]+$/)) {
  8743. o = (""+val); if(val === 0) o = "";
  8744. return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
  8745. }
  8746. if((r = fmt.match(frac1))) return write_num_f2(r, aval, sign);
  8747. if(fmt.match(/^#+0+$/)) return sign + pad0(aval,fmt.length - fmt.indexOf("0"));
  8748. if((r = fmt.match(dec1))) {
  8749. o = (""+val).replace(/^([^\.]+)$/,"$1."+hashq(r[1])).replace(/\.$/,"."+hashq(r[1]));
  8750. o = o.replace(/\.(\d*)$/,function($$, $1) {
  8751. return "." + $1 + fill("0", hashq(r[1]).length-$1.length); });
  8752. return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
  8753. }
  8754. fmt = fmt.replace(/^#+([0.])/, "$1");
  8755. if((r = fmt.match(/^(0*)\.(#*)$/))) {
  8756. return sign + (""+aval).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
  8757. }
  8758. if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify((""+aval));
  8759. if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
  8760. return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify((""+val)) + "." + fill('0',r[1].length);
  8761. }
  8762. if((r = fmt.match(/^#,#*,#0/))) return write_num_int(type,fmt.replace(/^#,#*,/,""),val);
  8763. if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
  8764. o = _strrev(write_num_int(type, fmt.replace(/[\\-]/g,""), val));
  8765. ri = 0;
  8766. return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
  8767. }
  8768. if(fmt.match(phone)) {
  8769. o = write_num_int(type, "##########", val);
  8770. return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
  8771. }
  8772. var oa = "";
  8773. if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  8774. ri = Math.min(r[4].length,7);
  8775. ff = frac(aval, Math.pow(10,ri)-1, false);
  8776. o = "" + sign;
  8777. oa = write_num("n", r[1], ff[1]);
  8778. if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
  8779. o += oa + r[2] + "/" + r[3];
  8780. oa = rpad_(ff[2],ri);
  8781. if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
  8782. o += oa;
  8783. return o;
  8784. }
  8785. if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  8786. ri = Math.min(Math.max(r[1].length, r[4].length),7);
  8787. ff = frac(aval, Math.pow(10,ri)-1, true);
  8788. return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill(" ", 2*ri+1 + r[2].length + r[3].length));
  8789. }
  8790. if((r = fmt.match(/^[#0?]+$/))) {
  8791. o = "" + val;
  8792. if(fmt.length <= o.length) return o;
  8793. return hashq(fmt.substr(0,fmt.length-o.length)) + o;
  8794. }
  8795. if((r = fmt.match(/^([#0]+)\.([#0]+)$/))) {
  8796. o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
  8797. ri = o.indexOf(".");
  8798. var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
  8799. return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
  8800. }
  8801. if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
  8802. return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify(""+val).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(0,r[1].length);
  8803. }
  8804. switch(fmt) {
  8805. case "###,###":
  8806. case "##,###":
  8807. case "#,###": var x = commaify(""+aval); return x !== "0" ? sign + x : "";
  8808. default:
  8809. if(fmt.match(/\.[0#?]*$/)) return write_num_int(type, fmt.slice(0,fmt.lastIndexOf(".")), val) + hashq(fmt.slice(fmt.lastIndexOf(".")));
  8810. }
  8811. throw new Error("unsupported format |" + fmt + "|");
  8812. }
  8813. return function write_num(type, fmt, val) {
  8814. return (val|0) === val ? write_num_int(type, fmt, val) : write_num_flt(type, fmt, val);
  8815. };})();
  8816. function split_fmt(fmt) {
  8817. var out = [];
  8818. var in_str = false/*, cc*/;
  8819. for(var i = 0, j = 0; i < fmt.length; ++i) switch((/*cc=*/fmt.charCodeAt(i))) {
  8820. case 34: /* '"' */
  8821. in_str = !in_str; break;
  8822. case 95: case 42: case 92: /* '_' '*' '\\' */
  8823. ++i; break;
  8824. case 59: /* ';' */
  8825. out[out.length] = fmt.substr(j,i-j);
  8826. j = i+1;
  8827. }
  8828. out[out.length] = fmt.substr(j);
  8829. if(in_str === true) throw new Error("Format |" + fmt + "| unterminated string ");
  8830. return out;
  8831. }
  8832. SSF._split = split_fmt;
  8833. var abstime = /\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;
  8834. function fmt_is_date(fmt) {
  8835. var i = 0, /*cc = 0,*/ c = "", o = "";
  8836. while(i < fmt.length) {
  8837. switch((c = fmt.charAt(i))) {
  8838. case 'G': if(isgeneral(fmt, i)) i+= 6; i++; break;
  8839. case '"': for(;(/*cc=*/fmt.charCodeAt(++i)) !== 34 && i < fmt.length;){/*empty*/} ++i; break;
  8840. case '\\': i+=2; break;
  8841. case '_': i+=2; break;
  8842. case '@': ++i; break;
  8843. case 'B': case 'b':
  8844. if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") return true;
  8845. /* falls through */
  8846. case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
  8847. /* falls through */
  8848. case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g': return true;
  8849. case 'A': case 'a': case '上':
  8850. if(fmt.substr(i, 3).toUpperCase() === "A/P") return true;
  8851. if(fmt.substr(i, 5).toUpperCase() === "AM/PM") return true;
  8852. if(fmt.substr(i, 5).toUpperCase() === "上午/下午") return true;
  8853. ++i; break;
  8854. case '[':
  8855. o = c;
  8856. while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
  8857. if(o.match(abstime)) return true;
  8858. break;
  8859. case '.':
  8860. /* falls through */
  8861. case '0': case '#':
  8862. while(i < fmt.length && ("0#?.,E+-%".indexOf(c=fmt.charAt(++i)) > -1 || (c=='\\' && fmt.charAt(i+1) == "-" && "0#".indexOf(fmt.charAt(i+2))>-1))){/* empty */}
  8863. break;
  8864. case '?': while(fmt.charAt(++i) === c){/* empty */} break;
  8865. case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break;
  8866. case '(': case ')': ++i; break;
  8867. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  8868. while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1){/* empty */} break;
  8869. case ' ': ++i; break;
  8870. default: ++i; break;
  8871. }
  8872. }
  8873. return false;
  8874. }
  8875. SSF.is_date = fmt_is_date;
  8876. function eval_fmt(fmt, v, opts, flen) {
  8877. var out = [], o = "", i = 0, c = "", lst='t', dt, j, cc;
  8878. var hr='H';
  8879. /* Tokenize */
  8880. while(i < fmt.length) {
  8881. switch((c = fmt.charAt(i))) {
  8882. case 'G': /* General */
  8883. if(!isgeneral(fmt, i)) throw new Error('unrecognized character ' + c + ' in ' +fmt);
  8884. out[out.length] = {t:'G', v:'General'}; i+=7; break;
  8885. case '"': /* Literal text */
  8886. for(o="";(cc=fmt.charCodeAt(++i)) !== 34 && i < fmt.length;) o += String.fromCharCode(cc);
  8887. out[out.length] = {t:'t', v:o}; ++i; break;
  8888. case '\\': var w = fmt.charAt(++i), t = (w === "(" || w === ")") ? w : 't';
  8889. out[out.length] = {t:t, v:w}; ++i; break;
  8890. case '_': out[out.length] = {t:'t', v:" "}; i+=2; break;
  8891. case '@': /* Text Placeholder */
  8892. out[out.length] = {t:'T', v:v}; ++i; break;
  8893. case 'B': case 'b':
  8894. if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") {
  8895. if(dt==null) { dt=parse_date_code(v, opts, fmt.charAt(i+1) === "2"); if(dt==null) return ""; }
  8896. out[out.length] = {t:'X', v:fmt.substr(i,2)}; lst = c; i+=2; break;
  8897. }
  8898. /* falls through */
  8899. case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
  8900. c = c.toLowerCase();
  8901. /* falls through */
  8902. case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g':
  8903. if(v < 0) return "";
  8904. if(dt==null) { dt=parse_date_code(v, opts); if(dt==null) return ""; }
  8905. o = c; while(++i < fmt.length && fmt.charAt(i).toLowerCase() === c) o+=c;
  8906. if(c === 'm' && lst.toLowerCase() === 'h') c = 'M';
  8907. if(c === 'h') c = hr;
  8908. out[out.length] = {t:c, v:o}; lst = c; break;
  8909. case 'A': case 'a': case '上':
  8910. var q={t:c, v:c};
  8911. if(dt==null) dt=parse_date_code(v, opts);
  8912. if(fmt.substr(i, 3).toUpperCase() === "A/P") { if(dt!=null) q.v = dt.H >= 12 ? "P" : "A"; q.t = 'T'; hr='h';i+=3;}
  8913. else if(fmt.substr(i,5).toUpperCase() === "AM/PM") { if(dt!=null) q.v = dt.H >= 12 ? "PM" : "AM"; q.t = 'T'; i+=5; hr='h'; }
  8914. else if(fmt.substr(i,5).toUpperCase() === "上午/下午") { if(dt!=null) q.v = dt.H >= 12 ? "下午" : "上午"; q.t = 'T'; i+=5; hr='h'; }
  8915. else { q.t = "t"; ++i; }
  8916. if(dt==null && q.t === 'T') return "";
  8917. out[out.length] = q; lst = c; break;
  8918. case '[':
  8919. o = c;
  8920. while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
  8921. if(o.slice(-1) !== ']') throw 'unterminated "[" block: |' + o + '|';
  8922. if(o.match(abstime)) {
  8923. if(dt==null) { dt=parse_date_code(v, opts); if(dt==null) return ""; }
  8924. out[out.length] = {t:'Z', v:o.toLowerCase()};
  8925. lst = o.charAt(1);
  8926. } else if(o.indexOf("$") > -1) {
  8927. o = (o.match(/\$([^-\[\]]*)/)||[])[1]||"$";
  8928. if(!fmt_is_date(fmt)) out[out.length] = {t:'t',v:o};
  8929. }
  8930. break;
  8931. /* Numbers */
  8932. case '.':
  8933. if(dt != null) {
  8934. o = c; while(++i < fmt.length && (c=fmt.charAt(i)) === "0") o += c;
  8935. out[out.length] = {t:'s', v:o}; break;
  8936. }
  8937. /* falls through */
  8938. case '0': case '#':
  8939. o = c; while(++i < fmt.length && "0#?.,E+-%".indexOf(c=fmt.charAt(i)) > -1) o += c;
  8940. out[out.length] = {t:'n', v:o}; break;
  8941. case '?':
  8942. o = c; while(fmt.charAt(++i) === c) o+=c;
  8943. out[out.length] = {t:c, v:o}; lst = c; break;
  8944. case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break; // **
  8945. case '(': case ')': out[out.length] = {t:(flen===1?'t':c), v:c}; ++i; break;
  8946. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  8947. o = c; while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1) o+=fmt.charAt(i);
  8948. out[out.length] = {t:'D', v:o}; break;
  8949. case ' ': out[out.length] = {t:c, v:c}; ++i; break;
  8950. case '$': out[out.length] = {t:'t', v:'$'}; ++i; break;
  8951. default:
  8952. if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxzP".indexOf(c) === -1) throw new Error('unrecognized character ' + c + ' in ' + fmt);
  8953. out[out.length] = {t:'t', v:c}; ++i; break;
  8954. }
  8955. }
  8956. /* Scan for date/time parts */
  8957. var bt = 0, ss0 = 0, ssm;
  8958. for(i=out.length-1, lst='t'; i >= 0; --i) {
  8959. switch(out[i].t) {
  8960. case 'h': case 'H': out[i].t = hr; lst='h'; if(bt < 1) bt = 1; break;
  8961. case 's':
  8962. if((ssm=out[i].v.match(/\.0+$/))) ss0=Math.max(ss0,ssm[0].length-1);
  8963. if(bt < 3) bt = 3;
  8964. /* falls through */
  8965. case 'd': case 'y': case 'M': case 'e': lst=out[i].t; break;
  8966. case 'm': if(lst === 's') { out[i].t = 'M'; if(bt < 2) bt = 2; } break;
  8967. case 'X': /*if(out[i].v === "B2");*/
  8968. break;
  8969. case 'Z':
  8970. if(bt < 1 && out[i].v.match(/[Hh]/)) bt = 1;
  8971. if(bt < 2 && out[i].v.match(/[Mm]/)) bt = 2;
  8972. if(bt < 3 && out[i].v.match(/[Ss]/)) bt = 3;
  8973. }
  8974. }
  8975. /* time rounding depends on presence of minute / second / usec fields */
  8976. switch(bt) {
  8977. case 0: break;
  8978. case 1:
  8979. if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
  8980. if(dt.S >= 60) { dt.S = 0; ++dt.M; }
  8981. if(dt.M >= 60) { dt.M = 0; ++dt.H; }
  8982. break;
  8983. case 2:
  8984. if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
  8985. if(dt.S >= 60) { dt.S = 0; ++dt.M; }
  8986. break;
  8987. }
  8988. /* replace fields */
  8989. var nstr = "", jj;
  8990. for(i=0; i < out.length; ++i) {
  8991. switch(out[i].t) {
  8992. case 't': case 'T': case ' ': case 'D': break;
  8993. case 'X': out[i].v = ""; out[i].t = ";"; break;
  8994. case 'd': case 'm': case 'y': case 'h': case 'H': case 'M': case 's': case 'e': case 'b': case 'Z':
  8995. out[i].v = write_date(out[i].t.charCodeAt(0), out[i].v, dt, ss0);
  8996. out[i].t = 't'; break;
  8997. case 'n': case '?':
  8998. jj = i+1;
  8999. while(out[jj] != null && (
  9000. (c=out[jj].t) === "?" || c === "D" ||
  9001. ((c === " " || c === "t") && out[jj+1] != null && (out[jj+1].t === '?' || out[jj+1].t === "t" && out[jj+1].v === '/')) ||
  9002. (out[i].t === '(' && (c === ' ' || c === 'n' || c === ')')) ||
  9003. (c === 't' && (out[jj].v === '/' || out[jj].v === ' ' && out[jj+1] != null && out[jj+1].t == '?'))
  9004. )) {
  9005. out[i].v += out[jj].v;
  9006. out[jj] = {v:"", t:";"}; ++jj;
  9007. }
  9008. nstr += out[i].v;
  9009. i = jj-1; break;
  9010. case 'G': out[i].t = 't'; out[i].v = general_fmt(v,opts); break;
  9011. }
  9012. }
  9013. var vv = "", myv, ostr;
  9014. if(nstr.length > 0) {
  9015. if(nstr.charCodeAt(0) == 40) /* '(' */ {
  9016. myv = (v<0&&nstr.charCodeAt(0) === 45 ? -v : v);
  9017. ostr = write_num('n', nstr, myv);
  9018. } else {
  9019. myv = (v<0 && flen > 1 ? -v : v);
  9020. ostr = write_num('n', nstr, myv);
  9021. if(myv < 0 && out[0] && out[0].t == 't') {
  9022. ostr = ostr.substr(1);
  9023. out[0].v = "-" + out[0].v;
  9024. }
  9025. }
  9026. jj=ostr.length-1;
  9027. var decpt = out.length;
  9028. for(i=0; i < out.length; ++i) if(out[i] != null && out[i].t != 't' && out[i].v.indexOf(".") > -1) { decpt = i; break; }
  9029. var lasti=out.length;
  9030. if(decpt === out.length && ostr.indexOf("E") === -1) {
  9031. for(i=out.length-1; i>= 0;--i) {
  9032. if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
  9033. if(jj>=out[i].v.length-1) { jj -= out[i].v.length; out[i].v = ostr.substr(jj+1, out[i].v.length); }
  9034. else if(jj < 0) out[i].v = "";
  9035. else { out[i].v = ostr.substr(0, jj+1); jj = -1; }
  9036. out[i].t = 't';
  9037. lasti = i;
  9038. }
  9039. if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
  9040. }
  9041. else if(decpt !== out.length && ostr.indexOf("E") === -1) {
  9042. jj = ostr.indexOf(".")-1;
  9043. for(i=decpt; i>= 0; --i) {
  9044. if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
  9045. j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")-1:out[i].v.length-1;
  9046. vv = out[i].v.substr(j+1);
  9047. for(; j>=0; --j) {
  9048. if(jj>=0 && (out[i].v.charAt(j) === "0" || out[i].v.charAt(j) === "#")) vv = ostr.charAt(jj--) + vv;
  9049. }
  9050. out[i].v = vv;
  9051. out[i].t = 't';
  9052. lasti = i;
  9053. }
  9054. if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
  9055. jj = ostr.indexOf(".")+1;
  9056. for(i=decpt; i<out.length; ++i) {
  9057. if(out[i] == null || ('n?('.indexOf(out[i].t) === -1 && i !== decpt)) continue;
  9058. j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")+1:0;
  9059. vv = out[i].v.substr(0,j);
  9060. for(; j<out[i].v.length; ++j) {
  9061. if(jj<ostr.length) vv += ostr.charAt(jj++);
  9062. }
  9063. out[i].v = vv;
  9064. out[i].t = 't';
  9065. lasti = i;
  9066. }
  9067. }
  9068. }
  9069. for(i=0; i<out.length; ++i) if(out[i] != null && 'n?'.indexOf(out[i].t)>-1) {
  9070. myv = (flen >1 && v < 0 && i>0 && out[i-1].v === "-" ? -v:v);
  9071. out[i].v = write_num(out[i].t, out[i].v, myv);
  9072. out[i].t = 't';
  9073. }
  9074. var retval = "";
  9075. for(i=0; i !== out.length; ++i) if(out[i] != null) retval += out[i].v;
  9076. return retval;
  9077. }
  9078. SSF._eval = eval_fmt;
  9079. var cfregex = /\[[=<>]/;
  9080. var cfregex2 = /\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;
  9081. function chkcond(v, rr) {
  9082. if(rr == null) return false;
  9083. var thresh = parseFloat(rr[2]);
  9084. switch(rr[1]) {
  9085. case "=": if(v == thresh) return true; break;
  9086. case ">": if(v > thresh) return true; break;
  9087. case "<": if(v < thresh) return true; break;
  9088. case "<>": if(v != thresh) return true; break;
  9089. case ">=": if(v >= thresh) return true; break;
  9090. case "<=": if(v <= thresh) return true; break;
  9091. }
  9092. return false;
  9093. }
  9094. function choose_fmt(f, v) {
  9095. var fmt = split_fmt(f);
  9096. var l = fmt.length, lat = fmt[l-1].indexOf("@");
  9097. if(l<4 && lat>-1) --l;
  9098. if(fmt.length > 4) throw new Error("cannot find right format for |" + fmt.join("|") + "|");
  9099. if(typeof v !== "number") return [4, fmt.length === 4 || lat>-1?fmt[fmt.length-1]:"@"];
  9100. switch(fmt.length) {
  9101. case 1: fmt = lat>-1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"]; break;
  9102. case 2: fmt = lat>-1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"]; break;
  9103. case 3: fmt = lat>-1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"]; break;
  9104. case 4: break;
  9105. }
  9106. var ff = v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2];
  9107. if(fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l, ff];
  9108. if(fmt[0].match(cfregex) != null || fmt[1].match(cfregex) != null) {
  9109. var m1 = fmt[0].match(cfregex2);
  9110. var m2 = fmt[1].match(cfregex2);
  9111. return chkcond(v, m1) ? [l, fmt[0]] : chkcond(v, m2) ? [l, fmt[1]] : [l, fmt[m1 != null && m2 != null ? 2 : 1]];
  9112. }
  9113. return [l, ff];
  9114. }
  9115. function format(fmt,v,o) {
  9116. if(o == null) o = {};
  9117. var sfmt = "";
  9118. switch(typeof fmt) {
  9119. case "string":
  9120. if(fmt == "m/d/yy" && o.dateNF) sfmt = o.dateNF;
  9121. else sfmt = fmt;
  9122. break;
  9123. case "number":
  9124. if(fmt == 14 && o.dateNF) sfmt = o.dateNF;
  9125. else sfmt = (o.table != null ? (o.table) : table_fmt)[fmt];
  9126. if(sfmt == null) sfmt = (o.table && o.table[default_map[fmt]]) || table_fmt[default_map[fmt]];
  9127. if(sfmt == null) sfmt = default_str[fmt] || "General";
  9128. break;
  9129. }
  9130. if(isgeneral(sfmt,0)) return general_fmt(v, o);
  9131. if(v instanceof Date) v = datenum_local(v, o.date1904);
  9132. var f = choose_fmt(sfmt, v);
  9133. if(isgeneral(f[1])) return general_fmt(v, o);
  9134. if(v === true) v = "TRUE"; else if(v === false) v = "FALSE";
  9135. else if(v === "" || v == null) return "";
  9136. return eval_fmt(f[1], v, o, f[0]);
  9137. }
  9138. function load_entry(fmt, idx) {
  9139. if(typeof idx != 'number') {
  9140. idx = +idx || -1;
  9141. for(var i = 0; i < 0x0188; ++i) {
  9142. if(table_fmt[i] == undefined) { if(idx < 0) idx = i; continue; }
  9143. if(table_fmt[i] == fmt) { idx = i; break; }
  9144. }
  9145. if(idx < 0) idx = 0x187;
  9146. }
  9147. table_fmt[idx] = fmt;
  9148. return idx;
  9149. }
  9150. SSF.load = load_entry;
  9151. SSF._table = table_fmt;
  9152. SSF.get_table = function get_table() { return table_fmt; };
  9153. SSF.load_table = function load_table(tbl) {
  9154. for(var i=0; i!=0x0188; ++i)
  9155. if(tbl[i] !== undefined) load_entry(tbl[i], i);
  9156. };
  9157. SSF.init_table = init_table;
  9158. SSF.format = format;
  9159. };
  9160. make_ssf(SSF);
  9161. /* map from xlml named formats to SSF TODO: localize */
  9162. var XLMLFormatMap/*{[string]:string}*/ = ({
  9163. "General Number": "General",
  9164. "General Date": SSF._table[22],
  9165. "Long Date": "dddd, mmmm dd, yyyy",
  9166. "Medium Date": SSF._table[15],
  9167. "Short Date": SSF._table[14],
  9168. "Long Time": SSF._table[19],
  9169. "Medium Time": SSF._table[18],
  9170. "Short Time": SSF._table[20],
  9171. "Currency": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  9172. "Fixed": SSF._table[2],
  9173. "Standard": SSF._table[4],
  9174. "Percent": SSF._table[10],
  9175. "Scientific": SSF._table[11],
  9176. "Yes/No": '"Yes";"Yes";"No";@',
  9177. "True/False": '"True";"True";"False";@',
  9178. "On/Off": '"Yes";"Yes";"No";@'
  9179. });
  9180. var SSFImplicit/*{[number]:string}*/ = ({
  9181. "5": '"$"#,##0_);\\("$"#,##0\\)',
  9182. "6": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  9183. "7": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  9184. "8": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  9185. "23": 'General', "24": 'General', "25": 'General', "26": 'General',
  9186. "27": 'm/d/yy', "28": 'm/d/yy', "29": 'm/d/yy', "30": 'm/d/yy', "31": 'm/d/yy',
  9187. "32": 'h:mm:ss', "33": 'h:mm:ss', "34": 'h:mm:ss', "35": 'h:mm:ss',
  9188. "36": 'm/d/yy',
  9189. "41": '_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)',
  9190. "42": '_("$"* #,##0_);_("$"* \(#,##0\);_("$"* "-"_);_(@_)',
  9191. "43": '_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)',
  9192. "44": '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)',
  9193. "50": 'm/d/yy', "51": 'm/d/yy', "52": 'm/d/yy', "53": 'm/d/yy', "54": 'm/d/yy',
  9194. "55": 'm/d/yy', "56": 'm/d/yy', "57": 'm/d/yy', "58": 'm/d/yy',
  9195. "59": '0',
  9196. "60": '0.00',
  9197. "61": '#,##0',
  9198. "62": '#,##0.00',
  9199. "63": '"$"#,##0_);\\("$"#,##0\\)',
  9200. "64": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  9201. "65": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  9202. "66": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  9203. "67": '0%',
  9204. "68": '0.00%',
  9205. "69": '# ?/?',
  9206. "70": '# ??/??',
  9207. "71": 'm/d/yy',
  9208. "72": 'm/d/yy',
  9209. "73": 'd-mmm-yy',
  9210. "74": 'd-mmm',
  9211. "75": 'mmm-yy',
  9212. "76": 'h:mm',
  9213. "77": 'h:mm:ss',
  9214. "78": 'm/d/yy h:mm',
  9215. "79": 'mm:ss',
  9216. "80": '[h]:mm:ss',
  9217. "81": 'mmss.0'
  9218. });
  9219. /* dateNF parse TODO: move to SSF */
  9220. var dateNFregex = /[dD]+|[mM]+|[yYeE]+|[Hh]+|[Ss]+/g;
  9221. function dateNF_regex(dateNF) {
  9222. var fmt = typeof dateNF == "number" ? SSF._table[dateNF] : dateNF;
  9223. fmt = fmt.replace(dateNFregex, "(\\d+)");
  9224. return new RegExp("^" + fmt + "$");
  9225. }
  9226. function dateNF_fix(str, dateNF, match) {
  9227. var Y = -1, m = -1, d = -1, H = -1, M = -1, S = -1;
  9228. (dateNF.match(dateNFregex)||[]).forEach(function(n, i) {
  9229. var v = parseInt(match[i+1], 10);
  9230. switch(n.toLowerCase().charAt(0)) {
  9231. case 'y': Y = v; break; case 'd': d = v; break;
  9232. case 'h': H = v; break; case 's': S = v; break;
  9233. case 'm': if(H >= 0) M = v; else m = v; break;
  9234. }
  9235. });
  9236. if(S >= 0 && M == -1 && m >= 0) { M = m; m = -1; }
  9237. var datestr = (("" + (Y>=0?Y: new Date().getFullYear())).slice(-4) + "-" + ("00" + (m>=1?m:1)).slice(-2) + "-" + ("00" + (d>=1?d:1)).slice(-2));
  9238. if(datestr.length == 7) datestr = "0" + datestr;
  9239. if(datestr.length == 8) datestr = "20" + datestr;
  9240. var timestr = (("00" + (H>=0?H:0)).slice(-2) + ":" + ("00" + (M>=0?M:0)).slice(-2) + ":" + ("00" + (S>=0?S:0)).slice(-2));
  9241. if(H == -1 && M == -1 && S == -1) return datestr;
  9242. if(Y == -1 && m == -1 && d == -1) return timestr;
  9243. return datestr + "T" + timestr;
  9244. }
  9245. var DO_NOT_EXPORT_CFB = true;
  9246. /* cfb.js (C) 2013-present SheetJS -- http://sheetjs.com */
  9247. /* vim: set ts=2: */
  9248. /*jshint eqnull:true */
  9249. /*exported CFB */
  9250. /*global Uint8Array:false, Uint16Array:false */
  9251. /* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
  9252. /* vim: set ts=2: */
  9253. /*exported CRC32 */
  9254. var CRC32;
  9255. (function (factory) {
  9256. /*jshint ignore:start */
  9257. /*eslint-disable */
  9258. factory(CRC32 = {});
  9259. /*eslint-enable */
  9260. /*jshint ignore:end */
  9261. }(function(CRC32) {
  9262. CRC32.version = '1.2.0';
  9263. /* see perf/crc32table.js */
  9264. /*global Int32Array */
  9265. function signed_crc_table() {
  9266. var c = 0, table = new Array(256);
  9267. for(var n =0; n != 256; ++n){
  9268. c = n;
  9269. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9270. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9271. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9272. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9273. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9274. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9275. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9276. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9277. table[n] = c;
  9278. }
  9279. return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;
  9280. }
  9281. var T = signed_crc_table();
  9282. function crc32_bstr(bstr, seed) {
  9283. var C = seed ^ -1, L = bstr.length - 1;
  9284. for(var i = 0; i < L;) {
  9285. C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
  9286. C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
  9287. }
  9288. if(i === L) C = (C>>>8) ^ T[(C ^ bstr.charCodeAt(i))&0xFF];
  9289. return C ^ -1;
  9290. }
  9291. function crc32_buf(buf, seed) {
  9292. if(buf.length > 10000) return crc32_buf_8(buf, seed);
  9293. var C = seed ^ -1, L = buf.length - 3;
  9294. for(var i = 0; i < L;) {
  9295. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9296. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9297. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9298. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9299. }
  9300. while(i < L+3) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9301. return C ^ -1;
  9302. }
  9303. function crc32_buf_8(buf, seed) {
  9304. var C = seed ^ -1, L = buf.length - 7;
  9305. for(var i = 0; i < L;) {
  9306. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9307. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9308. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9309. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9310. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9311. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9312. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9313. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9314. }
  9315. while(i < L+7) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9316. return C ^ -1;
  9317. }
  9318. function crc32_str(str, seed) {
  9319. var C = seed ^ -1;
  9320. for(var i = 0, L=str.length, c, d; i < L;) {
  9321. c = str.charCodeAt(i++);
  9322. if(c < 0x80) {
  9323. C = (C>>>8) ^ T[(C ^ c)&0xFF];
  9324. } else if(c < 0x800) {
  9325. C = (C>>>8) ^ T[(C ^ (192|((c>>6)&31)))&0xFF];
  9326. C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
  9327. } else if(c >= 0xD800 && c < 0xE000) {
  9328. c = (c&1023)+64; d = str.charCodeAt(i++)&1023;
  9329. C = (C>>>8) ^ T[(C ^ (240|((c>>8)&7)))&0xFF];
  9330. C = (C>>>8) ^ T[(C ^ (128|((c>>2)&63)))&0xFF];
  9331. C = (C>>>8) ^ T[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF];
  9332. C = (C>>>8) ^ T[(C ^ (128|(d&63)))&0xFF];
  9333. } else {
  9334. C = (C>>>8) ^ T[(C ^ (224|((c>>12)&15)))&0xFF];
  9335. C = (C>>>8) ^ T[(C ^ (128|((c>>6)&63)))&0xFF];
  9336. C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
  9337. }
  9338. }
  9339. return C ^ -1;
  9340. }
  9341. CRC32.table = T;
  9342. CRC32.bstr = crc32_bstr;
  9343. CRC32.buf = crc32_buf;
  9344. CRC32.str = crc32_str;
  9345. }));
  9346. /* [MS-CFB] v20171201 */
  9347. var CFB = (function _CFB(){
  9348. var exports = {};
  9349. exports.version = '1.1.4';
  9350. /* [MS-CFB] 2.6.4 */
  9351. function namecmp(l, r) {
  9352. var L = l.split("/"), R = r.split("/");
  9353. for(var i = 0, c = 0, Z = Math.min(L.length, R.length); i < Z; ++i) {
  9354. if((c = L[i].length - R[i].length)) return c;
  9355. if(L[i] != R[i]) return L[i] < R[i] ? -1 : 1;
  9356. }
  9357. return L.length - R.length;
  9358. }
  9359. function dirname(p) {
  9360. if(p.charAt(p.length - 1) == "/") return (p.slice(0,-1).indexOf("/") === -1) ? p : dirname(p.slice(0, -1));
  9361. var c = p.lastIndexOf("/");
  9362. return (c === -1) ? p : p.slice(0, c+1);
  9363. }
  9364. function filename(p) {
  9365. if(p.charAt(p.length - 1) == "/") return filename(p.slice(0, -1));
  9366. var c = p.lastIndexOf("/");
  9367. return (c === -1) ? p : p.slice(c+1);
  9368. }
  9369. /* -------------------------------------------------------------------------- */
  9370. /* DOS Date format:
  9371. high|YYYYYYYm.mmmddddd.HHHHHMMM.MMMSSSSS|low
  9372. add 1980 to stored year
  9373. stored second should be doubled
  9374. */
  9375. /* write JS date to buf as a DOS date */
  9376. function write_dos_date(buf, date) {
  9377. if(typeof date === "string") date = new Date(date);
  9378. var hms = date.getHours();
  9379. hms = hms << 6 | date.getMinutes();
  9380. hms = hms << 5 | (date.getSeconds()>>>1);
  9381. buf.write_shift(2, hms);
  9382. var ymd = (date.getFullYear() - 1980);
  9383. ymd = ymd << 4 | (date.getMonth()+1);
  9384. ymd = ymd << 5 | date.getDate();
  9385. buf.write_shift(2, ymd);
  9386. }
  9387. /* read four bytes from buf and interpret as a DOS date */
  9388. function parse_dos_date(buf) {
  9389. var hms = buf.read_shift(2) & 0xFFFF;
  9390. var ymd = buf.read_shift(2) & 0xFFFF;
  9391. var val = new Date();
  9392. var d = ymd & 0x1F; ymd >>>= 5;
  9393. var m = ymd & 0x0F; ymd >>>= 4;
  9394. val.setMilliseconds(0);
  9395. val.setFullYear(ymd + 1980);
  9396. val.setMonth(m-1);
  9397. val.setDate(d);
  9398. var S = hms & 0x1F; hms >>>= 5;
  9399. var M = hms & 0x3F; hms >>>= 6;
  9400. val.setHours(hms);
  9401. val.setMinutes(M);
  9402. val.setSeconds(S<<1);
  9403. return val;
  9404. }
  9405. function parse_extra_field(blob) {
  9406. prep_blob(blob, 0);
  9407. var o = {};
  9408. var flags = 0;
  9409. while(blob.l <= blob.length - 4) {
  9410. var type = blob.read_shift(2);
  9411. var sz = blob.read_shift(2), tgt = blob.l + sz;
  9412. var p = {};
  9413. switch(type) {
  9414. /* UNIX-style Timestamps */
  9415. case 0x5455: {
  9416. flags = blob.read_shift(1);
  9417. if(flags & 1) p.mtime = blob.read_shift(4);
  9418. /* for some reason, CD flag corresponds to LFH */
  9419. if(sz > 5) {
  9420. if(flags & 2) p.atime = blob.read_shift(4);
  9421. if(flags & 4) p.ctime = blob.read_shift(4);
  9422. }
  9423. if(p.mtime) p.mt = new Date(p.mtime*1000);
  9424. }
  9425. break;
  9426. }
  9427. blob.l = tgt;
  9428. o[type] = p;
  9429. }
  9430. return o;
  9431. }
  9432. var fs;
  9433. function get_fs() { return fs || (fs = require('fs')); }
  9434. function parse(file, options) {
  9435. if(file[0] == 0x50 && file[1] == 0x4b) return parse_zip(file, options);
  9436. if(file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
  9437. var mver = 3;
  9438. var ssz = 512;
  9439. var nmfs = 0; // number of mini FAT sectors
  9440. var difat_sec_cnt = 0;
  9441. var dir_start = 0;
  9442. var minifat_start = 0;
  9443. var difat_start = 0;
  9444. var fat_addrs = []; // locations of FAT sectors
  9445. /* [MS-CFB] 2.2 Compound File Header */
  9446. var blob = file.slice(0,512);
  9447. prep_blob(blob, 0);
  9448. /* major version */
  9449. var mv = check_get_mver(blob);
  9450. mver = mv[0];
  9451. switch(mver) {
  9452. case 3: ssz = 512; break; case 4: ssz = 4096; break;
  9453. case 0: if(mv[1] == 0) return parse_zip(file, options);
  9454. /* falls through */
  9455. default: throw new Error("Major Version: Expected 3 or 4 saw " + mver);
  9456. }
  9457. /* reprocess header */
  9458. if(ssz !== 512) { blob = file.slice(0,ssz); prep_blob(blob, 28 /* blob.l */); }
  9459. /* Save header for final object */
  9460. var header = file.slice(0,ssz);
  9461. check_shifts(blob, mver);
  9462. // Number of Directory Sectors
  9463. var dir_cnt = blob.read_shift(4, 'i');
  9464. if(mver === 3 && dir_cnt !== 0) throw new Error('# Directory Sectors: Expected 0 saw ' + dir_cnt);
  9465. // Number of FAT Sectors
  9466. blob.l += 4;
  9467. // First Directory Sector Location
  9468. dir_start = blob.read_shift(4, 'i');
  9469. // Transaction Signature
  9470. blob.l += 4;
  9471. // Mini Stream Cutoff Size
  9472. blob.chk('00100000', 'Mini Stream Cutoff Size: ');
  9473. // First Mini FAT Sector Location
  9474. minifat_start = blob.read_shift(4, 'i');
  9475. // Number of Mini FAT Sectors
  9476. nmfs = blob.read_shift(4, 'i');
  9477. // First DIFAT sector location
  9478. difat_start = blob.read_shift(4, 'i');
  9479. // Number of DIFAT Sectors
  9480. difat_sec_cnt = blob.read_shift(4, 'i');
  9481. // Grab FAT Sector Locations
  9482. for(var q = -1, j = 0; j < 109; ++j) { /* 109 = (512 - blob.l)>>>2; */
  9483. q = blob.read_shift(4, 'i');
  9484. if(q<0) break;
  9485. fat_addrs[j] = q;
  9486. }
  9487. /** Break the file up into sectors */
  9488. var sectors = sectorify(file, ssz);
  9489. sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);
  9490. /** Chains */
  9491. var sector_list = make_sector_list(sectors, dir_start, fat_addrs, ssz);
  9492. sector_list[dir_start].name = "!Directory";
  9493. if(nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
  9494. sector_list[fat_addrs[0]].name = "!FAT";
  9495. sector_list.fat_addrs = fat_addrs;
  9496. sector_list.ssz = ssz;
  9497. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  9498. var files = {}, Paths = [], FileIndex = [], FullPaths = [];
  9499. read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);
  9500. build_full_paths(FileIndex, FullPaths, Paths);
  9501. Paths.shift();
  9502. var o = {
  9503. FileIndex: FileIndex,
  9504. FullPaths: FullPaths
  9505. };
  9506. // $FlowIgnore
  9507. if(options && options.raw) o.raw = {header: header, sectors: sectors};
  9508. return o;
  9509. } // parse
  9510. /* [MS-CFB] 2.2 Compound File Header -- read up to major version */
  9511. function check_get_mver(blob) {
  9512. if(blob[blob.l] == 0x50 && blob[blob.l + 1] == 0x4b) return [0, 0];
  9513. // header signature 8
  9514. blob.chk(HEADER_SIGNATURE, 'Header Signature: ');
  9515. // clsid 16
  9516. //blob.chk(HEADER_CLSID, 'CLSID: ');
  9517. blob.l += 16;
  9518. // minor version 2
  9519. var mver = blob.read_shift(2, 'u');
  9520. return [blob.read_shift(2,'u'), mver];
  9521. }
  9522. function check_shifts(blob, mver) {
  9523. var shift = 0x09;
  9524. // Byte Order
  9525. //blob.chk('feff', 'Byte Order: '); // note: some writers put 0xffff
  9526. blob.l += 2;
  9527. // Sector Shift
  9528. switch((shift = blob.read_shift(2))) {
  9529. case 0x09: if(mver != 3) throw new Error('Sector Shift: Expected 9 saw ' + shift); break;
  9530. case 0x0c: if(mver != 4) throw new Error('Sector Shift: Expected 12 saw ' + shift); break;
  9531. default: throw new Error('Sector Shift: Expected 9 or 12 saw ' + shift);
  9532. }
  9533. // Mini Sector Shift
  9534. blob.chk('0600', 'Mini Sector Shift: ');
  9535. // Reserved
  9536. blob.chk('000000000000', 'Reserved: ');
  9537. }
  9538. /** Break the file up into sectors */
  9539. function sectorify(file, ssz) {
  9540. var nsectors = Math.ceil(file.length/ssz)-1;
  9541. var sectors = [];
  9542. for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz);
  9543. sectors[nsectors-1] = file.slice(nsectors*ssz);
  9544. return sectors;
  9545. }
  9546. /* [MS-CFB] 2.6.4 Red-Black Tree */
  9547. function build_full_paths(FI, FP, Paths) {
  9548. var i = 0, L = 0, R = 0, C = 0, j = 0, pl = Paths.length;
  9549. var dad = [], q = [];
  9550. for(; i < pl; ++i) { dad[i]=q[i]=i; FP[i]=Paths[i]; }
  9551. for(; j < q.length; ++j) {
  9552. i = q[j];
  9553. L = FI[i].L; R = FI[i].R; C = FI[i].C;
  9554. if(dad[i] === i) {
  9555. if(L !== -1 /*NOSTREAM*/ && dad[L] !== L) dad[i] = dad[L];
  9556. if(R !== -1 && dad[R] !== R) dad[i] = dad[R];
  9557. }
  9558. if(C !== -1 /*NOSTREAM*/) dad[C] = i;
  9559. if(L !== -1 && i != dad[i]) { dad[L] = dad[i]; if(q.lastIndexOf(L) < j) q.push(L); }
  9560. if(R !== -1 && i != dad[i]) { dad[R] = dad[i]; if(q.lastIndexOf(R) < j) q.push(R); }
  9561. }
  9562. for(i=1; i < pl; ++i) if(dad[i] === i) {
  9563. if(R !== -1 /*NOSTREAM*/ && dad[R] !== R) dad[i] = dad[R];
  9564. else if(L !== -1 && dad[L] !== L) dad[i] = dad[L];
  9565. }
  9566. for(i=1; i < pl; ++i) {
  9567. if(FI[i].type === 0 /* unknown */) continue;
  9568. j = i;
  9569. if(j != dad[j]) do {
  9570. j = dad[j];
  9571. FP[i] = FP[j] + "/" + FP[i];
  9572. } while (j !== 0 && -1 !== dad[j] && j != dad[j]);
  9573. dad[i] = -1;
  9574. }
  9575. FP[0] += "/";
  9576. for(i=1; i < pl; ++i) {
  9577. if(FI[i].type !== 2 /* stream */) FP[i] += "/";
  9578. }
  9579. }
  9580. function get_mfat_entry(entry, payload, mini) {
  9581. var start = entry.start, size = entry.size;
  9582. //return (payload.slice(start*MSSZ, start*MSSZ + size));
  9583. var o = [];
  9584. var idx = start;
  9585. while(mini && size > 0 && idx >= 0) {
  9586. o.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
  9587. size -= MSSZ;
  9588. idx = __readInt32LE(mini, idx * 4);
  9589. }
  9590. if(o.length === 0) return (new_buf(0));
  9591. return (bconcat(o).slice(0, entry.size));
  9592. }
  9593. /** Chase down the rest of the DIFAT chain to build a comprehensive list
  9594. DIFAT chains by storing the next sector number as the last 32 bits */
  9595. function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) {
  9596. var q = ENDOFCHAIN;
  9597. if(idx === ENDOFCHAIN) {
  9598. if(cnt !== 0) throw new Error("DIFAT chain shorter than expected");
  9599. } else if(idx !== -1 /*FREESECT*/) {
  9600. var sector = sectors[idx], m = (ssz>>>2)-1;
  9601. if(!sector) return;
  9602. for(var i = 0; i < m; ++i) {
  9603. if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break;
  9604. fat_addrs.push(q);
  9605. }
  9606. sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs);
  9607. }
  9608. }
  9609. /** Follow the linked list of sectors for a given starting point */
  9610. function get_sector_list(sectors, start, fat_addrs, ssz, chkd) {
  9611. var buf = [], buf_chain = [];
  9612. if(!chkd) chkd = [];
  9613. var modulus = ssz - 1, j = 0, jj = 0;
  9614. for(j=start; j>=0;) {
  9615. chkd[j] = true;
  9616. buf[buf.length] = j;
  9617. buf_chain.push(sectors[j]);
  9618. var addr = fat_addrs[Math.floor(j*4/ssz)];
  9619. jj = ((j*4) & modulus);
  9620. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  9621. if(!sectors[addr]) break;
  9622. j = __readInt32LE(sectors[addr], jj);
  9623. }
  9624. return {nodes: buf, data:__toBuffer([buf_chain])};
  9625. }
  9626. /** Chase down the sector linked lists */
  9627. function make_sector_list(sectors, dir_start, fat_addrs, ssz) {
  9628. var sl = sectors.length, sector_list = ([]);
  9629. var chkd = [], buf = [], buf_chain = [];
  9630. var modulus = ssz - 1, i=0, j=0, k=0, jj=0;
  9631. for(i=0; i < sl; ++i) {
  9632. buf = ([]);
  9633. k = (i + dir_start); if(k >= sl) k-=sl;
  9634. if(chkd[k]) continue;
  9635. buf_chain = [];
  9636. var seen = [];
  9637. for(j=k; j>=0;) {
  9638. seen[j] = true;
  9639. chkd[j] = true;
  9640. buf[buf.length] = j;
  9641. buf_chain.push(sectors[j]);
  9642. var addr = fat_addrs[Math.floor(j*4/ssz)];
  9643. jj = ((j*4) & modulus);
  9644. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  9645. if(!sectors[addr]) break;
  9646. j = __readInt32LE(sectors[addr], jj);
  9647. if(seen[j]) break;
  9648. }
  9649. sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])});
  9650. }
  9651. return sector_list;
  9652. }
  9653. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  9654. function read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, mini) {
  9655. var minifat_store = 0, pl = (Paths.length?2:0);
  9656. var sector = sector_list[dir_start].data;
  9657. var i = 0, namelen = 0, name;
  9658. for(; i < sector.length; i+= 128) {
  9659. var blob = sector.slice(i, i+128);
  9660. prep_blob(blob, 64);
  9661. namelen = blob.read_shift(2);
  9662. name = __utf16le(blob,0,namelen-pl);
  9663. Paths.push(name);
  9664. var o = ({
  9665. name: name,
  9666. type: blob.read_shift(1),
  9667. color: blob.read_shift(1),
  9668. L: blob.read_shift(4, 'i'),
  9669. R: blob.read_shift(4, 'i'),
  9670. C: blob.read_shift(4, 'i'),
  9671. clsid: blob.read_shift(16),
  9672. state: blob.read_shift(4, 'i'),
  9673. start: 0,
  9674. size: 0
  9675. });
  9676. var ctime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  9677. if(ctime !== 0) o.ct = read_date(blob, blob.l-8);
  9678. var mtime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  9679. if(mtime !== 0) o.mt = read_date(blob, blob.l-8);
  9680. o.start = blob.read_shift(4, 'i');
  9681. o.size = blob.read_shift(4, 'i');
  9682. if(o.size < 0 && o.start < 0) { o.size = o.type = 0; o.start = ENDOFCHAIN; o.name = ""; }
  9683. if(o.type === 5) { /* root */
  9684. minifat_store = o.start;
  9685. if(nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
  9686. /*minifat_size = o.size;*/
  9687. } else if(o.size >= 4096 /* MSCSZ */) {
  9688. o.storage = 'fat';
  9689. if(sector_list[o.start] === undefined) sector_list[o.start] = get_sector_list(sectors, o.start, sector_list.fat_addrs, sector_list.ssz);
  9690. sector_list[o.start].name = o.name;
  9691. o.content = (sector_list[o.start].data.slice(0,o.size));
  9692. } else {
  9693. o.storage = 'minifat';
  9694. if(o.size < 0) o.size = 0;
  9695. else if(minifat_store !== ENDOFCHAIN && o.start !== ENDOFCHAIN && sector_list[minifat_store]) {
  9696. o.content = get_mfat_entry(o, sector_list[minifat_store].data, (sector_list[mini]||{}).data);
  9697. }
  9698. }
  9699. if(o.content) prep_blob(o.content, 0);
  9700. files[name] = o;
  9701. FileIndex.push(o);
  9702. }
  9703. }
  9704. function read_date(blob, offset) {
  9705. return new Date(( ( (__readUInt32LE(blob,offset+4)/1e7)*Math.pow(2,32)+__readUInt32LE(blob,offset)/1e7 ) - 11644473600)*1000);
  9706. }
  9707. function read_file(filename, options) {
  9708. get_fs();
  9709. return parse(fs.readFileSync(filename), options);
  9710. }
  9711. function read(blob, options) {
  9712. switch(options && options.type || "base64") {
  9713. case "file": return read_file(blob, options);
  9714. case "base64": return parse(s2a(Base64.decode(blob)), options);
  9715. case "binary": return parse(s2a(blob), options);
  9716. }
  9717. return parse(blob, options);
  9718. }
  9719. function init_cfb(cfb, opts) {
  9720. var o = opts || {}, root = o.root || "Root Entry";
  9721. if(!cfb.FullPaths) cfb.FullPaths = [];
  9722. if(!cfb.FileIndex) cfb.FileIndex = [];
  9723. if(cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
  9724. if(cfb.FullPaths.length === 0) {
  9725. cfb.FullPaths[0] = root + "/";
  9726. cfb.FileIndex[0] = ({ name: root, type: 5 });
  9727. }
  9728. if(o.CLSID) cfb.FileIndex[0].clsid = o.CLSID;
  9729. seed_cfb(cfb);
  9730. }
  9731. function seed_cfb(cfb) {
  9732. var nm = "\u0001Sh33tJ5";
  9733. if(CFB.find(cfb, "/" + nm)) return;
  9734. var p = new_buf(4); p[0] = 55; p[1] = p[3] = 50; p[2] = 54;
  9735. cfb.FileIndex.push(({ name: nm, type: 2, content:p, size:4, L:69, R:69, C:69 }));
  9736. cfb.FullPaths.push(cfb.FullPaths[0] + nm);
  9737. rebuild_cfb(cfb);
  9738. }
  9739. function rebuild_cfb(cfb, f) {
  9740. init_cfb(cfb);
  9741. var gc = false, s = false;
  9742. for(var i = cfb.FullPaths.length - 1; i >= 0; --i) {
  9743. var _file = cfb.FileIndex[i];
  9744. switch(_file.type) {
  9745. case 0:
  9746. if(s) gc = true;
  9747. else { cfb.FileIndex.pop(); cfb.FullPaths.pop(); }
  9748. break;
  9749. case 1: case 2: case 5:
  9750. s = true;
  9751. if(isNaN(_file.R * _file.L * _file.C)) gc = true;
  9752. if(_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
  9753. break;
  9754. default: gc = true; break;
  9755. }
  9756. }
  9757. if(!gc && !f) return;
  9758. var now = new Date(1987, 1, 19), j = 0;
  9759. var data = [];
  9760. for(i = 0; i < cfb.FullPaths.length; ++i) {
  9761. if(cfb.FileIndex[i].type === 0) continue;
  9762. data.push([cfb.FullPaths[i], cfb.FileIndex[i]]);
  9763. }
  9764. for(i = 0; i < data.length; ++i) {
  9765. var dad = dirname(data[i][0]);
  9766. s = false;
  9767. for(j = 0; j < data.length; ++j) if(data[j][0] === dad) s = true;
  9768. if(!s) data.push([dad, ({
  9769. name: filename(dad).replace("/",""),
  9770. type: 1,
  9771. clsid: HEADER_CLSID,
  9772. ct: now, mt: now,
  9773. content: null
  9774. })]);
  9775. }
  9776. data.sort(function(x,y) { return namecmp(x[0], y[0]); });
  9777. cfb.FullPaths = []; cfb.FileIndex = [];
  9778. for(i = 0; i < data.length; ++i) { cfb.FullPaths[i] = data[i][0]; cfb.FileIndex[i] = data[i][1]; }
  9779. for(i = 0; i < data.length; ++i) {
  9780. var elt = cfb.FileIndex[i];
  9781. var nm = cfb.FullPaths[i];
  9782. elt.name = filename(nm).replace("/","");
  9783. elt.L = elt.R = elt.C = -(elt.color = 1);
  9784. elt.size = elt.content ? elt.content.length : 0;
  9785. elt.start = 0;
  9786. elt.clsid = (elt.clsid || HEADER_CLSID);
  9787. if(i === 0) {
  9788. elt.C = data.length > 1 ? 1 : -1;
  9789. elt.size = 0;
  9790. elt.type = 5;
  9791. } else if(nm.slice(-1) == "/") {
  9792. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==nm) break;
  9793. elt.C = j >= data.length ? -1 : j;
  9794. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==dirname(nm)) break;
  9795. elt.R = j >= data.length ? -1 : j;
  9796. elt.type = 1;
  9797. } else {
  9798. if(dirname(cfb.FullPaths[i+1]||"") == dirname(nm)) elt.R = i + 1;
  9799. elt.type = 2;
  9800. }
  9801. }
  9802. }
  9803. function _write(cfb, options) {
  9804. var _opts = options || {};
  9805. rebuild_cfb(cfb);
  9806. if(_opts.fileType == 'zip') return write_zip(cfb, _opts);
  9807. var L = (function(cfb){
  9808. var mini_size = 0, fat_size = 0;
  9809. for(var i = 0; i < cfb.FileIndex.length; ++i) {
  9810. var file = cfb.FileIndex[i];
  9811. if(!file.content) continue;
  9812. var flen = file.content.length;
  9813. if(flen > 0){
  9814. if(flen < 0x1000) mini_size += (flen + 0x3F) >> 6;
  9815. else fat_size += (flen + 0x01FF) >> 9;
  9816. }
  9817. }
  9818. var dir_cnt = (cfb.FullPaths.length +3) >> 2;
  9819. var mini_cnt = (mini_size + 7) >> 3;
  9820. var mfat_cnt = (mini_size + 0x7F) >> 7;
  9821. var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
  9822. var fat_cnt = (fat_base + 0x7F) >> 7;
  9823. var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  9824. while(((fat_base + fat_cnt + difat_cnt + 0x7F) >> 7) > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  9825. var L = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
  9826. cfb.FileIndex[0].size = mini_size << 6;
  9827. L[7] = (cfb.FileIndex[0].start=L[0]+L[1]+L[2]+L[3]+L[4]+L[5])+((L[6]+7) >> 3);
  9828. return L;
  9829. })(cfb);
  9830. var o = new_buf(L[7] << 9);
  9831. var i = 0, T = 0;
  9832. {
  9833. for(i = 0; i < 8; ++i) o.write_shift(1, HEADER_SIG[i]);
  9834. for(i = 0; i < 8; ++i) o.write_shift(2, 0);
  9835. o.write_shift(2, 0x003E);
  9836. o.write_shift(2, 0x0003);
  9837. o.write_shift(2, 0xFFFE);
  9838. o.write_shift(2, 0x0009);
  9839. o.write_shift(2, 0x0006);
  9840. for(i = 0; i < 3; ++i) o.write_shift(2, 0);
  9841. o.write_shift(4, 0);
  9842. o.write_shift(4, L[2]);
  9843. o.write_shift(4, L[0] + L[1] + L[2] + L[3] - 1);
  9844. o.write_shift(4, 0);
  9845. o.write_shift(4, 1<<12);
  9846. o.write_shift(4, L[3] ? L[0] + L[1] + L[2] - 1: ENDOFCHAIN);
  9847. o.write_shift(4, L[3]);
  9848. o.write_shift(-4, L[1] ? L[0] - 1: ENDOFCHAIN);
  9849. o.write_shift(4, L[1]);
  9850. for(i = 0; i < 109; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  9851. }
  9852. if(L[1]) {
  9853. for(T = 0; T < L[1]; ++T) {
  9854. for(; i < 236 + T * 127; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  9855. o.write_shift(-4, T === L[1] - 1 ? ENDOFCHAIN : T + 1);
  9856. }
  9857. }
  9858. var chainit = function(w) {
  9859. for(T += w; i<T-1; ++i) o.write_shift(-4, i+1);
  9860. if(w) { ++i; o.write_shift(-4, ENDOFCHAIN); }
  9861. };
  9862. T = i = 0;
  9863. for(T+=L[1]; i<T; ++i) o.write_shift(-4, consts.DIFSECT);
  9864. for(T+=L[2]; i<T; ++i) o.write_shift(-4, consts.FATSECT);
  9865. chainit(L[3]);
  9866. chainit(L[4]);
  9867. var j = 0, flen = 0;
  9868. var file = cfb.FileIndex[0];
  9869. for(; j < cfb.FileIndex.length; ++j) {
  9870. file = cfb.FileIndex[j];
  9871. if(!file.content) continue;
  9872. flen = file.content.length;
  9873. if(flen < 0x1000) continue;
  9874. file.start = T;
  9875. chainit((flen + 0x01FF) >> 9);
  9876. }
  9877. chainit((L[6] + 7) >> 3);
  9878. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  9879. T = i = 0;
  9880. for(j = 0; j < cfb.FileIndex.length; ++j) {
  9881. file = cfb.FileIndex[j];
  9882. if(!file.content) continue;
  9883. flen = file.content.length;
  9884. if(!flen || flen >= 0x1000) continue;
  9885. file.start = T;
  9886. chainit((flen + 0x3F) >> 6);
  9887. }
  9888. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  9889. for(i = 0; i < L[4]<<2; ++i) {
  9890. var nm = cfb.FullPaths[i];
  9891. if(!nm || nm.length === 0) {
  9892. for(j = 0; j < 17; ++j) o.write_shift(4, 0);
  9893. for(j = 0; j < 3; ++j) o.write_shift(4, -1);
  9894. for(j = 0; j < 12; ++j) o.write_shift(4, 0);
  9895. continue;
  9896. }
  9897. file = cfb.FileIndex[i];
  9898. if(i === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
  9899. var _nm = (i === 0 && _opts.root) || file.name;
  9900. flen = 2*(_nm.length+1);
  9901. o.write_shift(64, _nm, "utf16le");
  9902. o.write_shift(2, flen);
  9903. o.write_shift(1, file.type);
  9904. o.write_shift(1, file.color);
  9905. o.write_shift(-4, file.L);
  9906. o.write_shift(-4, file.R);
  9907. o.write_shift(-4, file.C);
  9908. if(!file.clsid) for(j = 0; j < 4; ++j) o.write_shift(4, 0);
  9909. else o.write_shift(16, file.clsid, "hex");
  9910. o.write_shift(4, file.state || 0);
  9911. o.write_shift(4, 0); o.write_shift(4, 0);
  9912. o.write_shift(4, 0); o.write_shift(4, 0);
  9913. o.write_shift(4, file.start);
  9914. o.write_shift(4, file.size); o.write_shift(4, 0);
  9915. }
  9916. for(i = 1; i < cfb.FileIndex.length; ++i) {
  9917. file = cfb.FileIndex[i];
  9918. if(file.size >= 0x1000) {
  9919. o.l = (file.start+1) << 9;
  9920. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  9921. for(; j & 0x1FF; ++j) o.write_shift(1, 0);
  9922. }
  9923. }
  9924. for(i = 1; i < cfb.FileIndex.length; ++i) {
  9925. file = cfb.FileIndex[i];
  9926. if(file.size > 0 && file.size < 0x1000) {
  9927. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  9928. for(; j & 0x3F; ++j) o.write_shift(1, 0);
  9929. }
  9930. }
  9931. while(o.l < o.length) o.write_shift(1, 0);
  9932. return o;
  9933. }
  9934. /* [MS-CFB] 2.6.4 (Unicode 3.0.1 case conversion) */
  9935. function find(cfb, path) {
  9936. var UCFullPaths = cfb.FullPaths.map(function(x) { return x.toUpperCase(); });
  9937. var UCPaths = UCFullPaths.map(function(x) { var y = x.split("/"); return y[y.length - (x.slice(-1) == "/" ? 2 : 1)]; });
  9938. var k = false;
  9939. if(path.charCodeAt(0) === 47 /* "/" */) { k = true; path = UCFullPaths[0].slice(0, -1) + path; }
  9940. else k = path.indexOf("/") !== -1;
  9941. var UCPath = path.toUpperCase();
  9942. var w = k === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
  9943. if(w !== -1) return cfb.FileIndex[w];
  9944. var m = !UCPath.match(chr1);
  9945. UCPath = UCPath.replace(chr0,'');
  9946. if(m) UCPath = UCPath.replace(chr1,'!');
  9947. for(w = 0; w < UCFullPaths.length; ++w) {
  9948. if((m ? UCFullPaths[w].replace(chr1,'!') : UCFullPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  9949. if((m ? UCPaths[w].replace(chr1,'!') : UCPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  9950. }
  9951. return null;
  9952. }
  9953. /** CFB Constants */
  9954. var MSSZ = 64; /* Mini Sector Size = 1<<6 */
  9955. //var MSCSZ = 4096; /* Mini Stream Cutoff Size */
  9956. /* 2.1 Compound File Sector Numbers and Types */
  9957. var ENDOFCHAIN = -2;
  9958. /* 2.2 Compound File Header */
  9959. var HEADER_SIGNATURE = 'd0cf11e0a1b11ae1';
  9960. var HEADER_SIG = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
  9961. var HEADER_CLSID = '00000000000000000000000000000000';
  9962. var consts = {
  9963. /* 2.1 Compund File Sector Numbers and Types */
  9964. MAXREGSECT: -6,
  9965. DIFSECT: -4,
  9966. FATSECT: -3,
  9967. ENDOFCHAIN: ENDOFCHAIN,
  9968. FREESECT: -1,
  9969. /* 2.2 Compound File Header */
  9970. HEADER_SIGNATURE: HEADER_SIGNATURE,
  9971. HEADER_MINOR_VERSION: '3e00',
  9972. MAXREGSID: -6,
  9973. NOSTREAM: -1,
  9974. HEADER_CLSID: HEADER_CLSID,
  9975. /* 2.6.1 Compound File Directory Entry */
  9976. EntryTypes: ['unknown','storage','stream','lockbytes','property','root']
  9977. };
  9978. function write_file(cfb, filename, options) {
  9979. get_fs();
  9980. var o = _write(cfb, options);
  9981. fs.writeFileSync(filename, o);
  9982. }
  9983. function a2s(o) {
  9984. var out = new Array(o.length);
  9985. for(var i = 0; i < o.length; ++i) out[i] = String.fromCharCode(o[i]);
  9986. return out.join("");
  9987. }
  9988. function write(cfb, options) {
  9989. var o = _write(cfb, options);
  9990. switch(options && options.type) {
  9991. case "file": get_fs(); fs.writeFileSync(options.filename, (o)); return o;
  9992. case "binary": return a2s(o);
  9993. case "base64": return Base64.encode(a2s(o));
  9994. }
  9995. return o;
  9996. }
  9997. /* node < 8.1 zlib does not expose bytesRead, so default to pure JS */
  9998. var _zlib;
  9999. function use_zlib(zlib) { try {
  10000. var InflateRaw = zlib.InflateRaw;
  10001. var InflRaw = new InflateRaw();
  10002. InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
  10003. if(InflRaw.bytesRead) _zlib = zlib;
  10004. else throw new Error("zlib does not expose bytesRead");
  10005. } catch(e) {console.error("cannot use native zlib: " + (e.message || e)); } }
  10006. function _inflateRawSync(payload, usz) {
  10007. if(!_zlib) return _inflate(payload, usz);
  10008. var InflateRaw = _zlib.InflateRaw;
  10009. var InflRaw = new InflateRaw();
  10010. var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
  10011. payload.l += InflRaw.bytesRead;
  10012. return out;
  10013. }
  10014. function _deflateRawSync(payload) {
  10015. return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
  10016. }
  10017. var CLEN_ORDER = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  10018. /* LEN_ID = [ 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285 ]; */
  10019. var LEN_LN = [ 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 ];
  10020. /* DST_ID = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 ]; */
  10021. var DST_LN = [ 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 ];
  10022. function bit_swap_8(n) { var t = (((((n<<1)|(n<<11)) & 0x22110) | (((n<<5)|(n<<15)) & 0x88440))); return ((t>>16) | (t>>8) |t)&0xFF; }
  10023. var use_typed_arrays = typeof Uint8Array !== 'undefined';
  10024. var bitswap8 = use_typed_arrays ? new Uint8Array(1<<8) : [];
  10025. for(var q = 0; q < (1<<8); ++q) bitswap8[q] = bit_swap_8(q);
  10026. function bit_swap_n(n, b) {
  10027. var rev = bitswap8[n & 0xFF];
  10028. if(b <= 8) return rev >>> (8-b);
  10029. rev = (rev << 8) | bitswap8[(n>>8)&0xFF];
  10030. if(b <= 16) return rev >>> (16-b);
  10031. rev = (rev << 8) | bitswap8[(n>>16)&0xFF];
  10032. return rev >>> (24-b);
  10033. }
  10034. /* helpers for unaligned bit reads */
  10035. function read_bits_2(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 6 ? 0 : buf[h+1]<<8))>>>w)& 0x03; }
  10036. function read_bits_3(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 5 ? 0 : buf[h+1]<<8))>>>w)& 0x07; }
  10037. function read_bits_4(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 4 ? 0 : buf[h+1]<<8))>>>w)& 0x0F; }
  10038. function read_bits_5(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 3 ? 0 : buf[h+1]<<8))>>>w)& 0x1F; }
  10039. function read_bits_7(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 1 ? 0 : buf[h+1]<<8))>>>w)& 0x7F; }
  10040. /* works up to n = 3 * 8 + 1 = 25 */
  10041. function read_bits_n(buf, bl, n) {
  10042. var w = (bl&7), h = (bl>>>3), f = ((1<<n)-1);
  10043. var v = buf[h] >>> w;
  10044. if(n < 8 - w) return v & f;
  10045. v |= buf[h+1]<<(8-w);
  10046. if(n < 16 - w) return v & f;
  10047. v |= buf[h+2]<<(16-w);
  10048. if(n < 24 - w) return v & f;
  10049. v |= buf[h+3]<<(24-w);
  10050. return v & f;
  10051. }
  10052. /* until ArrayBuffer#realloc is a thing, fake a realloc */
  10053. function realloc(b, sz) {
  10054. var L = b.length, M = 2*L > sz ? 2*L : sz + 5, i = 0;
  10055. if(L >= sz) return b;
  10056. if(has_buf) {
  10057. var o = new_unsafe_buf(M);
  10058. // $FlowIgnore
  10059. if(b.copy) b.copy(o);
  10060. else for(; i < b.length; ++i) o[i] = b[i];
  10061. return o;
  10062. } else if(use_typed_arrays) {
  10063. var a = new Uint8Array(M);
  10064. if(a.set) a.set(b);
  10065. else for(; i < b.length; ++i) a[i] = b[i];
  10066. return a;
  10067. }
  10068. b.length = M;
  10069. return b;
  10070. }
  10071. /* zero-filled arrays for older browsers */
  10072. function zero_fill_array(n) {
  10073. var o = new Array(n);
  10074. for(var i = 0; i < n; ++i) o[i] = 0;
  10075. return o;
  10076. }var _deflate = (function() {
  10077. var _deflateRaw = (function() {
  10078. return function deflateRaw(data, out) {
  10079. var boff = 0;
  10080. while(boff < data.length) {
  10081. var L = Math.min(0xFFFF, data.length - boff);
  10082. var h = boff + L == data.length;
  10083. /* TODO: this is only type 0 stored */
  10084. out.write_shift(1, +h);
  10085. out.write_shift(2, L);
  10086. out.write_shift(2, (~L) & 0xFFFF);
  10087. while(L-- > 0) out[out.l++] = data[boff++];
  10088. }
  10089. return out.l;
  10090. };
  10091. })();
  10092. return function(data) {
  10093. var buf = new_buf(50+Math.floor(data.length*1.1));
  10094. var off = _deflateRaw(data, buf);
  10095. return buf.slice(0, off);
  10096. };
  10097. })();
  10098. /* modified inflate function also moves original read head */
  10099. /* build tree (used for literals and lengths) */
  10100. function build_tree(clens, cmap, MAX) {
  10101. var maxlen = 1, w = 0, i = 0, j = 0, ccode = 0, L = clens.length;
  10102. var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  10103. for(i = 0; i < 32; ++i) bl_count[i] = 0;
  10104. for(i = L; i < MAX; ++i) clens[i] = 0;
  10105. L = clens.length;
  10106. var ctree = use_typed_arrays ? new Uint16Array(L) : zero_fill_array(L); // []
  10107. /* build code tree */
  10108. for(i = 0; i < L; ++i) {
  10109. bl_count[(w = clens[i])]++;
  10110. if(maxlen < w) maxlen = w;
  10111. ctree[i] = 0;
  10112. }
  10113. bl_count[0] = 0;
  10114. for(i = 1; i <= maxlen; ++i) bl_count[i+16] = (ccode = (ccode + bl_count[i-1])<<1);
  10115. for(i = 0; i < L; ++i) {
  10116. ccode = clens[i];
  10117. if(ccode != 0) ctree[i] = bl_count[ccode+16]++;
  10118. }
  10119. /* cmap[maxlen + 4 bits] = (off&15) + (lit<<4) reverse mapping */
  10120. var cleni = 0;
  10121. for(i = 0; i < L; ++i) {
  10122. cleni = clens[i];
  10123. if(cleni != 0) {
  10124. ccode = bit_swap_n(ctree[i], maxlen)>>(maxlen-cleni);
  10125. for(j = (1<<(maxlen + 4 - cleni)) - 1; j>=0; --j)
  10126. cmap[ccode|(j<<cleni)] = (cleni&15) | (i<<4);
  10127. }
  10128. }
  10129. return maxlen;
  10130. }
  10131. var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
  10132. var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  10133. if(!use_typed_arrays) {
  10134. for(var i = 0; i < 512; ++i) fix_lmap[i] = 0;
  10135. for(i = 0; i < 32; ++i) fix_dmap[i] = 0;
  10136. }
  10137. (function() {
  10138. var dlens = [];
  10139. var i = 0;
  10140. for(;i<32; i++) dlens.push(5);
  10141. build_tree(dlens, fix_dmap, 32);
  10142. var clens = [];
  10143. i = 0;
  10144. for(; i<=143; i++) clens.push(8);
  10145. for(; i<=255; i++) clens.push(9);
  10146. for(; i<=279; i++) clens.push(7);
  10147. for(; i<=287; i++) clens.push(8);
  10148. build_tree(clens, fix_lmap, 288);
  10149. })();
  10150. var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  10151. var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  10152. var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128);
  10153. var dyn_len_1 = 1, dyn_len_2 = 1;
  10154. /* 5.5.3 Expanding Huffman Codes */
  10155. function dyn(data, boff) {
  10156. /* nomenclature from RFC1951 refers to bit values; these are offset by the implicit constant */
  10157. var _HLIT = read_bits_5(data, boff) + 257; boff += 5;
  10158. var _HDIST = read_bits_5(data, boff) + 1; boff += 5;
  10159. var _HCLEN = read_bits_4(data, boff) + 4; boff += 4;
  10160. var w = 0;
  10161. /* grab and store code lengths */
  10162. var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
  10163. var ctree = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
  10164. var maxlen = 1;
  10165. var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  10166. var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  10167. var L = clens.length; /* 19 */
  10168. for(var i = 0; i < _HCLEN; ++i) {
  10169. clens[CLEN_ORDER[i]] = w = read_bits_3(data, boff);
  10170. if(maxlen < w) maxlen = w;
  10171. bl_count[w]++;
  10172. boff += 3;
  10173. }
  10174. /* build code tree */
  10175. var ccode = 0;
  10176. bl_count[0] = 0;
  10177. for(i = 1; i <= maxlen; ++i) next_code[i] = ccode = (ccode + bl_count[i-1])<<1;
  10178. for(i = 0; i < L; ++i) if((ccode = clens[i]) != 0) ctree[i] = next_code[ccode]++;
  10179. /* cmap[7 bits from stream] = (off&7) + (lit<<3) */
  10180. var cleni = 0;
  10181. for(i = 0; i < L; ++i) {
  10182. cleni = clens[i];
  10183. if(cleni != 0) {
  10184. ccode = bitswap8[ctree[i]]>>(8-cleni);
  10185. for(var j = (1<<(7-cleni))-1; j>=0; --j) dyn_cmap[ccode|(j<<cleni)] = (cleni&7) | (i<<3);
  10186. }
  10187. }
  10188. /* read literal and dist codes at once */
  10189. var hcodes = [];
  10190. maxlen = 1;
  10191. for(; hcodes.length < _HLIT + _HDIST;) {
  10192. ccode = dyn_cmap[read_bits_7(data, boff)];
  10193. boff += ccode & 7;
  10194. switch((ccode >>>= 3)) {
  10195. case 16:
  10196. w = 3 + read_bits_2(data, boff); boff += 2;
  10197. ccode = hcodes[hcodes.length - 1];
  10198. while(w-- > 0) hcodes.push(ccode);
  10199. break;
  10200. case 17:
  10201. w = 3 + read_bits_3(data, boff); boff += 3;
  10202. while(w-- > 0) hcodes.push(0);
  10203. break;
  10204. case 18:
  10205. w = 11 + read_bits_7(data, boff); boff += 7;
  10206. while(w -- > 0) hcodes.push(0);
  10207. break;
  10208. default:
  10209. hcodes.push(ccode);
  10210. if(maxlen < ccode) maxlen = ccode;
  10211. break;
  10212. }
  10213. }
  10214. /* build literal / length trees */
  10215. var h1 = hcodes.slice(0, _HLIT), h2 = hcodes.slice(_HLIT);
  10216. for(i = _HLIT; i < 286; ++i) h1[i] = 0;
  10217. for(i = _HDIST; i < 30; ++i) h2[i] = 0;
  10218. dyn_len_1 = build_tree(h1, dyn_lmap, 286);
  10219. dyn_len_2 = build_tree(h2, dyn_dmap, 30);
  10220. return boff;
  10221. }
  10222. /* return [ data, bytesRead ] */
  10223. function inflate(data, usz) {
  10224. /* shortcircuit for empty buffer [0x03, 0x00] */
  10225. if(data[0] == 3 && !(data[1] & 0x3)) { return [new_raw_buf(usz), 2]; }
  10226. /* bit offset */
  10227. var boff = 0;
  10228. /* header includes final bit and type bits */
  10229. var header = 0;
  10230. var outbuf = new_unsafe_buf(usz ? usz : (1<<18));
  10231. var woff = 0;
  10232. var OL = outbuf.length>>>0;
  10233. var max_len_1 = 0, max_len_2 = 0;
  10234. while((header&1) == 0) {
  10235. header = read_bits_3(data, boff); boff += 3;
  10236. if((header >>> 1) == 0) {
  10237. /* Stored block */
  10238. if(boff & 7) boff += 8 - (boff&7);
  10239. /* 2 bytes sz, 2 bytes bit inverse */
  10240. var sz = data[boff>>>3] | data[(boff>>>3)+1]<<8;
  10241. boff += 32;
  10242. /* push sz bytes */
  10243. if(!usz && OL < woff + sz) { outbuf = realloc(outbuf, woff + sz); OL = outbuf.length; }
  10244. if(typeof data.copy === 'function') {
  10245. // $FlowIgnore
  10246. data.copy(outbuf, woff, boff>>>3, (boff>>>3)+sz);
  10247. woff += sz; boff += 8*sz;
  10248. } else while(sz-- > 0) { outbuf[woff++] = data[boff>>>3]; boff += 8; }
  10249. continue;
  10250. } else if((header >>> 1) == 1) {
  10251. /* Fixed Huffman */
  10252. max_len_1 = 9; max_len_2 = 5;
  10253. } else {
  10254. /* Dynamic Huffman */
  10255. boff = dyn(data, boff);
  10256. max_len_1 = dyn_len_1; max_len_2 = dyn_len_2;
  10257. }
  10258. if(!usz && (OL < woff + 32767)) { outbuf = realloc(outbuf, woff + 32767); OL = outbuf.length; }
  10259. for(;;) { // while(true) is apparently out of vogue in modern JS circles
  10260. /* ingest code and move read head */
  10261. var bits = read_bits_n(data, boff, max_len_1);
  10262. var code = (header>>>1) == 1 ? fix_lmap[bits] : dyn_lmap[bits];
  10263. boff += code & 15; code >>>= 4;
  10264. /* 0-255 are literals, 256 is end of block token, 257+ are copy tokens */
  10265. if(((code>>>8)&0xFF) === 0) outbuf[woff++] = code;
  10266. else if(code == 256) break;
  10267. else {
  10268. code -= 257;
  10269. var len_eb = (code < 8) ? 0 : ((code-4)>>2); if(len_eb > 5) len_eb = 0;
  10270. var tgt = woff + LEN_LN[code];
  10271. /* length extra bits */
  10272. if(len_eb > 0) {
  10273. tgt += read_bits_n(data, boff, len_eb);
  10274. boff += len_eb;
  10275. }
  10276. /* dist code */
  10277. bits = read_bits_n(data, boff, max_len_2);
  10278. code = (header>>>1) == 1 ? fix_dmap[bits] : dyn_dmap[bits];
  10279. boff += code & 15; code >>>= 4;
  10280. var dst_eb = (code < 4 ? 0 : (code-2)>>1);
  10281. var dst = DST_LN[code];
  10282. /* dist extra bits */
  10283. if(dst_eb > 0) {
  10284. dst += read_bits_n(data, boff, dst_eb);
  10285. boff += dst_eb;
  10286. }
  10287. /* in the common case, manual byte copy is faster than TA set / Buffer copy */
  10288. if(!usz && OL < tgt) { outbuf = realloc(outbuf, tgt); OL = outbuf.length; }
  10289. while(woff < tgt) { outbuf[woff] = outbuf[woff - dst]; ++woff; }
  10290. }
  10291. }
  10292. }
  10293. return [usz ? outbuf : outbuf.slice(0, woff), (boff+7)>>>3];
  10294. }
  10295. function _inflate(payload, usz) {
  10296. var data = payload.slice(payload.l||0);
  10297. var out = inflate(data, usz);
  10298. payload.l += out[1];
  10299. return out[0];
  10300. }
  10301. function warn_or_throw(wrn, msg) {
  10302. if(wrn) { if(typeof console !== 'undefined') console.error(msg); }
  10303. else throw new Error(msg);
  10304. }
  10305. function parse_zip(file, options) {
  10306. var blob = file;
  10307. prep_blob(blob, 0);
  10308. var FileIndex = [], FullPaths = [];
  10309. var o = {
  10310. FileIndex: FileIndex,
  10311. FullPaths: FullPaths
  10312. };
  10313. init_cfb(o, { root: options.root });
  10314. /* find end of central directory, start just after signature */
  10315. var i = blob.length - 4;
  10316. while((blob[i] != 0x50 || blob[i+1] != 0x4b || blob[i+2] != 0x05 || blob[i+3] != 0x06) && i >= 0) --i;
  10317. blob.l = i + 4;
  10318. /* parse end of central directory */
  10319. blob.l += 4;
  10320. var fcnt = blob.read_shift(2);
  10321. blob.l += 6;
  10322. var start_cd = blob.read_shift(4);
  10323. /* parse central directory */
  10324. blob.l = start_cd;
  10325. for(i = 0; i < fcnt; ++i) {
  10326. /* trust local file header instead of CD entry */
  10327. blob.l += 20;
  10328. var csz = blob.read_shift(4);
  10329. var usz = blob.read_shift(4);
  10330. var namelen = blob.read_shift(2);
  10331. var efsz = blob.read_shift(2);
  10332. var fcsz = blob.read_shift(2);
  10333. blob.l += 8;
  10334. var offset = blob.read_shift(4);
  10335. var EF = parse_extra_field(blob.slice(blob.l+namelen, blob.l+namelen+efsz));
  10336. blob.l += namelen + efsz + fcsz;
  10337. var L = blob.l;
  10338. blob.l = offset + 4;
  10339. parse_local_file(blob, csz, usz, o, EF);
  10340. blob.l = L;
  10341. }
  10342. return o;
  10343. }
  10344. /* head starts just after local file header signature */
  10345. function parse_local_file(blob, csz, usz, o, EF) {
  10346. /* [local file header] */
  10347. blob.l += 2;
  10348. var flags = blob.read_shift(2);
  10349. var meth = blob.read_shift(2);
  10350. var date = parse_dos_date(blob);
  10351. if(flags & 0x2041) throw new Error("Unsupported ZIP encryption");
  10352. var crc32 = blob.read_shift(4);
  10353. var _csz = blob.read_shift(4);
  10354. var _usz = blob.read_shift(4);
  10355. var namelen = blob.read_shift(2);
  10356. var efsz = blob.read_shift(2);
  10357. // TODO: flags & (1<<11) // UTF8
  10358. var name = ""; for(var i = 0; i < namelen; ++i) name += String.fromCharCode(blob[blob.l++]);
  10359. if(efsz) {
  10360. var ef = parse_extra_field(blob.slice(blob.l, blob.l + efsz));
  10361. if((ef[0x5455]||{}).mt) date = ef[0x5455].mt;
  10362. if(((EF||{})[0x5455]||{}).mt) date = EF[0x5455].mt;
  10363. }
  10364. blob.l += efsz;
  10365. /* [encryption header] */
  10366. /* [file data] */
  10367. var data = blob.slice(blob.l, blob.l + _csz);
  10368. switch(meth) {
  10369. case 8: data = _inflateRawSync(blob, _usz); break;
  10370. case 0: break;
  10371. default: throw new Error("Unsupported ZIP Compression method " + meth);
  10372. }
  10373. /* [data descriptor] */
  10374. var wrn = false;
  10375. if(flags & 8) {
  10376. crc32 = blob.read_shift(4);
  10377. if(crc32 == 0x08074b50) { crc32 = blob.read_shift(4); wrn = true; }
  10378. _csz = blob.read_shift(4);
  10379. _usz = blob.read_shift(4);
  10380. }
  10381. if(_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
  10382. if(_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
  10383. var _crc32 = CRC32.buf(data, 0);
  10384. if((crc32>>0) != (_crc32>>0)) warn_or_throw(wrn, "Bad CRC32 checksum: " + crc32 + " != " + _crc32);
  10385. cfb_add(o, name, data, {unsafe: true, mt: date});
  10386. }
  10387. function write_zip(cfb, options) {
  10388. var _opts = options || {};
  10389. var out = [], cdirs = [];
  10390. var o = new_buf(1);
  10391. var method = (_opts.compression ? 8 : 0), flags = 0;
  10392. var desc = false;
  10393. if(desc) flags |= 8;
  10394. var i = 0, j = 0;
  10395. var start_cd = 0, fcnt = 0;
  10396. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  10397. var crcs = [];
  10398. var sz_cd = 0;
  10399. for(i = 1; i < cfb.FullPaths.length; ++i) {
  10400. fp = cfb.FullPaths[i].slice(root.length); fi = cfb.FileIndex[i];
  10401. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  10402. var start = start_cd;
  10403. /* TODO: CP437 filename */
  10404. var namebuf = new_buf(fp.length);
  10405. for(j = 0; j < fp.length; ++j) namebuf.write_shift(1, fp.charCodeAt(j) & 0x7F);
  10406. namebuf = namebuf.slice(0, namebuf.l);
  10407. crcs[fcnt] = CRC32.buf(fi.content, 0);
  10408. var outbuf = fi.content;
  10409. if(method == 8) outbuf = _deflateRawSync(outbuf);
  10410. /* local file header */
  10411. o = new_buf(30);
  10412. o.write_shift(4, 0x04034b50);
  10413. o.write_shift(2, 20);
  10414. o.write_shift(2, flags);
  10415. o.write_shift(2, method);
  10416. /* TODO: last mod file time/date */
  10417. if(fi.mt) write_dos_date(o, fi.mt);
  10418. else o.write_shift(4, 0);
  10419. o.write_shift(-4, (flags & 8) ? 0 : crcs[fcnt]);
  10420. o.write_shift(4, (flags & 8) ? 0 : outbuf.length);
  10421. o.write_shift(4, (flags & 8) ? 0 : fi.content.length);
  10422. o.write_shift(2, namebuf.length);
  10423. o.write_shift(2, 0);
  10424. start_cd += o.length;
  10425. out.push(o);
  10426. start_cd += namebuf.length;
  10427. out.push(namebuf);
  10428. /* TODO: encryption header ? */
  10429. start_cd += outbuf.length;
  10430. out.push(outbuf);
  10431. /* data descriptor */
  10432. if(flags & 8) {
  10433. o = new_buf(12);
  10434. o.write_shift(-4, crcs[fcnt]);
  10435. o.write_shift(4, outbuf.length);
  10436. o.write_shift(4, fi.content.length);
  10437. start_cd += o.l;
  10438. out.push(o);
  10439. }
  10440. /* central directory */
  10441. o = new_buf(46);
  10442. o.write_shift(4, 0x02014b50);
  10443. o.write_shift(2, 0);
  10444. o.write_shift(2, 20);
  10445. o.write_shift(2, flags);
  10446. o.write_shift(2, method);
  10447. o.write_shift(4, 0); /* TODO: last mod file time/date */
  10448. o.write_shift(-4, crcs[fcnt]);
  10449. o.write_shift(4, outbuf.length);
  10450. o.write_shift(4, fi.content.length);
  10451. o.write_shift(2, namebuf.length);
  10452. o.write_shift(2, 0);
  10453. o.write_shift(2, 0);
  10454. o.write_shift(2, 0);
  10455. o.write_shift(2, 0);
  10456. o.write_shift(4, 0);
  10457. o.write_shift(4, start);
  10458. sz_cd += o.l;
  10459. cdirs.push(o);
  10460. sz_cd += namebuf.length;
  10461. cdirs.push(namebuf);
  10462. ++fcnt;
  10463. }
  10464. /* end of central directory */
  10465. o = new_buf(22);
  10466. o.write_shift(4, 0x06054b50);
  10467. o.write_shift(2, 0);
  10468. o.write_shift(2, 0);
  10469. o.write_shift(2, fcnt);
  10470. o.write_shift(2, fcnt);
  10471. o.write_shift(4, sz_cd);
  10472. o.write_shift(4, start_cd);
  10473. o.write_shift(2, 0);
  10474. return bconcat(([bconcat((out)), bconcat(cdirs), o]));
  10475. }
  10476. function cfb_new(opts) {
  10477. var o = ({});
  10478. init_cfb(o, opts);
  10479. return o;
  10480. }
  10481. function cfb_add(cfb, name, content, opts) {
  10482. var unsafe = opts && opts.unsafe;
  10483. if(!unsafe) init_cfb(cfb);
  10484. var file = !unsafe && CFB.find(cfb, name);
  10485. if(!file) {
  10486. var fpath = cfb.FullPaths[0];
  10487. if(name.slice(0, fpath.length) == fpath) fpath = name;
  10488. else {
  10489. if(fpath.slice(-1) != "/") fpath += "/";
  10490. fpath = (fpath + name).replace("//","/");
  10491. }
  10492. file = ({name: filename(name), type: 2});
  10493. cfb.FileIndex.push(file);
  10494. cfb.FullPaths.push(fpath);
  10495. if(!unsafe) CFB.utils.cfb_gc(cfb);
  10496. }
  10497. file.content = (content);
  10498. file.size = content ? content.length : 0;
  10499. if(opts) {
  10500. if(opts.CLSID) file.clsid = opts.CLSID;
  10501. if(opts.mt) file.mt = opts.mt;
  10502. if(opts.ct) file.ct = opts.ct;
  10503. }
  10504. return file;
  10505. }
  10506. function cfb_del(cfb, name) {
  10507. init_cfb(cfb);
  10508. var file = CFB.find(cfb, name);
  10509. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  10510. cfb.FileIndex.splice(j, 1);
  10511. cfb.FullPaths.splice(j, 1);
  10512. return true;
  10513. }
  10514. return false;
  10515. }
  10516. function cfb_mov(cfb, old_name, new_name) {
  10517. init_cfb(cfb);
  10518. var file = CFB.find(cfb, old_name);
  10519. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  10520. cfb.FileIndex[j].name = filename(new_name);
  10521. cfb.FullPaths[j] = new_name;
  10522. return true;
  10523. }
  10524. return false;
  10525. }
  10526. function cfb_gc(cfb) { rebuild_cfb(cfb, true); }
  10527. exports.find = find;
  10528. exports.read = read;
  10529. exports.parse = parse;
  10530. exports.write = write;
  10531. exports.writeFile = write_file;
  10532. exports.utils = {
  10533. cfb_new: cfb_new,
  10534. cfb_add: cfb_add,
  10535. cfb_del: cfb_del,
  10536. cfb_mov: cfb_mov,
  10537. cfb_gc: cfb_gc,
  10538. ReadShift: ReadShift,
  10539. CheckField: CheckField,
  10540. prep_blob: prep_blob,
  10541. bconcat: bconcat,
  10542. use_zlib: use_zlib,
  10543. _deflateRaw: _deflate,
  10544. _inflateRaw: _inflate,
  10545. consts: consts
  10546. };
  10547. return exports;
  10548. })();
  10549. if(typeof require !== 'undefined' && typeof module !== 'undefined' && typeof DO_NOT_EXPORT_CFB === 'undefined') { module.exports = CFB; }
  10550. var _fs;
  10551. if(typeof require !== 'undefined') try { _fs = require('fs'); } catch(e) {}
  10552. /* normalize data for blob ctor */
  10553. function blobify(data) {
  10554. if(typeof data === "string") return s2ab(data);
  10555. if(Array.isArray(data)) return a2u(data);
  10556. return data;
  10557. }
  10558. /* write or download file */
  10559. function write_dl(fname, payload, enc) {
  10560. /*global IE_SaveFile, Blob, navigator, saveAs, document, File, chrome */
  10561. if(typeof _fs !== 'undefined' && _fs.writeFileSync) return enc ? _fs.writeFileSync(fname, payload, enc) : _fs.writeFileSync(fname, payload);
  10562. var data = (enc == "utf8") ? utf8write(payload) : payload;
  10563. if(typeof IE_SaveFile !== 'undefined') return IE_SaveFile(data, fname);
  10564. if(typeof Blob !== 'undefined') {
  10565. var blob = new Blob([blobify(data)], {type:"application/octet-stream"});
  10566. if(typeof navigator !== 'undefined' && navigator.msSaveBlob) return navigator.msSaveBlob(blob, fname);
  10567. if(typeof saveAs !== 'undefined') return saveAs(blob, fname);
  10568. if(typeof URL !== 'undefined' && typeof document !== 'undefined' && document.createElement && URL.createObjectURL) {
  10569. var url = URL.createObjectURL(blob);
  10570. if(typeof chrome === 'object' && typeof (chrome.downloads||{}).download == "function") {
  10571. if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
  10572. return chrome.downloads.download({ url: url, filename: fname, saveAs: true});
  10573. }
  10574. var a = document.createElement("a");
  10575. if(a.download != null) {
  10576. a.download = fname; a.href = url; document.body.appendChild(a); a.click();
  10577. document.body.removeChild(a);
  10578. if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
  10579. return url;
  10580. }
  10581. }
  10582. }
  10583. // $FlowIgnore
  10584. if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
  10585. // $FlowIgnore
  10586. var out = File(fname); out.open("w"); out.encoding = "binary";
  10587. if(Array.isArray(payload)) payload = a2s(payload);
  10588. out.write(payload); out.close(); return payload;
  10589. } catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
  10590. throw new Error("cannot save file " + fname);
  10591. }
  10592. /* read binary data from file */
  10593. function read_binary(path) {
  10594. if(typeof _fs !== 'undefined') return _fs.readFileSync(path);
  10595. // $FlowIgnore
  10596. if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
  10597. // $FlowIgnore
  10598. var infile = File(path); infile.open("r"); infile.encoding = "binary";
  10599. var data = infile.read(); infile.close();
  10600. return data;
  10601. } catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
  10602. throw new Error("Cannot access file " + path);
  10603. }
  10604. function keys(o) {
  10605. var ks = Object.keys(o), o2 = [];
  10606. for(var i = 0; i < ks.length; ++i) if(Object.prototype.hasOwnProperty.call(o, ks[i])) o2.push(ks[i]);
  10607. return o2;
  10608. }
  10609. function evert_key(obj, key) {
  10610. var o = ([]), K = keys(obj);
  10611. for(var i = 0; i !== K.length; ++i) if(o[obj[K[i]][key]] == null) o[obj[K[i]][key]] = K[i];
  10612. return o;
  10613. }
  10614. function evert(obj) {
  10615. var o = ([]), K = keys(obj);
  10616. for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = K[i];
  10617. return o;
  10618. }
  10619. function evert_num(obj) {
  10620. var o = ([]), K = keys(obj);
  10621. for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = parseInt(K[i],10);
  10622. return o;
  10623. }
  10624. function evert_arr(obj) {
  10625. var o = ([]), K = keys(obj);
  10626. for(var i = 0; i !== K.length; ++i) {
  10627. if(o[obj[K[i]]] == null) o[obj[K[i]]] = [];
  10628. o[obj[K[i]]].push(K[i]);
  10629. }
  10630. return o;
  10631. }
  10632. var basedate = new Date(1899, 11, 30, 0, 0, 0); // 2209161600000
  10633. function datenum(v, date1904) {
  10634. var epoch = v.getTime();
  10635. if(date1904) epoch -= 1462*24*60*60*1000;
  10636. var dnthresh = basedate.getTime() + (v.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
  10637. return (epoch - dnthresh) / (24 * 60 * 60 * 1000);
  10638. }
  10639. var refdate = new Date();
  10640. var dnthresh = basedate.getTime() + (refdate.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
  10641. var refoffset = refdate.getTimezoneOffset();
  10642. function numdate(v) {
  10643. var out = new Date();
  10644. out.setTime(v * 24 * 60 * 60 * 1000 + dnthresh);
  10645. if (out.getTimezoneOffset() !== refoffset) {
  10646. out.setTime(out.getTime() + (out.getTimezoneOffset() - refoffset) * 60000);
  10647. }
  10648. return out;
  10649. }
  10650. /* ISO 8601 Duration */
  10651. function parse_isodur(s) {
  10652. var sec = 0, mt = 0, time = false;
  10653. var m = s.match(/P([0-9\.]+Y)?([0-9\.]+M)?([0-9\.]+D)?T([0-9\.]+H)?([0-9\.]+M)?([0-9\.]+S)?/);
  10654. if(!m) throw new Error("|" + s + "| is not an ISO8601 Duration");
  10655. for(var i = 1; i != m.length; ++i) {
  10656. if(!m[i]) continue;
  10657. mt = 1;
  10658. if(i > 3) time = true;
  10659. switch(m[i].slice(m[i].length-1)) {
  10660. case 'Y':
  10661. throw new Error("Unsupported ISO Duration Field: " + m[i].slice(m[i].length-1));
  10662. case 'D': mt *= 24;
  10663. /* falls through */
  10664. case 'H': mt *= 60;
  10665. /* falls through */
  10666. case 'M':
  10667. if(!time) throw new Error("Unsupported ISO Duration Field: M");
  10668. else mt *= 60;
  10669. /* falls through */
  10670. case 'S': break;
  10671. }
  10672. sec += mt * parseInt(m[i], 10);
  10673. }
  10674. return sec;
  10675. }
  10676. var good_pd_date = new Date('2017-02-19T19:06:09.000Z');
  10677. if(isNaN(good_pd_date.getFullYear())) good_pd_date = new Date('2/19/17');
  10678. var good_pd = good_pd_date.getFullYear() == 2017;
  10679. /* parses a date as a local date */
  10680. function parseDate(str, fixdate) {
  10681. var d = new Date(str);
  10682. if(good_pd) {
  10683. if(fixdate > 0) d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
  10684. else if(fixdate < 0) d.setTime(d.getTime() - d.getTimezoneOffset() * 60 * 1000);
  10685. return d;
  10686. }
  10687. if(str instanceof Date) return str;
  10688. if(good_pd_date.getFullYear() == 1917 && !isNaN(d.getFullYear())) {
  10689. var s = d.getFullYear();
  10690. if(str.indexOf("" + s) > -1) return d;
  10691. d.setFullYear(d.getFullYear() + 100); return d;
  10692. }
  10693. var n = str.match(/\d+/g)||["2017","2","19","0","0","0"];
  10694. var out = new Date(+n[0], +n[1] - 1, +n[2], (+n[3]||0), (+n[4]||0), (+n[5]||0));
  10695. if(str.indexOf("Z") > -1) out = new Date(out.getTime() - out.getTimezoneOffset() * 60 * 1000);
  10696. return out;
  10697. }
  10698. function cc2str(arr) {
  10699. var o = "";
  10700. for(var i = 0; i != arr.length; ++i) o += String.fromCharCode(arr[i]);
  10701. return o;
  10702. }
  10703. function dup(o) {
  10704. if(typeof JSON != 'undefined' && !Array.isArray(o)) return JSON.parse(JSON.stringify(o));
  10705. if(typeof o != 'object' || o == null) return o;
  10706. if(o instanceof Date) return new Date(o.getTime());
  10707. var out = {};
  10708. for(var k in o) if(Object.prototype.hasOwnProperty.call(o, k)) out[k] = dup(o[k]);
  10709. return out;
  10710. }
  10711. function fill(c,l) { var o = ""; while(o.length < l) o+=c; return o; }
  10712. /* TODO: stress test */
  10713. function fuzzynum(s) {
  10714. var v = Number(s);
  10715. if(!isNaN(v)) return v;
  10716. if(!/\d/.test(s)) return v;
  10717. var wt = 1;
  10718. var ss = s.replace(/([\d]),([\d])/g,"$1$2").replace(/[$]/g,"").replace(/[%]/g, function() { wt *= 100; return "";});
  10719. if(!isNaN(v = Number(ss))) return v / wt;
  10720. ss = ss.replace(/[(](.*)[)]/,function($$, $1) { wt = -wt; return $1;});
  10721. if(!isNaN(v = Number(ss))) return v / wt;
  10722. return v;
  10723. }
  10724. function fuzzydate(s) {
  10725. var o = new Date(s), n = new Date(NaN);
  10726. var y = o.getYear(), m = o.getMonth(), d = o.getDate();
  10727. if(isNaN(d)) return n;
  10728. if(y < 0 || y > 8099) return n;
  10729. if((m > 0 || d > 1) && y != 101) return o;
  10730. if(s.toLowerCase().match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/)) return o;
  10731. if(s.match(/[^-0-9:,\/\\]/)) return n;
  10732. return o;
  10733. }
  10734. var safe_split_regex = "abacaba".split(/(:?b)/i).length == 5;
  10735. function split_regex(str, re, def) {
  10736. if(safe_split_regex || typeof re == "string") return str.split(re);
  10737. var p = str.split(re), o = [p[0]];
  10738. for(var i = 1; i < p.length; ++i) { o.push(def); o.push(p[i]); }
  10739. return o;
  10740. }
  10741. function getdatastr(data) {
  10742. if(!data) return null;
  10743. if(data.data) return debom(data.data);
  10744. if(data.asNodeBuffer && has_buf) return debom(data.asNodeBuffer().toString('binary'));
  10745. if(data.asBinary) return debom(data.asBinary());
  10746. if(data._data && data._data.getContent) return debom(cc2str(Array.prototype.slice.call(data._data.getContent(),0)));
  10747. if(data.content && data.type) return debom(cc2str(data.content));
  10748. return null;
  10749. }
  10750. function getdatabin(data) {
  10751. if(!data) return null;
  10752. if(data.data) return char_codes(data.data);
  10753. if(data.asNodeBuffer && has_buf) return data.asNodeBuffer();
  10754. if(data._data && data._data.getContent) {
  10755. var o = data._data.getContent();
  10756. if(typeof o == "string") return char_codes(o);
  10757. return Array.prototype.slice.call(o);
  10758. }
  10759. if(data.content && data.type) return data.content;
  10760. return null;
  10761. }
  10762. function getdata(data) { return (data && data.name.slice(-4) === ".bin") ? getdatabin(data) : getdatastr(data); }
  10763. /* Part 2 Section 10.1.2 "Mapping Content Types" Names are case-insensitive */
  10764. /* OASIS does not comment on filename case sensitivity */
  10765. function safegetzipfile(zip, file) {
  10766. var k = zip.FullPaths || keys(zip.files);
  10767. var f = file.toLowerCase(), g = f.replace(/\//g,'\\');
  10768. for(var i=0; i<k.length; ++i) {
  10769. var n = k[i].toLowerCase();
  10770. if(f == n || g == n) return zip.files[k[i]];
  10771. }
  10772. return null;
  10773. }
  10774. function getzipfile(zip, file) {
  10775. var o = safegetzipfile(zip, file);
  10776. if(o == null) throw new Error("Cannot find file " + file + " in zip");
  10777. return o;
  10778. }
  10779. function getzipdata(zip, file, safe) {
  10780. if(!safe) return getdata(getzipfile(zip, file));
  10781. if(!file) return null;
  10782. try { return getzipdata(zip, file); } catch(e) { return null; }
  10783. }
  10784. function getzipstr(zip, file, safe) {
  10785. if(!safe) return getdatastr(getzipfile(zip, file));
  10786. if(!file) return null;
  10787. try { return getzipstr(zip, file); } catch(e) { return null; }
  10788. }
  10789. function zipentries(zip) {
  10790. var k = zip.FullPaths || keys(zip.files), o = [];
  10791. for(var i = 0; i < k.length; ++i) if(k[i].slice(-1) != '/') o.push(k[i]);
  10792. return o.sort();
  10793. }
  10794. function zip_add_file(zip, path, content) {
  10795. if(zip.FullPaths) CFB.utils.cfb_add(zip, path, content);
  10796. else zip.file(path, content);
  10797. }
  10798. var jszip;
  10799. /*global JSZipSync:true */
  10800. if(typeof JSZipSync !== 'undefined') jszip = JSZipSync;
  10801. if(typeof exports !== 'undefined') {
  10802. if(typeof module !== 'undefined' && module.exports) {
  10803. if(typeof jszip === 'undefined') jszip = undefined;
  10804. }
  10805. }
  10806. function zip_new() {
  10807. if(!jszip) return CFB.utils.cfb_new();
  10808. return new jszip();
  10809. }
  10810. function zip_read(d, o) {
  10811. var zip;
  10812. if(jszip) switch(o.type) {
  10813. case "base64": zip = new jszip(d, { base64:true }); break;
  10814. case "binary": case "array": zip = new jszip(d, { base64:false }); break;
  10815. case "buffer": zip = new jszip(d); break;
  10816. default: throw new Error("Unrecognized type " + o.type);
  10817. }
  10818. else switch(o.type) {
  10819. case "base64": zip = CFB.read(d, { type: "base64" }); break;
  10820. case "binary": zip = CFB.read(d, { type: "binary" }); break;
  10821. case "buffer": case "array": zip = CFB.read(d, { type: "buffer" }); break;
  10822. default: throw new Error("Unrecognized type " + o.type);
  10823. }
  10824. return zip;
  10825. }
  10826. function resolve_path(path, base) {
  10827. if(path.charAt(0) == "/") return path.slice(1);
  10828. var result = base.split('/');
  10829. if(base.slice(-1) != "/") result.pop(); // folder path
  10830. var target = path.split('/');
  10831. while (target.length !== 0) {
  10832. var step = target.shift();
  10833. if (step === '..') result.pop();
  10834. else if (step !== '.') result.push(step);
  10835. }
  10836. return result.join('/');
  10837. }
  10838. var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';
  10839. var attregexg=/([^"\s?>\/]+)\s*=\s*((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g;
  10840. var tagregex=/<[\/\?]?[a-zA-Z0-9:_-]+(?:\s+[^"\s?>\/]+\s*=\s*(?:"[^"]*"|'[^']*'|[^'">\s=]+))*\s?[\/\?]?>/mg;
  10841. if(!(XML_HEADER.match(tagregex))) tagregex = /<[^>]*>/g;
  10842. var nsregex=/<\w*:/, nsregex2 = /<(\/?)\w+:/;
  10843. function parsexmltag(tag, skip_root, skip_LC) {
  10844. var z = ({});
  10845. var eq = 0, c = 0;
  10846. for(; eq !== tag.length; ++eq) if((c = tag.charCodeAt(eq)) === 32 || c === 10 || c === 13) break;
  10847. if(!skip_root) z[0] = tag.slice(0, eq);
  10848. if(eq === tag.length) return z;
  10849. var m = tag.match(attregexg), j=0, v="", i=0, q="", cc="", quot = 1;
  10850. if(m) for(i = 0; i != m.length; ++i) {
  10851. cc = m[i];
  10852. for(c=0; c != cc.length; ++c) if(cc.charCodeAt(c) === 61) break;
  10853. q = cc.slice(0,c).trim();
  10854. while(cc.charCodeAt(c+1) == 32) ++c;
  10855. quot = ((eq=cc.charCodeAt(c+1)) == 34 || eq == 39) ? 1 : 0;
  10856. v = cc.slice(c+1+quot, cc.length-quot);
  10857. for(j=0;j!=q.length;++j) if(q.charCodeAt(j) === 58) break;
  10858. if(j===q.length) {
  10859. if(q.indexOf("_") > 0) q = q.slice(0, q.indexOf("_")); // from ods
  10860. z[q] = v;
  10861. if(!skip_LC) z[q.toLowerCase()] = v;
  10862. }
  10863. else {
  10864. var k = (j===5 && q.slice(0,5)==="xmlns"?"xmlns":"")+q.slice(j+1);
  10865. if(z[k] && q.slice(j-3,j) == "ext") continue; // from ods
  10866. z[k] = v;
  10867. if(!skip_LC) z[k.toLowerCase()] = v;
  10868. }
  10869. }
  10870. return z;
  10871. }
  10872. function strip_ns(x) { return x.replace(nsregex2, "<$1"); }
  10873. var encodings = {
  10874. '&quot;': '"',
  10875. '&apos;': "'",
  10876. '&gt;': '>',
  10877. '&lt;': '<',
  10878. '&amp;': '&'
  10879. };
  10880. var rencoding = evert(encodings);
  10881. //var rencstr = "&<>'\"".split("");
  10882. // TODO: CP remap (need to read file version to determine OS)
  10883. var unescapexml = (function() {
  10884. /* 22.4.2.4 bstr (Basic String) */
  10885. var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/ig, coderegex = /_x([\da-fA-F]{4})_/ig;
  10886. return function unescapexml(text) {
  10887. var s = text + '', i = s.indexOf("<![CDATA[");
  10888. if(i == -1) return s.replace(encregex, function($$, $1) { return encodings[$$]||String.fromCharCode(parseInt($1,$$.indexOf("x")>-1?16:10))||$$; }).replace(coderegex,function(m,c) {return String.fromCharCode(parseInt(c,16));});
  10889. var j = s.indexOf("]]>");
  10890. return unescapexml(s.slice(0, i)) + s.slice(i+9,j) + unescapexml(s.slice(j+3));
  10891. };
  10892. })();
  10893. var decregex=/[&<>'"]/g, charegex = /[\u0000-\u0008\u000b-\u001f]/g;
  10894. function escapexml(text){
  10895. var s = text + '';
  10896. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(charegex,function(s) { return "_x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + "_";});
  10897. }
  10898. function escapexmltag(text){ return escapexml(text).replace(/ /g,"_x0020_"); }
  10899. var htmlcharegex = /[\u0000-\u001f]/g;
  10900. function escapehtml(text){
  10901. var s = text + '';
  10902. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(/\n/g, "<br/>").replace(htmlcharegex,function(s) { return "&#x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + ";"; });
  10903. }
  10904. function escapexlml(text){
  10905. var s = text + '';
  10906. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(htmlcharegex,function(s) { return "&#x" + (s.charCodeAt(0).toString(16)).toUpperCase() + ";"; });
  10907. }
  10908. /* TODO: handle codepages */
  10909. var xlml_fixstr = (function() {
  10910. var entregex = /&#(\d+);/g;
  10911. function entrepl($$,$1) { return String.fromCharCode(parseInt($1,10)); }
  10912. return function xlml_fixstr(str) { return str.replace(entregex,entrepl); };
  10913. })();
  10914. var xlml_unfixstr = (function() {
  10915. return function xlml_unfixstr(str) { return str.replace(/(\r\n|[\r\n])/g,"\&#10;"); };
  10916. })();
  10917. function parsexmlbool(value) {
  10918. switch(value) {
  10919. case 1: case true: case '1': case 'true': case 'TRUE': return true;
  10920. /* case '0': case 'false': case 'FALSE':*/
  10921. default: return false;
  10922. }
  10923. }
  10924. var utf8read = function utf8reada(orig) {
  10925. var out = "", i = 0, c = 0, d = 0, e = 0, f = 0, w = 0;
  10926. while (i < orig.length) {
  10927. c = orig.charCodeAt(i++);
  10928. if (c < 128) { out += String.fromCharCode(c); continue; }
  10929. d = orig.charCodeAt(i++);
  10930. if (c>191 && c<224) { f = ((c & 31) << 6); f |= (d & 63); out += String.fromCharCode(f); continue; }
  10931. e = orig.charCodeAt(i++);
  10932. if (c < 240) { out += String.fromCharCode(((c & 15) << 12) | ((d & 63) << 6) | (e & 63)); continue; }
  10933. f = orig.charCodeAt(i++);
  10934. w = (((c & 7) << 18) | ((d & 63) << 12) | ((e & 63) << 6) | (f & 63))-65536;
  10935. out += String.fromCharCode(0xD800 + ((w>>>10)&1023));
  10936. out += String.fromCharCode(0xDC00 + (w&1023));
  10937. }
  10938. return out;
  10939. };
  10940. var utf8write = function(orig) {
  10941. var out = [], i = 0, c = 0, d = 0;
  10942. while(i < orig.length) {
  10943. c = orig.charCodeAt(i++);
  10944. switch(true) {
  10945. case c < 128: out.push(String.fromCharCode(c)); break;
  10946. case c < 2048:
  10947. out.push(String.fromCharCode(192 + (c >> 6)));
  10948. out.push(String.fromCharCode(128 + (c & 63)));
  10949. break;
  10950. case c >= 55296 && c < 57344:
  10951. c -= 55296; d = orig.charCodeAt(i++) - 56320 + (c<<10);
  10952. out.push(String.fromCharCode(240 + ((d >>18) & 7)));
  10953. out.push(String.fromCharCode(144 + ((d >>12) & 63)));
  10954. out.push(String.fromCharCode(128 + ((d >> 6) & 63)));
  10955. out.push(String.fromCharCode(128 + (d & 63)));
  10956. break;
  10957. default:
  10958. out.push(String.fromCharCode(224 + (c >> 12)));
  10959. out.push(String.fromCharCode(128 + ((c >> 6) & 63)));
  10960. out.push(String.fromCharCode(128 + (c & 63)));
  10961. }
  10962. }
  10963. return out.join("");
  10964. };
  10965. if(has_buf) {
  10966. var utf8readb = function utf8readb(data) {
  10967. var out = Buffer.alloc(2*data.length), w, i, j = 1, k = 0, ww=0, c;
  10968. for(i = 0; i < data.length; i+=j) {
  10969. j = 1;
  10970. if((c=data.charCodeAt(i)) < 128) w = c;
  10971. else if(c < 224) { w = (c&31)*64+(data.charCodeAt(i+1)&63); j=2; }
  10972. else if(c < 240) { w=(c&15)*4096+(data.charCodeAt(i+1)&63)*64+(data.charCodeAt(i+2)&63); j=3; }
  10973. else { j = 4;
  10974. w = (c & 7)*262144+(data.charCodeAt(i+1)&63)*4096+(data.charCodeAt(i+2)&63)*64+(data.charCodeAt(i+3)&63);
  10975. w -= 65536; ww = 0xD800 + ((w>>>10)&1023); w = 0xDC00 + (w&1023);
  10976. }
  10977. if(ww !== 0) { out[k++] = ww&255; out[k++] = ww>>>8; ww = 0; }
  10978. out[k++] = w%256; out[k++] = w>>>8;
  10979. }
  10980. return out.slice(0,k).toString('ucs2');
  10981. };
  10982. var corpus = "foo bar baz\u00e2\u0098\u0083\u00f0\u009f\u008d\u00a3";
  10983. if(utf8read(corpus) == utf8readb(corpus)) utf8read = utf8readb;
  10984. var utf8readc = function utf8readc(data) { return Buffer_from(data, 'binary').toString('utf8'); };
  10985. if(utf8read(corpus) == utf8readc(corpus)) utf8read = utf8readc;
  10986. utf8write = function(data) { return Buffer_from(data, 'utf8').toString("binary"); };
  10987. }
  10988. // matches <foo>...</foo> extracts content
  10989. var matchtag = (function() {
  10990. var mtcache = ({});
  10991. return function matchtag(f,g) {
  10992. var t = f+"|"+(g||"");
  10993. if(mtcache[t]) return mtcache[t];
  10994. return (mtcache[t] = new RegExp('<(?:\\w+:)?'+f+'(?: xml:space="preserve")?(?:[^>]*)>([\\s\\S]*?)</(?:\\w+:)?'+f+'>',((g||""))));
  10995. };
  10996. })();
  10997. var htmldecode = (function() {
  10998. var entities = [
  10999. ['nbsp', ' '], ['middot', '·'],
  11000. ['quot', '"'], ['apos', "'"], ['gt', '>'], ['lt', '<'], ['amp', '&']
  11001. ].map(function(x) { return [new RegExp('&' + x[0] + ';', "ig"), x[1]]; });
  11002. return function htmldecode(str) {
  11003. var o = str
  11004. // Remove new lines and spaces from start of content
  11005. .replace(/^[\t\n\r ]+/, "")
  11006. // Remove new lines and spaces from end of content
  11007. .replace(/[\t\n\r ]+$/,"")
  11008. // Added line which removes any white space characters after and before html tags
  11009. .replace(/>\s+/g,">").replace(/\s+</g,"<")
  11010. // Replace remaining new lines and spaces with space
  11011. .replace(/[\t\n\r ]+/g, " ")
  11012. // Replace <br> tags with new lines
  11013. .replace(/<\s*[bB][rR]\s*\/?>/g,"\n")
  11014. // Strip HTML elements
  11015. .replace(/<[^>]*>/g,"");
  11016. for(var i = 0; i < entities.length; ++i) o = o.replace(entities[i][0], entities[i][1]);
  11017. return o;
  11018. };
  11019. })();
  11020. var vtregex = (function(){ var vt_cache = {};
  11021. return function vt_regex(bt) {
  11022. if(vt_cache[bt] !== undefined) return vt_cache[bt];
  11023. return (vt_cache[bt] = new RegExp("<(?:vt:)?" + bt + ">([\\s\\S]*?)</(?:vt:)?" + bt + ">", 'g') );
  11024. };})();
  11025. var vtvregex = /<\/?(?:vt:)?variant>/g, vtmregex = /<(?:vt:)([^>]*)>([\s\S]*)</;
  11026. function parseVector(data, opts) {
  11027. var h = parsexmltag(data);
  11028. var matches = data.match(vtregex(h.baseType))||[];
  11029. var res = [];
  11030. if(matches.length != h.size) {
  11031. if(opts.WTF) throw new Error("unexpected vector length " + matches.length + " != " + h.size);
  11032. return res;
  11033. }
  11034. matches.forEach(function(x) {
  11035. var v = x.replace(vtvregex,"").match(vtmregex);
  11036. if(v) res.push({v:utf8read(v[2]), t:v[1]});
  11037. });
  11038. return res;
  11039. }
  11040. var wtregex = /(^\s|\s$|\n)/;
  11041. function writetag(f,g) { return '<' + f + (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f + '>'; }
  11042. function wxt_helper(h) { return keys(h).map(function(k) { return " " + k + '="' + h[k] + '"';}).join(""); }
  11043. function writextag(f,g,h) { return '<' + f + ((h != null) ? wxt_helper(h) : "") + ((g != null) ? (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f : "/") + '>';}
  11044. function write_w3cdtf(d, t) { try { return d.toISOString().replace(/\.\d*/,""); } catch(e) { if(t) throw e; } return ""; }
  11045. function write_vt(s, xlsx) {
  11046. switch(typeof s) {
  11047. case 'string':
  11048. var o = writextag('vt:lpwstr', escapexml(s));
  11049. if(xlsx) o = o.replace(/&quot;/g, "_x0022_");
  11050. return o;
  11051. case 'number': return writextag((s|0)==s?'vt:i4':'vt:r8', escapexml(String(s)));
  11052. case 'boolean': return writextag('vt:bool',s?'true':'false');
  11053. }
  11054. if(s instanceof Date) return writextag('vt:filetime', write_w3cdtf(s));
  11055. throw new Error("Unable to serialize " + s);
  11056. }
  11057. var XMLNS = ({
  11058. 'dc': 'http://purl.org/dc/elements/1.1/',
  11059. 'dcterms': 'http://purl.org/dc/terms/',
  11060. 'dcmitype': 'http://purl.org/dc/dcmitype/',
  11061. 'mx': 'http://schemas.microsoft.com/office/mac/excel/2008/main',
  11062. 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  11063. 'sjs': 'http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties',
  11064. 'vt': 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
  11065. 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
  11066. 'xsd': 'http://www.w3.org/2001/XMLSchema'
  11067. });
  11068. XMLNS.main = [
  11069. 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  11070. 'http://purl.oclc.org/ooxml/spreadsheetml/main',
  11071. 'http://schemas.microsoft.com/office/excel/2006/main',
  11072. 'http://schemas.microsoft.com/office/excel/2006/2'
  11073. ];
  11074. var XLMLNS = ({
  11075. 'o': 'urn:schemas-microsoft-com:office:office',
  11076. 'x': 'urn:schemas-microsoft-com:office:excel',
  11077. 'ss': 'urn:schemas-microsoft-com:office:spreadsheet',
  11078. 'dt': 'uuid:C2F41010-65B3-11d1-A29F-00AA00C14882',
  11079. 'mv': 'http://macVmlSchemaUri',
  11080. 'v': 'urn:schemas-microsoft-com:vml',
  11081. 'html': 'http://www.w3.org/TR/REC-html40'
  11082. });
  11083. function read_double_le(b, idx) {
  11084. var s = 1 - 2 * (b[idx + 7] >>> 7);
  11085. var e = ((b[idx + 7] & 0x7f) << 4) + ((b[idx + 6] >>> 4) & 0x0f);
  11086. var m = (b[idx+6]&0x0f);
  11087. for(var i = 5; i >= 0; --i) m = m * 256 + b[idx + i];
  11088. if(e == 0x7ff) return m == 0 ? (s * Infinity) : NaN;
  11089. if(e == 0) e = -1022;
  11090. else { e -= 1023; m += Math.pow(2,52); }
  11091. return s * Math.pow(2, e - 52) * m;
  11092. }
  11093. function write_double_le(b, v, idx) {
  11094. var bs = ((((v < 0) || (1/v == -Infinity)) ? 1 : 0) << 7), e = 0, m = 0;
  11095. var av = bs ? (-v) : v;
  11096. if(!isFinite(av)) { e = 0x7ff; m = isNaN(v) ? 0x6969 : 0; }
  11097. else if(av == 0) e = m = 0;
  11098. else {
  11099. e = Math.floor(Math.log(av) / Math.LN2);
  11100. m = av * Math.pow(2, 52 - e);
  11101. if((e <= -1023) && (!isFinite(m) || (m < Math.pow(2,52)))) { e = -1022; }
  11102. else { m -= Math.pow(2,52); e+=1023; }
  11103. }
  11104. for(var i = 0; i <= 5; ++i, m/=256) b[idx + i] = m & 0xff;
  11105. b[idx + 6] = ((e & 0x0f) << 4) | (m & 0xf);
  11106. b[idx + 7] = (e >> 4) | bs;
  11107. }
  11108. var __toBuffer = function(bufs) { var x=[],w=10240; for(var i=0;i<bufs[0].length;++i) if(bufs[0][i]) for(var j=0,L=bufs[0][i].length;j<L;j+=w) x.push.apply(x, bufs[0][i].slice(j,j+w)); return x; };
  11109. var ___toBuffer = __toBuffer;
  11110. var __utf16le = function(b,s,e) { var ss=[]; for(var i=s; i<e; i+=2) ss.push(String.fromCharCode(__readUInt16LE(b,i))); return ss.join("").replace(chr0,''); };
  11111. var ___utf16le = __utf16le;
  11112. var __hexlify = function(b,s,l) { var ss=[]; for(var i=s; i<s+l; ++i) ss.push(("0" + b[i].toString(16)).slice(-2)); return ss.join(""); };
  11113. var ___hexlify = __hexlify;
  11114. var __utf8 = function(b,s,e) { var ss=[]; for(var i=s; i<e; i++) ss.push(String.fromCharCode(__readUInt8(b,i))); return ss.join(""); };
  11115. var ___utf8 = __utf8;
  11116. var __lpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  11117. var ___lpstr = __lpstr;
  11118. var __cpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  11119. var ___cpstr = __cpstr;
  11120. var __lpwstr = function(b,i) { var len = 2*__readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  11121. var ___lpwstr = __lpwstr;
  11122. var __lpp4, ___lpp4;
  11123. __lpp4 = ___lpp4 = function lpp4_(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf16le(b, i+4,i+4+len) : "";};
  11124. var __8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len) : "";};
  11125. var ___8lpp4 = __8lpp4;
  11126. var __double, ___double;
  11127. __double = ___double = function(b, idx) { return read_double_le(b, idx);};
  11128. var is_buf = function is_buf_a(a) { return Array.isArray(a); };
  11129. if(has_buf) {
  11130. __utf16le = function(b,s,e) { if(!Buffer.isBuffer(b)) return ___utf16le(b,s,e); return b.toString('utf16le',s,e).replace(chr0,'')/*.replace(chr1,'!')*/; };
  11131. __hexlify = function(b,s,l) { return Buffer.isBuffer(b) ? b.toString('hex',s,s+l) : ___hexlify(b,s,l); };
  11132. __lpstr = function lpstr_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpstr(b, i); var len = b.readUInt32LE(i); return len > 0 ? b.toString('utf8',i+4,i+4+len-1) : "";};
  11133. __cpstr = function cpstr_b(b, i) { if(!Buffer.isBuffer(b)) return ___cpstr(b, i); var len = b.readUInt32LE(i); return len > 0 ? b.toString('utf8',i+4,i+4+len-1) : "";};
  11134. __lpwstr = function lpwstr_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpwstr(b, i); var len = 2*b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len-1);};
  11135. __lpp4 = function lpp4_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpp4(b, i); var len = b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len);};
  11136. __8lpp4 = function lpp4_8b(b, i) { if(!Buffer.isBuffer(b)) return ___8lpp4(b, i); var len = b.readUInt32LE(i); return b.toString('utf8',i+4,i+4+len);};
  11137. __utf8 = function utf8_b(b, s, e) { return (Buffer.isBuffer(b)) ? b.toString('utf8',s,e) : ___utf8(b,s,e); };
  11138. __toBuffer = function(bufs) { return (bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0])) ? Buffer.concat(bufs[0]) : ___toBuffer(bufs);};
  11139. bconcat = function(bufs) { return Buffer.isBuffer(bufs[0]) ? Buffer.concat(bufs) : [].concat.apply([], bufs); };
  11140. __double = function double_(b, i) { if(Buffer.isBuffer(b)) return b.readDoubleLE(i); return ___double(b,i); };
  11141. is_buf = function is_buf_b(a) { return Buffer.isBuffer(a) || Array.isArray(a); };
  11142. }
  11143. /* from js-xls */
  11144. if(typeof cptable !== 'undefined') {
  11145. __utf16le = function(b,s,e) { return cptable.utils.decode(1200, b.slice(s,e)).replace(chr0, ''); };
  11146. __utf8 = function(b,s,e) { return cptable.utils.decode(65001, b.slice(s,e)); };
  11147. __lpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(current_ansi, b.slice(i+4, i+4+len-1)) : "";};
  11148. __cpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(current_codepage, b.slice(i+4, i+4+len-1)) : "";};
  11149. __lpwstr = function(b,i) { var len = 2*__readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(1200, b.slice(i+4,i+4+len-1)) : "";};
  11150. __lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(1200, b.slice(i+4,i+4+len)) : "";};
  11151. __8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(65001, b.slice(i+4,i+4+len)) : "";};
  11152. }
  11153. var __readUInt8 = function(b, idx) { return b[idx]; };
  11154. var __readUInt16LE = function(b, idx) { return (b[idx+1]*(1<<8))+b[idx]; };
  11155. var __readInt16LE = function(b, idx) { var u = (b[idx+1]*(1<<8))+b[idx]; return (u < 0x8000) ? u : ((0xffff - u + 1) * -1); };
  11156. var __readUInt32LE = function(b, idx) { return b[idx+3]*(1<<24)+(b[idx+2]<<16)+(b[idx+1]<<8)+b[idx]; };
  11157. var __readInt32LE = function(b, idx) { return (b[idx+3]<<24)|(b[idx+2]<<16)|(b[idx+1]<<8)|b[idx]; };
  11158. var __readInt32BE = function(b, idx) { return (b[idx]<<24)|(b[idx+1]<<16)|(b[idx+2]<<8)|b[idx+3]; };
  11159. function ReadShift(size, t) {
  11160. var o="", oI, oR, oo=[], w, vv, i, loc;
  11161. switch(t) {
  11162. case 'dbcs':
  11163. loc = this.l;
  11164. if(has_buf && Buffer.isBuffer(this)) o = this.slice(this.l, this.l+2*size).toString("utf16le");
  11165. else for(i = 0; i < size; ++i) { o+=String.fromCharCode(__readUInt16LE(this, loc)); loc+=2; }
  11166. size *= 2;
  11167. break;
  11168. case 'utf8': o = __utf8(this, this.l, this.l + size); break;
  11169. case 'utf16le': size *= 2; o = __utf16le(this, this.l, this.l + size); break;
  11170. case 'wstr':
  11171. if(typeof cptable !== 'undefined') o = cptable.utils.decode(current_codepage, this.slice(this.l, this.l+2*size));
  11172. else return ReadShift.call(this, size, 'dbcs');
  11173. size = 2 * size; break;
  11174. /* [MS-OLEDS] 2.1.4 LengthPrefixedAnsiString */
  11175. case 'lpstr-ansi': o = __lpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  11176. case 'lpstr-cp': o = __cpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  11177. /* [MS-OLEDS] 2.1.5 LengthPrefixedUnicodeString */
  11178. case 'lpwstr': o = __lpwstr(this, this.l); size = 4 + 2 * __readUInt32LE(this, this.l); break;
  11179. /* [MS-OFFCRYPTO] 2.1.2 Length-Prefixed Padded Unicode String (UNICODE-LP-P4) */
  11180. case 'lpp4': size = 4 + __readUInt32LE(this, this.l); o = __lpp4(this, this.l); if(size & 0x02) size += 2; break;
  11181. /* [MS-OFFCRYPTO] 2.1.3 Length-Prefixed UTF-8 String (UTF-8-LP-P4) */
  11182. case '8lpp4': size = 4 + __readUInt32LE(this, this.l); o = __8lpp4(this, this.l); if(size & 0x03) size += 4 - (size & 0x03); break;
  11183. case 'cstr': size = 0; o = "";
  11184. while((w=__readUInt8(this, this.l + size++))!==0) oo.push(_getchar(w));
  11185. o = oo.join(""); break;
  11186. case '_wstr': size = 0; o = "";
  11187. while((w=__readUInt16LE(this,this.l +size))!==0){oo.push(_getchar(w));size+=2;}
  11188. size+=2; o = oo.join(""); break;
  11189. /* sbcs and dbcs support continue records in the SST way TODO codepages */
  11190. case 'dbcs-cont': o = ""; loc = this.l;
  11191. for(i = 0; i < size; ++i) {
  11192. if(this.lens && this.lens.indexOf(loc) !== -1) {
  11193. w = __readUInt8(this, loc);
  11194. this.l = loc + 1;
  11195. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  11196. return oo.join("") + vv;
  11197. }
  11198. oo.push(_getchar(__readUInt16LE(this, loc)));
  11199. loc+=2;
  11200. } o = oo.join(""); size *= 2; break;
  11201. case 'cpstr':
  11202. if(typeof cptable !== 'undefined') {
  11203. o = cptable.utils.decode(current_codepage, this.slice(this.l, this.l + size));
  11204. break;
  11205. }
  11206. /* falls through */
  11207. case 'sbcs-cont': o = ""; loc = this.l;
  11208. for(i = 0; i != size; ++i) {
  11209. if(this.lens && this.lens.indexOf(loc) !== -1) {
  11210. w = __readUInt8(this, loc);
  11211. this.l = loc + 1;
  11212. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  11213. return oo.join("") + vv;
  11214. }
  11215. oo.push(_getchar(__readUInt8(this, loc)));
  11216. loc+=1;
  11217. } o = oo.join(""); break;
  11218. default:
  11219. switch(size) {
  11220. case 1: oI = __readUInt8(this, this.l); this.l++; return oI;
  11221. case 2: oI = (t === 'i' ? __readInt16LE : __readUInt16LE)(this, this.l); this.l += 2; return oI;
  11222. case 4: case -4:
  11223. if(t === 'i' || ((this[this.l+3] & 0x80)===0)) { oI = ((size > 0) ? __readInt32LE : __readInt32BE)(this, this.l); this.l += 4; return oI; }
  11224. else { oR = __readUInt32LE(this, this.l); this.l += 4; } return oR;
  11225. case 8: case -8:
  11226. if(t === 'f') {
  11227. if(size == 8) oR = __double(this, this.l);
  11228. else oR = __double([this[this.l+7],this[this.l+6],this[this.l+5],this[this.l+4],this[this.l+3],this[this.l+2],this[this.l+1],this[this.l+0]], 0);
  11229. this.l += 8; return oR;
  11230. } else size = 8;
  11231. /* falls through */
  11232. case 16: o = __hexlify(this, this.l, size); break;
  11233. }}
  11234. this.l+=size; return o;
  11235. }
  11236. var __writeUInt32LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); b[idx+2] = ((val >>> 16) & 0xFF); b[idx+3] = ((val >>> 24) & 0xFF); };
  11237. var __writeInt32LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >> 8) & 0xFF); b[idx+2] = ((val >> 16) & 0xFF); b[idx+3] = ((val >> 24) & 0xFF); };
  11238. var __writeUInt16LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); };
  11239. function WriteShift(t, val, f) {
  11240. var size = 0, i = 0;
  11241. if(f === 'dbcs') {
  11242. for(i = 0; i != val.length; ++i) __writeUInt16LE(this, val.charCodeAt(i), this.l + 2 * i);
  11243. size = 2 * val.length;
  11244. } else if(f === 'sbcs') {
  11245. if(typeof cptable !== 'undefined' && current_ansi == 874) {
  11246. /* TODO: use tables directly, don't encode */
  11247. for(i = 0; i != val.length; ++i) {
  11248. var cppayload = cptable.utils.encode(current_ansi, val.charAt(i));
  11249. this[this.l + i] = cppayload[0];
  11250. }
  11251. } else {
  11252. val = val.replace(/[^\x00-\x7F]/g, "_");
  11253. for(i = 0; i != val.length; ++i) this[this.l + i] = (val.charCodeAt(i) & 0xFF);
  11254. }
  11255. size = val.length;
  11256. } else if(f === 'hex') {
  11257. for(; i < t; ++i) {
  11258. this[this.l++] = (parseInt(val.slice(2*i, 2*i+2), 16)||0);
  11259. } return this;
  11260. } else if(f === 'utf16le') {
  11261. var end = Math.min(this.l + t, this.length);
  11262. for(i = 0; i < Math.min(val.length, t); ++i) {
  11263. var cc = val.charCodeAt(i);
  11264. this[this.l++] = (cc & 0xff);
  11265. this[this.l++] = (cc >> 8);
  11266. }
  11267. while(this.l < end) this[this.l++] = 0;
  11268. return this;
  11269. } else switch(t) {
  11270. case 1: size = 1; this[this.l] = val&0xFF; break;
  11271. case 2: size = 2; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; break;
  11272. case 3: size = 3; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; val >>>= 8; this[this.l+2] = val&0xFF; break;
  11273. case 4: size = 4; __writeUInt32LE(this, val, this.l); break;
  11274. case 8: size = 8; if(f === 'f') { write_double_le(this, val, this.l); break; }
  11275. /* falls through */
  11276. case 16: break;
  11277. case -4: size = 4; __writeInt32LE(this, val, this.l); break;
  11278. }
  11279. this.l += size; return this;
  11280. }
  11281. function CheckField(hexstr, fld) {
  11282. var m = __hexlify(this,this.l,hexstr.length>>1);
  11283. if(m !== hexstr) throw new Error(fld + 'Expected ' + hexstr + ' saw ' + m);
  11284. this.l += hexstr.length>>1;
  11285. }
  11286. function prep_blob(blob, pos) {
  11287. blob.l = pos;
  11288. blob.read_shift = ReadShift;
  11289. blob.chk = CheckField;
  11290. blob.write_shift = WriteShift;
  11291. }
  11292. function parsenoop(blob, length) { blob.l += length; }
  11293. function new_buf(sz) {
  11294. var o = new_raw_buf(sz);
  11295. prep_blob(o, 0);
  11296. return o;
  11297. }
  11298. /* [MS-XLSB] 2.1.4 Record */
  11299. function recordhopper(data, cb, opts) {
  11300. if(!data) return;
  11301. var tmpbyte, cntbyte, length;
  11302. prep_blob(data, data.l || 0);
  11303. var L = data.length, RT = 0, tgt = 0;
  11304. while(data.l < L) {
  11305. RT = data.read_shift(1);
  11306. if(RT & 0x80) RT = (RT & 0x7F) + ((data.read_shift(1) & 0x7F)<<7);
  11307. var R = XLSBRecordEnum[RT] || XLSBRecordEnum[0xFFFF];
  11308. tmpbyte = data.read_shift(1);
  11309. length = tmpbyte & 0x7F;
  11310. for(cntbyte = 1; cntbyte <4 && (tmpbyte & 0x80); ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 0x7F)<<(7*cntbyte);
  11311. tgt = data.l + length;
  11312. var d = (R.f||parsenoop)(data, length, opts);
  11313. data.l = tgt;
  11314. if(cb(d, R.n, RT)) return;
  11315. }
  11316. }
  11317. /* control buffer usage for fixed-length buffers */
  11318. function buf_array() {
  11319. var bufs = [], blksz = has_buf ? 256 : 2048;
  11320. var newblk = function ba_newblk(sz) {
  11321. var o = (new_buf(sz));
  11322. prep_blob(o, 0);
  11323. return o;
  11324. };
  11325. var curbuf = newblk(blksz);
  11326. var endbuf = function ba_endbuf() {
  11327. if(!curbuf) return;
  11328. if(curbuf.length > curbuf.l) { curbuf = curbuf.slice(0, curbuf.l); curbuf.l = curbuf.length; }
  11329. if(curbuf.length > 0) bufs.push(curbuf);
  11330. curbuf = null;
  11331. };
  11332. var next = function ba_next(sz) {
  11333. if(curbuf && (sz < (curbuf.length - curbuf.l))) return curbuf;
  11334. endbuf();
  11335. return (curbuf = newblk(Math.max(sz+1, blksz)));
  11336. };
  11337. var end = function ba_end() {
  11338. endbuf();
  11339. return __toBuffer([bufs]);
  11340. };
  11341. var push = function ba_push(buf) { endbuf(); curbuf = buf; if(curbuf.l == null) curbuf.l = curbuf.length; next(blksz); };
  11342. return ({ next:next, push:push, end:end, _bufs:bufs });
  11343. }
  11344. function write_record(ba, type, payload, length) {
  11345. var t = +XLSBRE[type], l;
  11346. if(isNaN(t)) return; // TODO: throw something here?
  11347. if(!length) length = XLSBRecordEnum[t].p || (payload||[]).length || 0;
  11348. l = 1 + (t >= 0x80 ? 1 : 0) + 1/* + length*/;
  11349. if(length >= 0x80) ++l; if(length >= 0x4000) ++l; if(length >= 0x200000) ++l;
  11350. var o = ba.next(l);
  11351. if(t <= 0x7F) o.write_shift(1, t);
  11352. else {
  11353. o.write_shift(1, (t & 0x7F) + 0x80);
  11354. o.write_shift(1, (t >> 7));
  11355. }
  11356. for(var i = 0; i != 4; ++i) {
  11357. if(length >= 0x80) { o.write_shift(1, (length & 0x7F)+0x80); length >>= 7; }
  11358. else { o.write_shift(1, length); break; }
  11359. }
  11360. if(length > 0 && is_buf(payload)) ba.push(payload);
  11361. }
  11362. /* XLS ranges enforced */
  11363. function shift_cell_xls(cell, tgt, opts) {
  11364. var out = dup(cell);
  11365. if(tgt.s) {
  11366. if(out.cRel) out.c += tgt.s.c;
  11367. if(out.rRel) out.r += tgt.s.r;
  11368. } else {
  11369. if(out.cRel) out.c += tgt.c;
  11370. if(out.rRel) out.r += tgt.r;
  11371. }
  11372. if(!opts || opts.biff < 12) {
  11373. while(out.c >= 0x100) out.c -= 0x100;
  11374. while(out.r >= 0x10000) out.r -= 0x10000;
  11375. }
  11376. return out;
  11377. }
  11378. function shift_range_xls(cell, range, opts) {
  11379. var out = dup(cell);
  11380. out.s = shift_cell_xls(out.s, range.s, opts);
  11381. out.e = shift_cell_xls(out.e, range.s, opts);
  11382. return out;
  11383. }
  11384. function encode_cell_xls(c, biff) {
  11385. if(c.cRel && c.c < 0) { c = dup(c); while(c.c < 0) c.c += (biff > 8) ? 0x4000 : 0x100; }
  11386. if(c.rRel && c.r < 0) { c = dup(c); while(c.r < 0) c.r += (biff > 8) ? 0x100000 : ((biff > 5) ? 0x10000 : 0x4000); }
  11387. var s = encode_cell(c);
  11388. if(!c.cRel && c.cRel != null) s = fix_col(s);
  11389. if(!c.rRel && c.rRel != null) s = fix_row(s);
  11390. return s;
  11391. }
  11392. function encode_range_xls(r, opts) {
  11393. if(r.s.r == 0 && !r.s.rRel) {
  11394. if(r.e.r == (opts.biff >= 12 ? 0xFFFFF : (opts.biff >= 8 ? 0x10000 : 0x4000)) && !r.e.rRel) {
  11395. return (r.s.cRel ? "" : "$") + encode_col(r.s.c) + ":" + (r.e.cRel ? "" : "$") + encode_col(r.e.c);
  11396. }
  11397. }
  11398. if(r.s.c == 0 && !r.s.cRel) {
  11399. if(r.e.c == (opts.biff >= 12 ? 0x3FFF : 0xFF) && !r.e.cRel) {
  11400. return (r.s.rRel ? "" : "$") + encode_row(r.s.r) + ":" + (r.e.rRel ? "" : "$") + encode_row(r.e.r);
  11401. }
  11402. }
  11403. return encode_cell_xls(r.s, opts.biff) + ":" + encode_cell_xls(r.e, opts.biff);
  11404. }
  11405. var OFFCRYPTO = {};
  11406. var make_offcrypto = function(O, _crypto) {
  11407. var crypto;
  11408. if(typeof _crypto !== 'undefined') crypto = _crypto;
  11409. else if(typeof require !== 'undefined') {
  11410. try { crypto = undefined; }
  11411. catch(e) { crypto = null; }
  11412. }
  11413. O.rc4 = function(key, data) {
  11414. var S = new Array(256);
  11415. var c = 0, i = 0, j = 0, t = 0;
  11416. for(i = 0; i != 256; ++i) S[i] = i;
  11417. for(i = 0; i != 256; ++i) {
  11418. j = (j + S[i] + (key[i%key.length]).charCodeAt(0))&255;
  11419. t = S[i]; S[i] = S[j]; S[j] = t;
  11420. }
  11421. // $FlowIgnore
  11422. i = j = 0; var out = new_raw_buf(data.length);
  11423. for(c = 0; c != data.length; ++c) {
  11424. i = (i + 1)&255;
  11425. j = (j + S[i])%256;
  11426. t = S[i]; S[i] = S[j]; S[j] = t;
  11427. out[c] = (data[c] ^ S[(S[i]+S[j])&255]);
  11428. }
  11429. return out;
  11430. };
  11431. O.md5 = function(hex) {
  11432. if(!crypto) throw new Error("Unsupported crypto");
  11433. return crypto.createHash('md5').update(hex).digest('hex');
  11434. };
  11435. };
  11436. /*global crypto:true */
  11437. make_offcrypto(OFFCRYPTO, typeof crypto !== "undefined" ? crypto : undefined);
  11438. function decode_row(rowstr) { return parseInt(unfix_row(rowstr),10) - 1; }
  11439. function encode_row(row) { return "" + (row + 1); }
  11440. function fix_row(cstr) { return cstr.replace(/([A-Z]|^)(\d+)$/,"$1$$$2"); }
  11441. function unfix_row(cstr) { return cstr.replace(/\$(\d+)$/,"$1"); }
  11442. function decode_col(colstr) { var c = unfix_col(colstr), d = 0, i = 0; for(; i !== c.length; ++i) d = 26*d + c.charCodeAt(i) - 64; return d - 1; }
  11443. function encode_col(col) { if(col < 0) throw new Error("invalid column " + col); var s=""; for(++col; col; col=Math.floor((col-1)/26)) s = String.fromCharCode(((col-1)%26) + 65) + s; return s; }
  11444. function fix_col(cstr) { return cstr.replace(/^([A-Z])/,"$$$1"); }
  11445. function unfix_col(cstr) { return cstr.replace(/^\$([A-Z])/,"$1"); }
  11446. function split_cell(cstr) { return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/,"$1,$2").split(","); }
  11447. //function decode_cell(cstr) { var splt = split_cell(cstr); return { c:decode_col(splt[0]), r:decode_row(splt[1]) }; }
  11448. function decode_cell(cstr) {
  11449. var R = 0, C = 0;
  11450. for(var i = 0; i < cstr.length; ++i) {
  11451. var cc = cstr.charCodeAt(i);
  11452. if(cc >= 48 && cc <= 57) R = 10 * R + (cc - 48);
  11453. else if(cc >= 65 && cc <= 90) C = 26 * C + (cc - 64);
  11454. }
  11455. return { c: C - 1, r:R - 1 };
  11456. }
  11457. //function encode_cell(cell) { return encode_col(cell.c) + encode_row(cell.r); }
  11458. function encode_cell(cell) {
  11459. var col = cell.c + 1;
  11460. var s="";
  11461. for(; col; col=((col-1)/26)|0) s = String.fromCharCode(((col-1)%26) + 65) + s;
  11462. return s + (cell.r + 1);
  11463. }
  11464. function decode_range(range) {
  11465. var idx = range.indexOf(":");
  11466. if(idx == -1) return { s: decode_cell(range), e: decode_cell(range) };
  11467. return { s: decode_cell(range.slice(0, idx)), e: decode_cell(range.slice(idx + 1)) };
  11468. }
  11469. function encode_range(cs,ce) {
  11470. if(typeof ce === 'undefined' || typeof ce === 'number') {
  11471. return encode_range(cs.s, cs.e);
  11472. }
  11473. if(typeof cs !== 'string') cs = encode_cell((cs));
  11474. if(typeof ce !== 'string') ce = encode_cell((ce));
  11475. return cs == ce ? cs : cs + ":" + ce;
  11476. }
  11477. function safe_decode_range(range) {
  11478. var o = {s:{c:0,r:0},e:{c:0,r:0}};
  11479. var idx = 0, i = 0, cc = 0;
  11480. var len = range.length;
  11481. for(idx = 0; i < len; ++i) {
  11482. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  11483. idx = 26*idx + cc;
  11484. }
  11485. o.s.c = --idx;
  11486. for(idx = 0; i < len; ++i) {
  11487. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  11488. idx = 10*idx + cc;
  11489. }
  11490. o.s.r = --idx;
  11491. if(i === len || range.charCodeAt(++i) === 58) { o.e.c=o.s.c; o.e.r=o.s.r; return o; }
  11492. for(idx = 0; i != len; ++i) {
  11493. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  11494. idx = 26*idx + cc;
  11495. }
  11496. o.e.c = --idx;
  11497. for(idx = 0; i != len; ++i) {
  11498. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  11499. idx = 10*idx + cc;
  11500. }
  11501. o.e.r = --idx;
  11502. return o;
  11503. }
  11504. function safe_format_cell(cell, v) {
  11505. var q = (cell.t == 'd' && v instanceof Date);
  11506. if(cell.z != null) try { return (cell.w = SSF.format(cell.z, q ? datenum(v) : v)); } catch(e) { }
  11507. try { return (cell.w = SSF.format((cell.XF||{}).numFmtId||(q ? 14 : 0), q ? datenum(v) : v)); } catch(e) { return ''+v; }
  11508. }
  11509. function format_cell(cell, v, o) {
  11510. if(cell == null || cell.t == null || cell.t == 'z') return "";
  11511. if(cell.w !== undefined) return cell.w;
  11512. if(cell.t == 'd' && !cell.z && o && o.dateNF) cell.z = o.dateNF;
  11513. if(v == undefined) return safe_format_cell(cell, cell.v);
  11514. return safe_format_cell(cell, v);
  11515. }
  11516. function sheet_to_workbook(sheet, opts) {
  11517. var n = opts && opts.sheet ? opts.sheet : "Sheet1";
  11518. var sheets = {}; sheets[n] = sheet;
  11519. return { SheetNames: [n], Sheets: sheets };
  11520. }
  11521. function sheet_add_aoa(_ws, data, opts) {
  11522. var o = opts || {};
  11523. var dense = _ws ? Array.isArray(_ws) : o.dense;
  11524. if(DENSE != null && dense == null) dense = DENSE;
  11525. var ws = _ws || (dense ? ([]) : ({}));
  11526. var _R = 0, _C = 0;
  11527. if(ws && o.origin != null) {
  11528. if(typeof o.origin == 'number') _R = o.origin;
  11529. else {
  11530. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  11531. _R = _origin.r; _C = _origin.c;
  11532. }
  11533. if(!ws["!ref"]) ws["!ref"] = "A1:A1";
  11534. }
  11535. var range = ({s: {c:10000000, r:10000000}, e: {c:0, r:0}});
  11536. if(ws['!ref']) {
  11537. var _range = safe_decode_range(ws['!ref']);
  11538. range.s.c = _range.s.c;
  11539. range.s.r = _range.s.r;
  11540. range.e.c = Math.max(range.e.c, _range.e.c);
  11541. range.e.r = Math.max(range.e.r, _range.e.r);
  11542. if(_R == -1) range.e.r = _R = _range.e.r + 1;
  11543. }
  11544. for(var R = 0; R != data.length; ++R) {
  11545. if(!data[R]) continue;
  11546. if(!Array.isArray(data[R])) throw new Error("aoa_to_sheet expects an array of arrays");
  11547. for(var C = 0; C != data[R].length; ++C) {
  11548. if(typeof data[R][C] === 'undefined') continue;
  11549. var cell = ({v: data[R][C] });
  11550. var __R = _R + R, __C = _C + C;
  11551. if(range.s.r > __R) range.s.r = __R;
  11552. if(range.s.c > __C) range.s.c = __C;
  11553. if(range.e.r < __R) range.e.r = __R;
  11554. if(range.e.c < __C) range.e.c = __C;
  11555. if(data[R][C] && typeof data[R][C] === 'object' && !Array.isArray(data[R][C]) && !(data[R][C] instanceof Date)) cell = data[R][C];
  11556. else {
  11557. if(Array.isArray(cell.v)) { cell.f = data[R][C][1]; cell.v = cell.v[0]; }
  11558. if(cell.v === null) { if(cell.f) cell.t = 'n'; else if(!o.sheetStubs) continue; else cell.t = 'z'; }
  11559. else if(typeof cell.v === 'number') cell.t = 'n';
  11560. else if(typeof cell.v === 'boolean') cell.t = 'b';
  11561. else if(cell.v instanceof Date) {
  11562. cell.z = o.dateNF || SSF._table[14];
  11563. if(o.cellDates) { cell.t = 'd'; cell.w = SSF.format(cell.z, datenum(cell.v)); }
  11564. else { cell.t = 'n'; cell.v = datenum(cell.v); cell.w = SSF.format(cell.z, cell.v); }
  11565. }
  11566. else cell.t = 's';
  11567. }
  11568. if(dense) {
  11569. if(!ws[__R]) ws[__R] = [];
  11570. if(ws[__R][__C] && ws[__R][__C].z) cell.z = ws[__R][__C].z;
  11571. ws[__R][__C] = cell;
  11572. } else {
  11573. var cell_ref = encode_cell(({c:__C,r:__R}));
  11574. if(ws[cell_ref] && ws[cell_ref].z) cell.z = ws[cell_ref].z;
  11575. ws[cell_ref] = cell;
  11576. }
  11577. }
  11578. }
  11579. if(range.s.c < 10000000) ws['!ref'] = encode_range(range);
  11580. return ws;
  11581. }
  11582. function aoa_to_sheet(data, opts) { return sheet_add_aoa(null, data, opts); }
  11583. function write_UInt32LE(x, o) {
  11584. if (!o) o = new_buf(4);
  11585. o.write_shift(4, x);
  11586. return o;
  11587. }
  11588. /* [MS-XLSB] 2.5.168 */
  11589. function parse_XLWideString(data) {
  11590. var cchCharacters = data.read_shift(4);
  11591. return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, 'dbcs');
  11592. }
  11593. function write_XLWideString(data, o) {
  11594. var _null = false; if (o == null) { _null = true; o = new_buf(4 + 2 * data.length); }
  11595. o.write_shift(4, data.length);
  11596. if (data.length > 0) o.write_shift(0, data, 'dbcs');
  11597. return _null ? o.slice(0, o.l) : o;
  11598. }
  11599. /* [MS-XLSB] 2.5.91 */
  11600. //function parse_LPWideString(data) {
  11601. // var cchCharacters = data.read_shift(2);
  11602. // return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, "utf16le");
  11603. //}
  11604. /* [MS-XLSB] 2.5.143 */
  11605. function parse_StrRun(data) {
  11606. return { ich: data.read_shift(2), ifnt: data.read_shift(2) };
  11607. }
  11608. function write_StrRun(run, o) {
  11609. if (!o) o = new_buf(4);
  11610. o.write_shift(2, run.ich || 0);
  11611. o.write_shift(2, run.ifnt || 0);
  11612. return o;
  11613. }
  11614. /* [MS-XLSB] 2.5.121 */
  11615. function parse_RichStr(data, length) {
  11616. var start = data.l;
  11617. var flags = data.read_shift(1);
  11618. var str = parse_XLWideString(data);
  11619. var rgsStrRun = [];
  11620. var z = ({ t: str, h: str });
  11621. if ((flags & 1) !== 0) { /* fRichStr */
  11622. /* TODO: formatted string */
  11623. var dwSizeStrRun = data.read_shift(4);
  11624. for (var i = 0; i != dwSizeStrRun; ++i) rgsStrRun.push(parse_StrRun(data));
  11625. z.r = rgsStrRun;
  11626. }
  11627. else z.r = [{ ich: 0, ifnt: 0 }];
  11628. //if((flags & 2) !== 0) { /* fExtStr */
  11629. // /* TODO: phonetic string */
  11630. //}
  11631. data.l = start + length;
  11632. return z;
  11633. }
  11634. function write_RichStr(str, o) {
  11635. /* TODO: formatted string */
  11636. var _null = false; if (o == null) { _null = true; o = new_buf(15 + 4 * str.t.length); }
  11637. o.write_shift(1, 0);
  11638. write_XLWideString(str.t, o);
  11639. return _null ? o.slice(0, o.l) : o;
  11640. }
  11641. /* [MS-XLSB] 2.4.328 BrtCommentText (RichStr w/1 run) */
  11642. var parse_BrtCommentText = parse_RichStr;
  11643. function write_BrtCommentText(str, o) {
  11644. /* TODO: formatted string */
  11645. var _null = false; if (o == null) { _null = true; o = new_buf(23 + 4 * str.t.length); }
  11646. o.write_shift(1, 1);
  11647. write_XLWideString(str.t, o);
  11648. o.write_shift(4, 1);
  11649. write_StrRun({ ich: 0, ifnt: 0 }, o);
  11650. return _null ? o.slice(0, o.l) : o;
  11651. }
  11652. /* [MS-XLSB] 2.5.9 */
  11653. function parse_XLSBCell(data) {
  11654. var col = data.read_shift(4);
  11655. var iStyleRef = data.read_shift(2);
  11656. iStyleRef += data.read_shift(1) << 16;
  11657. data.l++; //var fPhShow = data.read_shift(1);
  11658. return { c: col, iStyleRef: iStyleRef };
  11659. }
  11660. function write_XLSBCell(cell, o) {
  11661. if (o == null) o = new_buf(8);
  11662. o.write_shift(-4, cell.c);
  11663. o.write_shift(3, cell.iStyleRef || cell.s);
  11664. o.write_shift(1, 0); /* fPhShow */
  11665. return o;
  11666. }
  11667. /* [MS-XLSB] 2.5.21 */
  11668. var parse_XLSBCodeName = parse_XLWideString;
  11669. var write_XLSBCodeName = write_XLWideString;
  11670. /* [MS-XLSB] 2.5.166 */
  11671. function parse_XLNullableWideString(data) {
  11672. var cchCharacters = data.read_shift(4);
  11673. return cchCharacters === 0 || cchCharacters === 0xFFFFFFFF ? "" : data.read_shift(cchCharacters, 'dbcs');
  11674. }
  11675. function write_XLNullableWideString(data, o) {
  11676. var _null = false; if (o == null) { _null = true; o = new_buf(127); }
  11677. o.write_shift(4, data.length > 0 ? data.length : 0xFFFFFFFF);
  11678. if (data.length > 0) o.write_shift(0, data, 'dbcs');
  11679. return _null ? o.slice(0, o.l) : o;
  11680. }
  11681. /* [MS-XLSB] 2.5.165 */
  11682. var parse_XLNameWideString = parse_XLWideString;
  11683. //var write_XLNameWideString = write_XLWideString;
  11684. /* [MS-XLSB] 2.5.114 */
  11685. var parse_RelID = parse_XLNullableWideString;
  11686. var write_RelID = write_XLNullableWideString;
  11687. /* [MS-XLS] 2.5.217 ; [MS-XLSB] 2.5.122 */
  11688. function parse_RkNumber(data) {
  11689. var b = data.slice(data.l, data.l + 4);
  11690. var fX100 = (b[0] & 1), fInt = (b[0] & 2);
  11691. data.l += 4;
  11692. b[0] &= 0xFC; // b[0] &= ~3;
  11693. var RK = fInt === 0 ? __double([0, 0, 0, 0, b[0], b[1], b[2], b[3]], 0) : __readInt32LE(b, 0) >> 2;
  11694. return fX100 ? (RK / 100) : RK;
  11695. }
  11696. function write_RkNumber(data, o) {
  11697. if (o == null) o = new_buf(4);
  11698. var fX100 = 0, fInt = 0, d100 = data * 100;
  11699. if ((data == (data | 0)) && (data >= -(1 << 29)) && (data < (1 << 29))) { fInt = 1; }
  11700. else if ((d100 == (d100 | 0)) && (d100 >= -(1 << 29)) && (d100 < (1 << 29))) { fInt = 1; fX100 = 1; }
  11701. if (fInt) o.write_shift(-4, ((fX100 ? d100 : data) << 2) + (fX100 + 2));
  11702. else throw new Error("unsupported RkNumber " + data); // TODO
  11703. }
  11704. /* [MS-XLSB] 2.5.117 RfX */
  11705. function parse_RfX(data ) {
  11706. var cell = ({ s: {}, e: {} });
  11707. cell.s.r = data.read_shift(4);
  11708. cell.e.r = data.read_shift(4);
  11709. cell.s.c = data.read_shift(4);
  11710. cell.e.c = data.read_shift(4);
  11711. return cell;
  11712. }
  11713. function write_RfX(r, o) {
  11714. if (!o) o = new_buf(16);
  11715. o.write_shift(4, r.s.r);
  11716. o.write_shift(4, r.e.r);
  11717. o.write_shift(4, r.s.c);
  11718. o.write_shift(4, r.e.c);
  11719. return o;
  11720. }
  11721. /* [MS-XLSB] 2.5.153 UncheckedRfX */
  11722. var parse_UncheckedRfX = parse_RfX;
  11723. var write_UncheckedRfX = write_RfX;
  11724. /* [MS-XLSB] 2.5.155 UncheckedSqRfX */
  11725. //function parse_UncheckedSqRfX(data) {
  11726. // var cnt = data.read_shift(4);
  11727. // var out = [];
  11728. // for(var i = 0; i < cnt; ++i) {
  11729. // var rng = parse_UncheckedRfX(data);
  11730. // out.push(encode_range(rng));
  11731. // }
  11732. // return out.join(",");
  11733. //}
  11734. //function write_UncheckedSqRfX(sqrfx) {
  11735. // var parts = sqrfx.split(/\s*,\s*/);
  11736. // var o = new_buf(4); o.write_shift(4, parts.length);
  11737. // var out = [o];
  11738. // parts.forEach(function(rng) {
  11739. // out.push(write_UncheckedRfX(safe_decode_range(rng)));
  11740. // });
  11741. // return bconcat(out);
  11742. //}
  11743. /* [MS-XLS] 2.5.342 ; [MS-XLSB] 2.5.171 */
  11744. /* TODO: error checking, NaN and Infinity values are not valid Xnum */
  11745. function parse_Xnum(data) { return data.read_shift(8, 'f'); }
  11746. function write_Xnum(data, o) { return (o || new_buf(8)).write_shift(8, data, 'f'); }
  11747. /* [MS-XLSB] 2.4.324 BrtColor */
  11748. function parse_BrtColor(data) {
  11749. var out = {};
  11750. var d = data.read_shift(1);
  11751. //var fValidRGB = d & 1;
  11752. var xColorType = d >>> 1;
  11753. var index = data.read_shift(1);
  11754. var nTS = data.read_shift(2, 'i');
  11755. var bR = data.read_shift(1);
  11756. var bG = data.read_shift(1);
  11757. var bB = data.read_shift(1);
  11758. data.l++; //var bAlpha = data.read_shift(1);
  11759. switch (xColorType) {
  11760. case 0: out.auto = 1; break;
  11761. case 1:
  11762. out.index = index;
  11763. var icv = XLSIcv[index];
  11764. /* automatic pseudo index 81 */
  11765. if (icv) out.rgb = rgb2Hex(icv);
  11766. break;
  11767. case 2:
  11768. /* if(!fValidRGB) throw new Error("invalid"); */
  11769. out.rgb = rgb2Hex([bR, bG, bB]);
  11770. break;
  11771. case 3: out.theme = index; break;
  11772. }
  11773. if (nTS != 0) out.tint = nTS > 0 ? nTS / 32767 : nTS / 32768;
  11774. return out;
  11775. }
  11776. function write_BrtColor(color, o) {
  11777. if (!o) o = new_buf(8);
  11778. if (!color || color.auto) { o.write_shift(4, 0); o.write_shift(4, 0); return o; }
  11779. if (color.index != null) {
  11780. o.write_shift(1, 0x02);
  11781. o.write_shift(1, color.index);
  11782. } else if (color.theme != null) {
  11783. o.write_shift(1, 0x06);
  11784. o.write_shift(1, color.theme);
  11785. } else {
  11786. o.write_shift(1, 0x05);
  11787. o.write_shift(1, 0);
  11788. }
  11789. var nTS = color.tint || 0;
  11790. if (nTS > 0) nTS *= 32767;
  11791. else if (nTS < 0) nTS *= 32768;
  11792. o.write_shift(2, nTS);
  11793. if (!color.rgb || color.theme != null) {
  11794. o.write_shift(2, 0);
  11795. o.write_shift(1, 0);
  11796. o.write_shift(1, 0);
  11797. } else {
  11798. var rgb = (color.rgb || 'FFFFFF');
  11799. if (typeof rgb == 'number') rgb = ("000000" + rgb.toString(16)).slice(-6);
  11800. o.write_shift(1, parseInt(rgb.slice(0, 2), 16));
  11801. o.write_shift(1, parseInt(rgb.slice(2, 4), 16));
  11802. o.write_shift(1, parseInt(rgb.slice(4, 6), 16));
  11803. o.write_shift(1, 0xFF);
  11804. }
  11805. return o;
  11806. }
  11807. /* [MS-XLSB] 2.5.52 */
  11808. function parse_FontFlags(data) {
  11809. var d = data.read_shift(1);
  11810. data.l++;
  11811. var out = {
  11812. fBold: d & 0x01,
  11813. fItalic: d & 0x02,
  11814. fUnderline: d & 0x04,
  11815. fStrikeout: d & 0x08,
  11816. fOutline: d & 0x10,
  11817. fShadow: d & 0x20,
  11818. fCondense: d & 0x40,
  11819. fExtend: d & 0x80
  11820. };
  11821. return out;
  11822. }
  11823. function write_FontFlags(font, o) {
  11824. if (!o) o = new_buf(2);
  11825. var grbit =
  11826. (font.italic ? 0x02 : 0) |
  11827. (font.strike ? 0x08 : 0) |
  11828. (font.outline ? 0x10 : 0) |
  11829. (font.shadow ? 0x20 : 0) |
  11830. (font.condense ? 0x40 : 0) |
  11831. (font.extend ? 0x80 : 0);
  11832. o.write_shift(1, grbit);
  11833. o.write_shift(1, 0);
  11834. return o;
  11835. }
  11836. /* [MS-OLEDS] 2.3.1 and 2.3.2 */
  11837. function parse_ClipboardFormatOrString(o, w) {
  11838. // $FlowIgnore
  11839. var ClipFmt = { 2: "BITMAP", 3: "METAFILEPICT", 8: "DIB", 14: "ENHMETAFILE" };
  11840. var m = o.read_shift(4);
  11841. switch (m) {
  11842. case 0x00000000: return "";
  11843. case 0xffffffff: case 0xfffffffe: return ClipFmt[o.read_shift(4)] || "";
  11844. }
  11845. if (m > 0x190) throw new Error("Unsupported Clipboard: " + m.toString(16));
  11846. o.l -= 4;
  11847. return o.read_shift(0, w == 1 ? "lpstr" : "lpwstr");
  11848. }
  11849. function parse_ClipboardFormatOrAnsiString(o) { return parse_ClipboardFormatOrString(o, 1); }
  11850. function parse_ClipboardFormatOrUnicodeString(o) { return parse_ClipboardFormatOrString(o, 2); }
  11851. /* [MS-OLEPS] 2.2 PropertyType */
  11852. //var VT_EMPTY = 0x0000;
  11853. //var VT_NULL = 0x0001;
  11854. var VT_I2 = 0x0002;
  11855. var VT_I4 = 0x0003;
  11856. //var VT_R4 = 0x0004;
  11857. //var VT_R8 = 0x0005;
  11858. //var VT_CY = 0x0006;
  11859. //var VT_DATE = 0x0007;
  11860. //var VT_BSTR = 0x0008;
  11861. //var VT_ERROR = 0x000A;
  11862. var VT_BOOL = 0x000B;
  11863. var VT_VARIANT = 0x000C;
  11864. //var VT_DECIMAL = 0x000E;
  11865. //var VT_I1 = 0x0010;
  11866. //var VT_UI1 = 0x0011;
  11867. //var VT_UI2 = 0x0012;
  11868. var VT_UI4 = 0x0013;
  11869. //var VT_I8 = 0x0014;
  11870. //var VT_UI8 = 0x0015;
  11871. //var VT_INT = 0x0016;
  11872. //var VT_UINT = 0x0017;
  11873. var VT_LPSTR = 0x001E;
  11874. //var VT_LPWSTR = 0x001F;
  11875. var VT_FILETIME = 0x0040;
  11876. var VT_BLOB = 0x0041;
  11877. //var VT_STREAM = 0x0042;
  11878. //var VT_STORAGE = 0x0043;
  11879. //var VT_STREAMED_Object = 0x0044;
  11880. //var VT_STORED_Object = 0x0045;
  11881. //var VT_BLOB_Object = 0x0046;
  11882. var VT_CF = 0x0047;
  11883. //var VT_CLSID = 0x0048;
  11884. //var VT_VERSIONED_STREAM = 0x0049;
  11885. var VT_VECTOR = 0x1000;
  11886. //var VT_ARRAY = 0x2000;
  11887. var VT_STRING = 0x0050; // 2.3.3.1.11 VtString
  11888. var VT_USTR = 0x0051; // 2.3.3.1.12 VtUnalignedString
  11889. var VT_CUSTOM = [VT_STRING, VT_USTR];
  11890. /* [MS-OSHARED] 2.3.3.2.2.1 Document Summary Information PIDDSI */
  11891. var DocSummaryPIDDSI = {
  11892. 0x01: { n: 'CodePage', t: VT_I2 },
  11893. 0x02: { n: 'Category', t: VT_STRING },
  11894. 0x03: { n: 'PresentationFormat', t: VT_STRING },
  11895. 0x04: { n: 'ByteCount', t: VT_I4 },
  11896. 0x05: { n: 'LineCount', t: VT_I4 },
  11897. 0x06: { n: 'ParagraphCount', t: VT_I4 },
  11898. 0x07: { n: 'SlideCount', t: VT_I4 },
  11899. 0x08: { n: 'NoteCount', t: VT_I4 },
  11900. 0x09: { n: 'HiddenCount', t: VT_I4 },
  11901. 0x0a: { n: 'MultimediaClipCount', t: VT_I4 },
  11902. 0x0b: { n: 'ScaleCrop', t: VT_BOOL },
  11903. 0x0c: { n: 'HeadingPairs', t: VT_VECTOR | VT_VARIANT },
  11904. 0x0d: { n: 'TitlesOfParts', t: VT_VECTOR | VT_LPSTR },
  11905. 0x0e: { n: 'Manager', t: VT_STRING },
  11906. 0x0f: { n: 'Company', t: VT_STRING },
  11907. 0x10: { n: 'LinksUpToDate', t: VT_BOOL },
  11908. 0x11: { n: 'CharacterCount', t: VT_I4 },
  11909. 0x13: { n: 'SharedDoc', t: VT_BOOL },
  11910. 0x16: { n: 'HyperlinksChanged', t: VT_BOOL },
  11911. 0x17: { n: 'AppVersion', t: VT_I4, p: 'version' },
  11912. 0x18: { n: 'DigSig', t: VT_BLOB },
  11913. 0x1A: { n: 'ContentType', t: VT_STRING },
  11914. 0x1B: { n: 'ContentStatus', t: VT_STRING },
  11915. 0x1C: { n: 'Language', t: VT_STRING },
  11916. 0x1D: { n: 'Version', t: VT_STRING },
  11917. 0xFF: {}
  11918. };
  11919. /* [MS-OSHARED] 2.3.3.2.1.1 Summary Information Property Set PIDSI */
  11920. var SummaryPIDSI = {
  11921. 0x01: { n: 'CodePage', t: VT_I2 },
  11922. 0x02: { n: 'Title', t: VT_STRING },
  11923. 0x03: { n: 'Subject', t: VT_STRING },
  11924. 0x04: { n: 'Author', t: VT_STRING },
  11925. 0x05: { n: 'Keywords', t: VT_STRING },
  11926. 0x06: { n: 'Comments', t: VT_STRING },
  11927. 0x07: { n: 'Template', t: VT_STRING },
  11928. 0x08: { n: 'LastAuthor', t: VT_STRING },
  11929. 0x09: { n: 'RevNumber', t: VT_STRING },
  11930. 0x0A: { n: 'EditTime', t: VT_FILETIME },
  11931. 0x0B: { n: 'LastPrinted', t: VT_FILETIME },
  11932. 0x0C: { n: 'CreatedDate', t: VT_FILETIME },
  11933. 0x0D: { n: 'ModifiedDate', t: VT_FILETIME },
  11934. 0x0E: { n: 'PageCount', t: VT_I4 },
  11935. 0x0F: { n: 'WordCount', t: VT_I4 },
  11936. 0x10: { n: 'CharCount', t: VT_I4 },
  11937. 0x11: { n: 'Thumbnail', t: VT_CF },
  11938. 0x12: { n: 'Application', t: VT_STRING },
  11939. 0x13: { n: 'DocSecurity', t: VT_I4 },
  11940. 0xFF: {}
  11941. };
  11942. /* [MS-OLEPS] 2.18 */
  11943. var SpecialProperties = {
  11944. 0x80000000: { n: 'Locale', t: VT_UI4 },
  11945. 0x80000003: { n: 'Behavior', t: VT_UI4 },
  11946. 0x72627262: {}
  11947. };
  11948. (function() {
  11949. for(var y in SpecialProperties) if(Object.prototype.hasOwnProperty.call(SpecialProperties, y))
  11950. DocSummaryPIDDSI[y] = SummaryPIDSI[y] = SpecialProperties[y];
  11951. })();
  11952. var DocSummaryRE = evert_key(DocSummaryPIDDSI, "n");
  11953. var SummaryRE = evert_key(SummaryPIDSI, "n");
  11954. /* [MS-XLS] 2.4.63 Country/Region codes */
  11955. var CountryEnum = {
  11956. 0x0001: "US", // United States
  11957. 0x0002: "CA", // Canada
  11958. 0x0003: "", // Latin America (except Brazil)
  11959. 0x0007: "RU", // Russia
  11960. 0x0014: "EG", // Egypt
  11961. 0x001E: "GR", // Greece
  11962. 0x001F: "NL", // Netherlands
  11963. 0x0020: "BE", // Belgium
  11964. 0x0021: "FR", // France
  11965. 0x0022: "ES", // Spain
  11966. 0x0024: "HU", // Hungary
  11967. 0x0027: "IT", // Italy
  11968. 0x0029: "CH", // Switzerland
  11969. 0x002B: "AT", // Austria
  11970. 0x002C: "GB", // United Kingdom
  11971. 0x002D: "DK", // Denmark
  11972. 0x002E: "SE", // Sweden
  11973. 0x002F: "NO", // Norway
  11974. 0x0030: "PL", // Poland
  11975. 0x0031: "DE", // Germany
  11976. 0x0034: "MX", // Mexico
  11977. 0x0037: "BR", // Brazil
  11978. 0x003d: "AU", // Australia
  11979. 0x0040: "NZ", // New Zealand
  11980. 0x0042: "TH", // Thailand
  11981. 0x0051: "JP", // Japan
  11982. 0x0052: "KR", // Korea
  11983. 0x0054: "VN", // Viet Nam
  11984. 0x0056: "CN", // China
  11985. 0x005A: "TR", // Turkey
  11986. 0x0069: "JS", // Ramastan
  11987. 0x00D5: "DZ", // Algeria
  11988. 0x00D8: "MA", // Morocco
  11989. 0x00DA: "LY", // Libya
  11990. 0x015F: "PT", // Portugal
  11991. 0x0162: "IS", // Iceland
  11992. 0x0166: "FI", // Finland
  11993. 0x01A4: "CZ", // Czech Republic
  11994. 0x0376: "TW", // Taiwan
  11995. 0x03C1: "LB", // Lebanon
  11996. 0x03C2: "JO", // Jordan
  11997. 0x03C3: "SY", // Syria
  11998. 0x03C4: "IQ", // Iraq
  11999. 0x03C5: "KW", // Kuwait
  12000. 0x03C6: "SA", // Saudi Arabia
  12001. 0x03CB: "AE", // United Arab Emirates
  12002. 0x03CC: "IL", // Israel
  12003. 0x03CE: "QA", // Qatar
  12004. 0x03D5: "IR", // Iran
  12005. 0xFFFF: "US" // United States
  12006. };
  12007. /* [MS-XLS] 2.5.127 */
  12008. var XLSFillPattern = [
  12009. null,
  12010. 'solid',
  12011. 'mediumGray',
  12012. 'darkGray',
  12013. 'lightGray',
  12014. 'darkHorizontal',
  12015. 'darkVertical',
  12016. 'darkDown',
  12017. 'darkUp',
  12018. 'darkGrid',
  12019. 'darkTrellis',
  12020. 'lightHorizontal',
  12021. 'lightVertical',
  12022. 'lightDown',
  12023. 'lightUp',
  12024. 'lightGrid',
  12025. 'lightTrellis',
  12026. 'gray125',
  12027. 'gray0625'
  12028. ];
  12029. function rgbify(arr) { return arr.map(function(x) { return [(x>>16)&255,(x>>8)&255,x&255]; }); }
  12030. /* [MS-XLS] 2.5.161 */
  12031. /* [MS-XLSB] 2.5.75 Icv */
  12032. var _XLSIcv = rgbify([
  12033. /* Color Constants */
  12034. 0x000000,
  12035. 0xFFFFFF,
  12036. 0xFF0000,
  12037. 0x00FF00,
  12038. 0x0000FF,
  12039. 0xFFFF00,
  12040. 0xFF00FF,
  12041. 0x00FFFF,
  12042. /* Overridable Defaults */
  12043. 0x000000,
  12044. 0xFFFFFF,
  12045. 0xFF0000,
  12046. 0x00FF00,
  12047. 0x0000FF,
  12048. 0xFFFF00,
  12049. 0xFF00FF,
  12050. 0x00FFFF,
  12051. 0x800000,
  12052. 0x008000,
  12053. 0x000080,
  12054. 0x808000,
  12055. 0x800080,
  12056. 0x008080,
  12057. 0xC0C0C0,
  12058. 0x808080,
  12059. 0x9999FF,
  12060. 0x993366,
  12061. 0xFFFFCC,
  12062. 0xCCFFFF,
  12063. 0x660066,
  12064. 0xFF8080,
  12065. 0x0066CC,
  12066. 0xCCCCFF,
  12067. 0x000080,
  12068. 0xFF00FF,
  12069. 0xFFFF00,
  12070. 0x00FFFF,
  12071. 0x800080,
  12072. 0x800000,
  12073. 0x008080,
  12074. 0x0000FF,
  12075. 0x00CCFF,
  12076. 0xCCFFFF,
  12077. 0xCCFFCC,
  12078. 0xFFFF99,
  12079. 0x99CCFF,
  12080. 0xFF99CC,
  12081. 0xCC99FF,
  12082. 0xFFCC99,
  12083. 0x3366FF,
  12084. 0x33CCCC,
  12085. 0x99CC00,
  12086. 0xFFCC00,
  12087. 0xFF9900,
  12088. 0xFF6600,
  12089. 0x666699,
  12090. 0x969696,
  12091. 0x003366,
  12092. 0x339966,
  12093. 0x003300,
  12094. 0x333300,
  12095. 0x993300,
  12096. 0x993366,
  12097. 0x333399,
  12098. 0x333333,
  12099. /* Other entries to appease BIFF8/12 */
  12100. 0xFFFFFF, /* 0x40 icvForeground ?? */
  12101. 0x000000, /* 0x41 icvBackground ?? */
  12102. 0x000000, /* 0x42 icvFrame ?? */
  12103. 0x000000, /* 0x43 icv3D ?? */
  12104. 0x000000, /* 0x44 icv3DText ?? */
  12105. 0x000000, /* 0x45 icv3DHilite ?? */
  12106. 0x000000, /* 0x46 icv3DShadow ?? */
  12107. 0x000000, /* 0x47 icvHilite ?? */
  12108. 0x000000, /* 0x48 icvCtlText ?? */
  12109. 0x000000, /* 0x49 icvCtlScrl ?? */
  12110. 0x000000, /* 0x4A icvCtlInv ?? */
  12111. 0x000000, /* 0x4B icvCtlBody ?? */
  12112. 0x000000, /* 0x4C icvCtlFrame ?? */
  12113. 0x000000, /* 0x4D icvCtlFore ?? */
  12114. 0x000000, /* 0x4E icvCtlBack ?? */
  12115. 0x000000, /* 0x4F icvCtlNeutral */
  12116. 0x000000, /* 0x50 icvInfoBk ?? */
  12117. 0x000000 /* 0x51 icvInfoText ?? */
  12118. ]);
  12119. var XLSIcv = dup(_XLSIcv);
  12120. /* [MS-XLSB] 2.5.97.2 */
  12121. var BErr = {
  12122. 0x00: "#NULL!",
  12123. 0x07: "#DIV/0!",
  12124. 0x0F: "#VALUE!",
  12125. 0x17: "#REF!",
  12126. 0x1D: "#NAME?",
  12127. 0x24: "#NUM!",
  12128. 0x2A: "#N/A",
  12129. 0x2B: "#GETTING_DATA",
  12130. 0xFF: "#WTF?"
  12131. };
  12132. var RBErr = evert_num(BErr);
  12133. /* Parts enumerated in OPC spec, MS-XLSB and MS-XLSX */
  12134. /* 12.3 Part Summary <SpreadsheetML> */
  12135. /* 14.2 Part Summary <DrawingML> */
  12136. /* [MS-XLSX] 2.1 Part Enumerations ; [MS-XLSB] 2.1.7 Part Enumeration */
  12137. var ct2type/*{[string]:string}*/ = ({
  12138. /* Workbook */
  12139. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
  12140. /* Worksheet */
  12141. "application/vnd.ms-excel.binIndexWs": "TODO", /* Binary Index */
  12142. /* Macrosheet */
  12143. "application/vnd.ms-excel.intlmacrosheet": "TODO",
  12144. "application/vnd.ms-excel.binIndexMs": "TODO", /* Binary Index */
  12145. /* File Properties */
  12146. "application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
  12147. "application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops",
  12148. "application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",
  12149. /* Custom Data Properties */
  12150. "application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO",
  12151. "application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty": "TODO",
  12152. /* PivotTable */
  12153. "application/vnd.ms-excel.pivotTable": "TODO",
  12154. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO",
  12155. /* Chart Objects */
  12156. "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO",
  12157. /* Chart Colors */
  12158. "application/vnd.ms-office.chartcolorstyle+xml": "TODO",
  12159. /* Chart Style */
  12160. "application/vnd.ms-office.chartstyle+xml": "TODO",
  12161. /* Chart Advanced */
  12162. "application/vnd.ms-office.chartex+xml": "TODO",
  12163. /* Calculation Chain */
  12164. "application/vnd.ms-excel.calcChain": "calcchains",
  12165. "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",
  12166. /* Printer Settings */
  12167. "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO",
  12168. /* ActiveX */
  12169. "application/vnd.ms-office.activeX": "TODO",
  12170. "application/vnd.ms-office.activeX+xml": "TODO",
  12171. /* Custom Toolbars */
  12172. "application/vnd.ms-excel.attachedToolbars": "TODO",
  12173. /* External Data Connections */
  12174. "application/vnd.ms-excel.connections": "TODO",
  12175. "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO",
  12176. /* External Links */
  12177. "application/vnd.ms-excel.externalLink": "links",
  12178. "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "links",
  12179. /* Metadata */
  12180. "application/vnd.ms-excel.sheetMetadata": "TODO",
  12181. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "TODO",
  12182. /* PivotCache */
  12183. "application/vnd.ms-excel.pivotCacheDefinition": "TODO",
  12184. "application/vnd.ms-excel.pivotCacheRecords": "TODO",
  12185. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO",
  12186. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO",
  12187. /* Query Table */
  12188. "application/vnd.ms-excel.queryTable": "TODO",
  12189. "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO",
  12190. /* Shared Workbook */
  12191. "application/vnd.ms-excel.userNames": "TODO",
  12192. "application/vnd.ms-excel.revisionHeaders": "TODO",
  12193. "application/vnd.ms-excel.revisionLog": "TODO",
  12194. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO",
  12195. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO",
  12196. "application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO",
  12197. /* Single Cell Table */
  12198. "application/vnd.ms-excel.tableSingleCells": "TODO",
  12199. "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO",
  12200. /* Slicer */
  12201. "application/vnd.ms-excel.slicer": "TODO",
  12202. "application/vnd.ms-excel.slicerCache": "TODO",
  12203. "application/vnd.ms-excel.slicer+xml": "TODO",
  12204. "application/vnd.ms-excel.slicerCache+xml": "TODO",
  12205. /* Sort Map */
  12206. "application/vnd.ms-excel.wsSortMap": "TODO",
  12207. /* Table */
  12208. "application/vnd.ms-excel.table": "TODO",
  12209. "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO",
  12210. /* Themes */
  12211. "application/vnd.openxmlformats-officedocument.theme+xml": "themes",
  12212. /* Theme Override */
  12213. "application/vnd.openxmlformats-officedocument.themeOverride+xml": "TODO",
  12214. /* Timeline */
  12215. "application/vnd.ms-excel.Timeline+xml": "TODO", /* verify */
  12216. "application/vnd.ms-excel.TimelineCache+xml": "TODO", /* verify */
  12217. /* VBA */
  12218. "application/vnd.ms-office.vbaProject": "vba",
  12219. "application/vnd.ms-office.vbaProjectSignature": "vba",
  12220. /* Volatile Dependencies */
  12221. "application/vnd.ms-office.volatileDependencies": "TODO",
  12222. "application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO",
  12223. /* Control Properties */
  12224. "application/vnd.ms-excel.controlproperties+xml": "TODO",
  12225. /* Data Model */
  12226. "application/vnd.openxmlformats-officedocument.model+data": "TODO",
  12227. /* Survey */
  12228. "application/vnd.ms-excel.Survey+xml": "TODO",
  12229. /* Drawing */
  12230. "application/vnd.openxmlformats-officedocument.drawing+xml": "drawings",
  12231. "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO",
  12232. "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO",
  12233. "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO",
  12234. "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO",
  12235. "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO",
  12236. /* VML */
  12237. "application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO",
  12238. "application/vnd.openxmlformats-package.relationships+xml": "rels",
  12239. "application/vnd.openxmlformats-officedocument.oleObject": "TODO",
  12240. /* Image */
  12241. "image/png": "TODO",
  12242. "sheet": "js"
  12243. });
  12244. var CT_LIST = (function(){
  12245. var o = {
  12246. workbooks: {
  12247. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
  12248. xlsm: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
  12249. xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
  12250. xlam: "application/vnd.ms-excel.addin.macroEnabled.main+xml",
  12251. xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml"
  12252. },
  12253. strs: { /* Shared Strings */
  12254. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
  12255. xlsb: "application/vnd.ms-excel.sharedStrings"
  12256. },
  12257. comments: { /* Comments */
  12258. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  12259. xlsb: "application/vnd.ms-excel.comments"
  12260. },
  12261. sheets: { /* Worksheet */
  12262. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  12263. xlsb: "application/vnd.ms-excel.worksheet"
  12264. },
  12265. charts: { /* Chartsheet */
  12266. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml",
  12267. xlsb: "application/vnd.ms-excel.chartsheet"
  12268. },
  12269. dialogs: { /* Dialogsheet */
  12270. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml",
  12271. xlsb: "application/vnd.ms-excel.dialogsheet"
  12272. },
  12273. macros: { /* Macrosheet (Excel 4.0 Macros) */
  12274. xlsx: "application/vnd.ms-excel.macrosheet+xml",
  12275. xlsb: "application/vnd.ms-excel.macrosheet"
  12276. },
  12277. styles: { /* Styles */
  12278. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
  12279. xlsb: "application/vnd.ms-excel.styles"
  12280. }
  12281. };
  12282. keys(o).forEach(function(k) { ["xlsm", "xlam"].forEach(function(v) { if(!o[k][v]) o[k][v] = o[k].xlsx; }); });
  12283. keys(o).forEach(function(k){ keys(o[k]).forEach(function(v) { ct2type[o[k][v]] = k; }); });
  12284. return o;
  12285. })();
  12286. var type2ct/*{[string]:Array<string>}*/ = evert_arr(ct2type);
  12287. XMLNS.CT = 'http://schemas.openxmlformats.org/package/2006/content-types';
  12288. function new_ct() {
  12289. return ({
  12290. workbooks:[], sheets:[], charts:[], dialogs:[], macros:[],
  12291. rels:[], strs:[], comments:[], links:[],
  12292. coreprops:[], extprops:[], custprops:[], themes:[], styles:[],
  12293. calcchains:[], vba: [], drawings: [],
  12294. TODO:[], xmlns: "" });
  12295. }
  12296. function parse_ct(data) {
  12297. var ct = new_ct();
  12298. if(!data || !data.match) return ct;
  12299. var ctext = {};
  12300. (data.match(tagregex)||[]).forEach(function(x) {
  12301. var y = parsexmltag(x);
  12302. switch(y[0].replace(nsregex,"<")) {
  12303. case '<?xml': break;
  12304. case '<Types': ct.xmlns = y['xmlns' + (y[0].match(/<(\w+):/)||["",""])[1] ]; break;
  12305. case '<Default': ctext[y.Extension] = y.ContentType; break;
  12306. case '<Override':
  12307. if(ct[ct2type[y.ContentType]] !== undefined) ct[ct2type[y.ContentType]].push(y.PartName);
  12308. break;
  12309. }
  12310. });
  12311. if(ct.xmlns !== XMLNS.CT) throw new Error("Unknown Namespace: " + ct.xmlns);
  12312. ct.calcchain = ct.calcchains.length > 0 ? ct.calcchains[0] : "";
  12313. ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
  12314. ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
  12315. ct.defaults = ctext;
  12316. delete ct.calcchains;
  12317. return ct;
  12318. }
  12319. var CTYPE_XML_ROOT = writextag('Types', null, {
  12320. 'xmlns': XMLNS.CT,
  12321. 'xmlns:xsd': XMLNS.xsd,
  12322. 'xmlns:xsi': XMLNS.xsi
  12323. });
  12324. var CTYPE_DEFAULTS = [
  12325. ['xml', 'application/xml'],
  12326. ['bin', 'application/vnd.ms-excel.sheet.binary.macroEnabled.main'],
  12327. ['vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'],
  12328. ['data', 'application/vnd.openxmlformats-officedocument.model+data'],
  12329. /* from test files */
  12330. ['bmp', 'image/bmp'],
  12331. ['png', 'image/png'],
  12332. ['gif', 'image/gif'],
  12333. ['emf', 'image/x-emf'],
  12334. ['wmf', 'image/x-wmf'],
  12335. ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg'],
  12336. ['tif', 'image/tiff'], ['tiff', 'image/tiff'],
  12337. ['pdf', 'application/pdf'],
  12338. ['rels', type2ct.rels[0]]
  12339. ].map(function(x) {
  12340. return writextag('Default', null, {'Extension':x[0], 'ContentType': x[1]});
  12341. });
  12342. function write_ct(ct, opts) {
  12343. var o = [], v;
  12344. o[o.length] = (XML_HEADER);
  12345. o[o.length] = (CTYPE_XML_ROOT);
  12346. o = o.concat(CTYPE_DEFAULTS);
  12347. /* only write first instance */
  12348. var f1 = function(w) {
  12349. if(ct[w] && ct[w].length > 0) {
  12350. v = ct[w][0];
  12351. o[o.length] = (writextag('Override', null, {
  12352. 'PartName': (v[0] == '/' ? "":"/") + v,
  12353. 'ContentType': CT_LIST[w][opts.bookType || 'xlsx']
  12354. }));
  12355. }
  12356. };
  12357. /* book type-specific */
  12358. var f2 = function(w) {
  12359. (ct[w]||[]).forEach(function(v) {
  12360. o[o.length] = (writextag('Override', null, {
  12361. 'PartName': (v[0] == '/' ? "":"/") + v,
  12362. 'ContentType': CT_LIST[w][opts.bookType || 'xlsx']
  12363. }));
  12364. });
  12365. };
  12366. /* standard type */
  12367. var f3 = function(t) {
  12368. (ct[t]||[]).forEach(function(v) {
  12369. o[o.length] = (writextag('Override', null, {
  12370. 'PartName': (v[0] == '/' ? "":"/") + v,
  12371. 'ContentType': type2ct[t][0]
  12372. }));
  12373. });
  12374. };
  12375. f1('workbooks');
  12376. f2('sheets');
  12377. f2('charts');
  12378. f3('themes');
  12379. ['strs', 'styles'].forEach(f1);
  12380. ['coreprops', 'extprops', 'custprops'].forEach(f3);
  12381. f3('vba');
  12382. f3('comments');
  12383. f3('drawings');
  12384. if(o.length>2){ o[o.length] = ('</Types>'); o[1]=o[1].replace("/>",">"); }
  12385. return o.join("");
  12386. }
  12387. /* 9.3 Relationships */
  12388. var RELS = ({
  12389. WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  12390. SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  12391. HLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
  12392. VML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
  12393. XPATH: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath",
  12394. XMISS: "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing",
  12395. XLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink",
  12396. CXML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
  12397. CXMLP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
  12398. VBA: "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
  12399. });
  12400. /* 9.3.3 Representing Relationships */
  12401. function get_rels_path(file) {
  12402. var n = file.lastIndexOf("/");
  12403. return file.slice(0,n+1) + '_rels/' + file.slice(n+1) + ".rels";
  12404. }
  12405. function parse_rels(data, currentFilePath) {
  12406. var rels = {"!id":{}};
  12407. if (!data) return rels;
  12408. if (currentFilePath.charAt(0) !== '/') {
  12409. currentFilePath = '/'+currentFilePath;
  12410. }
  12411. var hash = {};
  12412. (data.match(tagregex)||[]).forEach(function(x) {
  12413. var y = parsexmltag(x);
  12414. /* 9.3.2.2 OPC_Relationships */
  12415. if (y[0] === '<Relationship') {
  12416. var rel = {}; rel.Type = y.Type; rel.Target = y.Target; rel.Id = y.Id; rel.TargetMode = y.TargetMode;
  12417. var canonictarget = y.TargetMode === 'External' ? y.Target : resolve_path(y.Target, currentFilePath);
  12418. rels[canonictarget] = rel;
  12419. hash[y.Id] = rel;
  12420. }
  12421. });
  12422. rels["!id"] = hash;
  12423. return rels;
  12424. }
  12425. XMLNS.RELS = 'http://schemas.openxmlformats.org/package/2006/relationships';
  12426. var RELS_ROOT = writextag('Relationships', null, {
  12427. //'xmlns:ns0': XMLNS.RELS,
  12428. 'xmlns': XMLNS.RELS
  12429. });
  12430. /* TODO */
  12431. function write_rels(rels) {
  12432. var o = [XML_HEADER, RELS_ROOT];
  12433. keys(rels['!id']).forEach(function(rid) {
  12434. o[o.length] = (writextag('Relationship', null, rels['!id'][rid]));
  12435. });
  12436. if(o.length>2){ o[o.length] = ('</Relationships>'); o[1]=o[1].replace("/>",">"); }
  12437. return o.join("");
  12438. }
  12439. var RELS_EXTERN = [RELS.HLINK, RELS.XPATH, RELS.XMISS];
  12440. function add_rels(rels, rId, f, type, relobj, targetmode) {
  12441. if(!relobj) relobj = {};
  12442. if(!rels['!id']) rels['!id'] = {};
  12443. if(rId < 0) for(rId = 1; rels['!id']['rId' + rId]; ++rId){/* empty */}
  12444. relobj.Id = 'rId' + rId;
  12445. relobj.Type = type;
  12446. relobj.Target = f;
  12447. if(targetmode) relobj.TargetMode = targetmode;
  12448. else if(RELS_EXTERN.indexOf(relobj.Type) > -1) relobj.TargetMode = "External";
  12449. if(rels['!id'][relobj.Id]) throw new Error("Cannot rewrite rId " + rId);
  12450. rels['!id'][relobj.Id] = relobj;
  12451. rels[('/' + relobj.Target).replace("//","/")] = relobj;
  12452. return rId;
  12453. }
  12454. /* Open Document Format for Office Applications (OpenDocument) Version 1.2 */
  12455. /* Part 3 Section 4 Manifest File */
  12456. var CT_ODS = "application/vnd.oasis.opendocument.spreadsheet";
  12457. function parse_manifest(d, opts) {
  12458. var str = xlml_normalize(d);
  12459. var Rn;
  12460. var FEtag;
  12461. while((Rn = xlmlregex.exec(str))) switch(Rn[3]) {
  12462. case 'manifest': break; // 4.2 <manifest:manifest>
  12463. case 'file-entry': // 4.3 <manifest:file-entry>
  12464. FEtag = parsexmltag(Rn[0], false);
  12465. if(FEtag.path == '/' && FEtag.type !== CT_ODS) throw new Error("This OpenDocument is not a spreadsheet");
  12466. break;
  12467. case 'encryption-data': // 4.4 <manifest:encryption-data>
  12468. case 'algorithm': // 4.5 <manifest:algorithm>
  12469. case 'start-key-generation': // 4.6 <manifest:start-key-generation>
  12470. case 'key-derivation': // 4.7 <manifest:key-derivation>
  12471. throw new Error("Unsupported ODS Encryption");
  12472. default: if(opts && opts.WTF) throw Rn;
  12473. }
  12474. }
  12475. function write_manifest(manifest) {
  12476. var o = [XML_HEADER];
  12477. o.push('<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">\n');
  12478. o.push(' <manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>\n');
  12479. for(var i = 0; i < manifest.length; ++i) o.push(' <manifest:file-entry manifest:full-path="' + manifest[i][0] + '" manifest:media-type="' + manifest[i][1] + '"/>\n');
  12480. o.push('</manifest:manifest>');
  12481. return o.join("");
  12482. }
  12483. /* Part 3 Section 6 Metadata Manifest File */
  12484. function write_rdf_type(file, res, tag) {
  12485. return [
  12486. ' <rdf:Description rdf:about="' + file + '">\n',
  12487. ' <rdf:type rdf:resource="http://docs.oasis-open.org/ns/office/1.2/meta/' + (tag || "odf") + '#' + res + '"/>\n',
  12488. ' </rdf:Description>\n'
  12489. ].join("");
  12490. }
  12491. function write_rdf_has(base, file) {
  12492. return [
  12493. ' <rdf:Description rdf:about="' + base + '">\n',
  12494. ' <ns0:hasPart xmlns:ns0="http://docs.oasis-open.org/ns/office/1.2/meta/pkg#" rdf:resource="' + file + '"/>\n',
  12495. ' </rdf:Description>\n'
  12496. ].join("");
  12497. }
  12498. function write_rdf(rdf) {
  12499. var o = [XML_HEADER];
  12500. o.push('<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n');
  12501. for(var i = 0; i != rdf.length; ++i) {
  12502. o.push(write_rdf_type(rdf[i][0], rdf[i][1]));
  12503. o.push(write_rdf_has("",rdf[i][0]));
  12504. }
  12505. o.push(write_rdf_type("","Document", "pkg"));
  12506. o.push('</rdf:RDF>');
  12507. return o.join("");
  12508. }
  12509. /* TODO: pull properties */
  12510. var write_meta_ods = (function() {
  12511. var payload = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xlink="http://www.w3.org/1999/xlink" office:version="1.2"><office:meta><meta:generator>Sheet' + 'JS ' + XLSX.version + '</meta:generator></office:meta></office:document-meta>';
  12512. return function wmo() {
  12513. return payload;
  12514. };
  12515. })();
  12516. /* ECMA-376 Part II 11.1 Core Properties Part */
  12517. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  12518. var CORE_PROPS = [
  12519. ["cp:category", "Category"],
  12520. ["cp:contentStatus", "ContentStatus"],
  12521. ["cp:keywords", "Keywords"],
  12522. ["cp:lastModifiedBy", "LastAuthor"],
  12523. ["cp:lastPrinted", "LastPrinted"],
  12524. ["cp:revision", "RevNumber"],
  12525. ["cp:version", "Version"],
  12526. ["dc:creator", "Author"],
  12527. ["dc:description", "Comments"],
  12528. ["dc:identifier", "Identifier"],
  12529. ["dc:language", "Language"],
  12530. ["dc:subject", "Subject"],
  12531. ["dc:title", "Title"],
  12532. ["dcterms:created", "CreatedDate", 'date'],
  12533. ["dcterms:modified", "ModifiedDate", 'date']
  12534. ];
  12535. XMLNS.CORE_PROPS = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
  12536. RELS.CORE_PROPS = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties';
  12537. var CORE_PROPS_REGEX = (function() {
  12538. var r = new Array(CORE_PROPS.length);
  12539. for(var i = 0; i < CORE_PROPS.length; ++i) {
  12540. var f = CORE_PROPS[i];
  12541. var g = "(?:"+ f[0].slice(0,f[0].indexOf(":")) +":)"+ f[0].slice(f[0].indexOf(":")+1);
  12542. r[i] = new RegExp("<" + g + "[^>]*>([\\s\\S]*?)<\/" + g + ">");
  12543. }
  12544. return r;
  12545. })();
  12546. function parse_core_props(data) {
  12547. var p = {};
  12548. data = utf8read(data);
  12549. for(var i = 0; i < CORE_PROPS.length; ++i) {
  12550. var f = CORE_PROPS[i], cur = data.match(CORE_PROPS_REGEX[i]);
  12551. if(cur != null && cur.length > 0) p[f[1]] = unescapexml(cur[1]);
  12552. if(f[2] === 'date' && p[f[1]]) p[f[1]] = parseDate(p[f[1]]);
  12553. }
  12554. return p;
  12555. }
  12556. var CORE_PROPS_XML_ROOT = writextag('cp:coreProperties', null, {
  12557. //'xmlns': XMLNS.CORE_PROPS,
  12558. 'xmlns:cp': XMLNS.CORE_PROPS,
  12559. 'xmlns:dc': XMLNS.dc,
  12560. 'xmlns:dcterms': XMLNS.dcterms,
  12561. 'xmlns:dcmitype': XMLNS.dcmitype,
  12562. 'xmlns:xsi': XMLNS.xsi
  12563. });
  12564. function cp_doit(f, g, h, o, p) {
  12565. if(p[f] != null || g == null || g === "") return;
  12566. p[f] = g;
  12567. g = escapexml(g);
  12568. o[o.length] = (h ? writextag(f,g,h) : writetag(f,g));
  12569. }
  12570. function write_core_props(cp, _opts) {
  12571. var opts = _opts || {};
  12572. var o = [XML_HEADER, CORE_PROPS_XML_ROOT], p = {};
  12573. if(!cp && !opts.Props) return o.join("");
  12574. if(cp) {
  12575. if(cp.CreatedDate != null) cp_doit("dcterms:created", typeof cp.CreatedDate === "string" ? cp.CreatedDate : write_w3cdtf(cp.CreatedDate, opts.WTF), {"xsi:type":"dcterms:W3CDTF"}, o, p);
  12576. if(cp.ModifiedDate != null) cp_doit("dcterms:modified", typeof cp.ModifiedDate === "string" ? cp.ModifiedDate : write_w3cdtf(cp.ModifiedDate, opts.WTF), {"xsi:type":"dcterms:W3CDTF"}, o, p);
  12577. }
  12578. for(var i = 0; i != CORE_PROPS.length; ++i) {
  12579. var f = CORE_PROPS[i];
  12580. var v = opts.Props && opts.Props[f[1]] != null ? opts.Props[f[1]] : cp ? cp[f[1]] : null;
  12581. if(v === true) v = "1";
  12582. else if(v === false) v = "0";
  12583. else if(typeof v == "number") v = String(v);
  12584. if(v != null) cp_doit(f[0], v, null, o, p);
  12585. }
  12586. if(o.length>2){ o[o.length] = ('</cp:coreProperties>'); o[1]=o[1].replace("/>",">"); }
  12587. return o.join("");
  12588. }
  12589. /* 15.2.12.3 Extended File Properties Part */
  12590. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  12591. var EXT_PROPS = [
  12592. ["Application", "Application", "string"],
  12593. ["AppVersion", "AppVersion", "string"],
  12594. ["Company", "Company", "string"],
  12595. ["DocSecurity", "DocSecurity", "string"],
  12596. ["Manager", "Manager", "string"],
  12597. ["HyperlinksChanged", "HyperlinksChanged", "bool"],
  12598. ["SharedDoc", "SharedDoc", "bool"],
  12599. ["LinksUpToDate", "LinksUpToDate", "bool"],
  12600. ["ScaleCrop", "ScaleCrop", "bool"],
  12601. ["HeadingPairs", "HeadingPairs", "raw"],
  12602. ["TitlesOfParts", "TitlesOfParts", "raw"]
  12603. ];
  12604. XMLNS.EXT_PROPS = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
  12605. RELS.EXT_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties';
  12606. var PseudoPropsPairs = [
  12607. "Worksheets", "SheetNames",
  12608. "NamedRanges", "DefinedNames",
  12609. "Chartsheets", "ChartNames"
  12610. ];
  12611. function load_props_pairs(HP, TOP, props, opts) {
  12612. var v = [];
  12613. if(typeof HP == "string") v = parseVector(HP, opts);
  12614. else for(var j = 0; j < HP.length; ++j) v = v.concat(HP[j].map(function(hp) { return {v:hp}; }));
  12615. var parts = (typeof TOP == "string") ? parseVector(TOP, opts).map(function (x) { return x.v; }) : TOP;
  12616. var idx = 0, len = 0;
  12617. if(parts.length > 0) for(var i = 0; i !== v.length; i += 2) {
  12618. len = +(v[i+1].v);
  12619. switch(v[i].v) {
  12620. case "Worksheets":
  12621. case "工作表":
  12622. case "Листы":
  12623. case "أوراق العمل":
  12624. case "ワークシート":
  12625. case "גליונות עבודה":
  12626. case "Arbeitsblätter":
  12627. case "Çalışma Sayfaları":
  12628. case "Feuilles de calcul":
  12629. case "Fogli di lavoro":
  12630. case "Folhas de cálculo":
  12631. case "Planilhas":
  12632. case "Regneark":
  12633. case "Hojas de cálculo":
  12634. case "Werkbladen":
  12635. props.Worksheets = len;
  12636. props.SheetNames = parts.slice(idx, idx + len);
  12637. break;
  12638. case "Named Ranges":
  12639. case "Rangos con nombre":
  12640. case "名前付き一覧":
  12641. case "Benannte Bereiche":
  12642. case "Navngivne områder":
  12643. props.NamedRanges = len;
  12644. props.DefinedNames = parts.slice(idx, idx + len);
  12645. break;
  12646. case "Charts":
  12647. case "Diagramme":
  12648. props.Chartsheets = len;
  12649. props.ChartNames = parts.slice(idx, idx + len);
  12650. break;
  12651. }
  12652. idx += len;
  12653. }
  12654. }
  12655. function parse_ext_props(data, p, opts) {
  12656. var q = {}; if(!p) p = {};
  12657. data = utf8read(data);
  12658. EXT_PROPS.forEach(function(f) {
  12659. var xml = (data.match(matchtag(f[0]))||[])[1];
  12660. switch(f[2]) {
  12661. case "string": if(xml) p[f[1]] = unescapexml(xml); break;
  12662. case "bool": p[f[1]] = xml === "true"; break;
  12663. case "raw":
  12664. var cur = data.match(new RegExp("<" + f[0] + "[^>]*>([\\s\\S]*?)<\/" + f[0] + ">"));
  12665. if(cur && cur.length > 0) q[f[1]] = cur[1];
  12666. break;
  12667. }
  12668. });
  12669. if(q.HeadingPairs && q.TitlesOfParts) load_props_pairs(q.HeadingPairs, q.TitlesOfParts, p, opts);
  12670. return p;
  12671. }
  12672. var EXT_PROPS_XML_ROOT = writextag('Properties', null, {
  12673. 'xmlns': XMLNS.EXT_PROPS,
  12674. 'xmlns:vt': XMLNS.vt
  12675. });
  12676. function write_ext_props(cp) {
  12677. var o = [], W = writextag;
  12678. if(!cp) cp = {};
  12679. cp.Application = "SheetJS";
  12680. o[o.length] = (XML_HEADER);
  12681. o[o.length] = (EXT_PROPS_XML_ROOT);
  12682. EXT_PROPS.forEach(function(f) {
  12683. if(cp[f[1]] === undefined) return;
  12684. var v;
  12685. switch(f[2]) {
  12686. case 'string': v = escapexml(String(cp[f[1]])); break;
  12687. case 'bool': v = cp[f[1]] ? 'true' : 'false'; break;
  12688. }
  12689. if(v !== undefined) o[o.length] = (W(f[0], v));
  12690. });
  12691. /* TODO: HeadingPairs, TitlesOfParts */
  12692. o[o.length] = (W('HeadingPairs', W('vt:vector', W('vt:variant', '<vt:lpstr>Worksheets</vt:lpstr>')+W('vt:variant', W('vt:i4', String(cp.Worksheets))), {size:2, baseType:"variant"})));
  12693. o[o.length] = (W('TitlesOfParts', W('vt:vector', cp.SheetNames.map(function(s) { return "<vt:lpstr>" + escapexml(s) + "</vt:lpstr>"; }).join(""), {size: cp.Worksheets, baseType:"lpstr"})));
  12694. if(o.length>2){ o[o.length] = ('</Properties>'); o[1]=o[1].replace("/>",">"); }
  12695. return o.join("");
  12696. }
  12697. /* 15.2.12.2 Custom File Properties Part */
  12698. XMLNS.CUST_PROPS = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties";
  12699. RELS.CUST_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties';
  12700. var custregex = /<[^>]+>[^<]*/g;
  12701. function parse_cust_props(data, opts) {
  12702. var p = {}, name = "";
  12703. var m = data.match(custregex);
  12704. if(m) for(var i = 0; i != m.length; ++i) {
  12705. var x = m[i], y = parsexmltag(x);
  12706. switch(y[0]) {
  12707. case '<?xml': break;
  12708. case '<Properties': break;
  12709. case '<property': name = unescapexml(y.name); break;
  12710. case '</property>': name = null; break;
  12711. default: if (x.indexOf('<vt:') === 0) {
  12712. var toks = x.split('>');
  12713. var type = toks[0].slice(4), text = toks[1];
  12714. /* 22.4.2.32 (CT_Variant). Omit the binary types from 22.4 (Variant Types) */
  12715. switch(type) {
  12716. case 'lpstr': case 'bstr': case 'lpwstr':
  12717. p[name] = unescapexml(text);
  12718. break;
  12719. case 'bool':
  12720. p[name] = parsexmlbool(text);
  12721. break;
  12722. case 'i1': case 'i2': case 'i4': case 'i8': case 'int': case 'uint':
  12723. p[name] = parseInt(text, 10);
  12724. break;
  12725. case 'r4': case 'r8': case 'decimal':
  12726. p[name] = parseFloat(text);
  12727. break;
  12728. case 'filetime': case 'date':
  12729. p[name] = parseDate(text);
  12730. break;
  12731. case 'cy': case 'error':
  12732. p[name] = unescapexml(text);
  12733. break;
  12734. default:
  12735. if(type.slice(-1) == '/') break;
  12736. if(opts.WTF && typeof console !== 'undefined') console.warn('Unexpected', x, type, toks);
  12737. }
  12738. } else if(x.slice(0,2) === "</") {/* empty */
  12739. } else if(opts.WTF) throw new Error(x);
  12740. }
  12741. }
  12742. return p;
  12743. }
  12744. var CUST_PROPS_XML_ROOT = writextag('Properties', null, {
  12745. 'xmlns': XMLNS.CUST_PROPS,
  12746. 'xmlns:vt': XMLNS.vt
  12747. });
  12748. function write_cust_props(cp) {
  12749. var o = [XML_HEADER, CUST_PROPS_XML_ROOT];
  12750. if(!cp) return o.join("");
  12751. var pid = 1;
  12752. keys(cp).forEach(function custprop(k) { ++pid;
  12753. o[o.length] = (writextag('property', write_vt(cp[k], true), {
  12754. 'fmtid': '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}',
  12755. 'pid': pid,
  12756. 'name': escapexml(k)
  12757. }));
  12758. });
  12759. if(o.length>2){ o[o.length] = '</Properties>'; o[1]=o[1].replace("/>",">"); }
  12760. return o.join("");
  12761. }
  12762. /* Common Name -> XLML Name */
  12763. var XLMLDocPropsMap = {
  12764. Title: 'Title',
  12765. Subject: 'Subject',
  12766. Author: 'Author',
  12767. Keywords: 'Keywords',
  12768. Comments: 'Description',
  12769. LastAuthor: 'LastAuthor',
  12770. RevNumber: 'Revision',
  12771. Application: 'AppName',
  12772. /* TotalTime: 'TotalTime', */
  12773. LastPrinted: 'LastPrinted',
  12774. CreatedDate: 'Created',
  12775. ModifiedDate: 'LastSaved',
  12776. /* Pages */
  12777. /* Words */
  12778. /* Characters */
  12779. Category: 'Category',
  12780. /* PresentationFormat */
  12781. Manager: 'Manager',
  12782. Company: 'Company',
  12783. /* Guid */
  12784. /* HyperlinkBase */
  12785. /* Bytes */
  12786. /* Lines */
  12787. /* Paragraphs */
  12788. /* CharactersWithSpaces */
  12789. AppVersion: 'Version',
  12790. ContentStatus: 'ContentStatus', /* NOTE: missing from schema */
  12791. Identifier: 'Identifier', /* NOTE: missing from schema */
  12792. Language: 'Language' /* NOTE: missing from schema */
  12793. };
  12794. var evert_XLMLDPM = evert(XLMLDocPropsMap);
  12795. function xlml_set_prop(Props, tag, val) {
  12796. tag = evert_XLMLDPM[tag] || tag;
  12797. Props[tag] = val;
  12798. }
  12799. function xlml_write_docprops(Props, opts) {
  12800. var o = [];
  12801. keys(XLMLDocPropsMap).map(function(m) {
  12802. for(var i = 0; i < CORE_PROPS.length; ++i) if(CORE_PROPS[i][1] == m) return CORE_PROPS[i];
  12803. for(i = 0; i < EXT_PROPS.length; ++i) if(EXT_PROPS[i][1] == m) return EXT_PROPS[i];
  12804. throw m;
  12805. }).forEach(function(p) {
  12806. if(Props[p[1]] == null) return;
  12807. var m = opts && opts.Props && opts.Props[p[1]] != null ? opts.Props[p[1]] : Props[p[1]];
  12808. switch(p[2]) {
  12809. case 'date': m = new Date(m).toISOString().replace(/\.\d*Z/,"Z"); break;
  12810. }
  12811. if(typeof m == 'number') m = String(m);
  12812. else if(m === true || m === false) { m = m ? "1" : "0"; }
  12813. else if(m instanceof Date) m = new Date(m).toISOString().replace(/\.\d*Z/,"");
  12814. o.push(writetag(XLMLDocPropsMap[p[1]] || p[1], m));
  12815. });
  12816. return writextag('DocumentProperties', o.join(""), {xmlns:XLMLNS.o });
  12817. }
  12818. function xlml_write_custprops(Props, Custprops) {
  12819. var BLACKLIST = ["Worksheets","SheetNames"];
  12820. var T = 'CustomDocumentProperties';
  12821. var o = [];
  12822. if(Props) keys(Props).forEach(function(k) {
  12823. if(!Object.prototype.hasOwnProperty.call(Props, k)) return;
  12824. for(var i = 0; i < CORE_PROPS.length; ++i) if(k == CORE_PROPS[i][1]) return;
  12825. for(i = 0; i < EXT_PROPS.length; ++i) if(k == EXT_PROPS[i][1]) return;
  12826. for(i = 0; i < BLACKLIST.length; ++i) if(k == BLACKLIST[i]) return;
  12827. var m = Props[k];
  12828. var t = "string";
  12829. if(typeof m == 'number') { t = "float"; m = String(m); }
  12830. else if(m === true || m === false) { t = "boolean"; m = m ? "1" : "0"; }
  12831. else m = String(m);
  12832. o.push(writextag(escapexmltag(k), m, {"dt:dt":t}));
  12833. });
  12834. if(Custprops) keys(Custprops).forEach(function(k) {
  12835. if(!Object.prototype.hasOwnProperty.call(Custprops, k)) return;
  12836. if(Props && Object.prototype.hasOwnProperty.call(Props, k)) return;
  12837. var m = Custprops[k];
  12838. var t = "string";
  12839. if(typeof m == 'number') { t = "float"; m = String(m); }
  12840. else if(m === true || m === false) { t = "boolean"; m = m ? "1" : "0"; }
  12841. else if(m instanceof Date) { t = "dateTime.tz"; m = m.toISOString(); }
  12842. else m = String(m);
  12843. o.push(writextag(escapexmltag(k), m, {"dt:dt":t}));
  12844. });
  12845. return '<' + T + ' xmlns="' + XLMLNS.o + '">' + o.join("") + '</' + T + '>';
  12846. }
  12847. /* [MS-DTYP] 2.3.3 FILETIME */
  12848. /* [MS-OLEDS] 2.1.3 FILETIME (Packet Version) */
  12849. /* [MS-OLEPS] 2.8 FILETIME (Packet Version) */
  12850. function parse_FILETIME(blob) {
  12851. var dwLowDateTime = blob.read_shift(4), dwHighDateTime = blob.read_shift(4);
  12852. return new Date(((dwHighDateTime/1e7*Math.pow(2,32) + dwLowDateTime/1e7) - 11644473600)*1000).toISOString().replace(/\.000/,"");
  12853. }
  12854. function write_FILETIME(time) {
  12855. var date = (typeof time == "string") ? new Date(Date.parse(time)) : time;
  12856. var t = date.getTime() / 1000 + 11644473600;
  12857. var l = t % Math.pow(2,32), h = (t - l) / Math.pow(2,32);
  12858. l *= 1e7; h *= 1e7;
  12859. var w = (l / Math.pow(2,32)) | 0;
  12860. if(w > 0) { l = l % Math.pow(2,32); h += w; }
  12861. var o = new_buf(8); o.write_shift(4, l); o.write_shift(4, h); return o;
  12862. }
  12863. /* [MS-OSHARED] 2.3.3.1.4 Lpstr */
  12864. function parse_lpstr(blob, type, pad) {
  12865. var start = blob.l;
  12866. var str = blob.read_shift(0, 'lpstr-cp');
  12867. if(pad) while((blob.l - start) & 3) ++blob.l;
  12868. return str;
  12869. }
  12870. /* [MS-OSHARED] 2.3.3.1.6 Lpwstr */
  12871. function parse_lpwstr(blob, type, pad) {
  12872. var str = blob.read_shift(0, 'lpwstr');
  12873. if(pad) blob.l += (4 - ((str.length+1) & 3)) & 3;
  12874. return str;
  12875. }
  12876. /* [MS-OSHARED] 2.3.3.1.11 VtString */
  12877. /* [MS-OSHARED] 2.3.3.1.12 VtUnalignedString */
  12878. function parse_VtStringBase(blob, stringType, pad) {
  12879. if(stringType === 0x1F /*VT_LPWSTR*/) return parse_lpwstr(blob);
  12880. return parse_lpstr(blob, stringType, pad);
  12881. }
  12882. function parse_VtString(blob, t, pad) { return parse_VtStringBase(blob, t, pad === false ? 0: 4); }
  12883. function parse_VtUnalignedString(blob, t) { if(!t) throw new Error("VtUnalignedString must have positive length"); return parse_VtStringBase(blob, t, 0); }
  12884. /* [MS-OSHARED] 2.3.3.1.9 VtVecUnalignedLpstrValue */
  12885. function parse_VtVecUnalignedLpstrValue(blob) {
  12886. var length = blob.read_shift(4);
  12887. var ret = [];
  12888. for(var i = 0; i != length; ++i) ret[i] = blob.read_shift(0, 'lpstr-cp').replace(chr0,'');
  12889. return ret;
  12890. }
  12891. /* [MS-OSHARED] 2.3.3.1.10 VtVecUnalignedLpstr */
  12892. function parse_VtVecUnalignedLpstr(blob) {
  12893. return parse_VtVecUnalignedLpstrValue(blob);
  12894. }
  12895. /* [MS-OSHARED] 2.3.3.1.13 VtHeadingPair */
  12896. function parse_VtHeadingPair(blob) {
  12897. var headingString = parse_TypedPropertyValue(blob, VT_USTR);
  12898. var headerParts = parse_TypedPropertyValue(blob, VT_I4);
  12899. return [headingString, headerParts];
  12900. }
  12901. /* [MS-OSHARED] 2.3.3.1.14 VtVecHeadingPairValue */
  12902. function parse_VtVecHeadingPairValue(blob) {
  12903. var cElements = blob.read_shift(4);
  12904. var out = [];
  12905. for(var i = 0; i != cElements / 2; ++i) out.push(parse_VtHeadingPair(blob));
  12906. return out;
  12907. }
  12908. /* [MS-OSHARED] 2.3.3.1.15 VtVecHeadingPair */
  12909. function parse_VtVecHeadingPair(blob) {
  12910. // NOTE: When invoked, wType & padding were already consumed
  12911. return parse_VtVecHeadingPairValue(blob);
  12912. }
  12913. /* [MS-OLEPS] 2.18.1 Dictionary (uses 2.17, 2.16) */
  12914. function parse_dictionary(blob,CodePage) {
  12915. var cnt = blob.read_shift(4);
  12916. var dict = ({});
  12917. for(var j = 0; j != cnt; ++j) {
  12918. var pid = blob.read_shift(4);
  12919. var len = blob.read_shift(4);
  12920. dict[pid] = blob.read_shift(len, (CodePage === 0x4B0 ?'utf16le':'utf8')).replace(chr0,'').replace(chr1,'!');
  12921. if(CodePage === 0x4B0 && (len % 2)) blob.l += 2;
  12922. }
  12923. if(blob.l & 3) blob.l = (blob.l>>2+1)<<2;
  12924. return dict;
  12925. }
  12926. /* [MS-OLEPS] 2.9 BLOB */
  12927. function parse_BLOB(blob) {
  12928. var size = blob.read_shift(4);
  12929. var bytes = blob.slice(blob.l,blob.l+size);
  12930. blob.l += size;
  12931. if((size & 3) > 0) blob.l += (4 - (size & 3)) & 3;
  12932. return bytes;
  12933. }
  12934. /* [MS-OLEPS] 2.11 ClipboardData */
  12935. function parse_ClipboardData(blob) {
  12936. // TODO
  12937. var o = {};
  12938. o.Size = blob.read_shift(4);
  12939. //o.Format = blob.read_shift(4);
  12940. blob.l += o.Size + 3 - (o.Size - 1) % 4;
  12941. return o;
  12942. }
  12943. /* [MS-OLEPS] 2.15 TypedPropertyValue */
  12944. function parse_TypedPropertyValue(blob, type, _opts) {
  12945. var t = blob.read_shift(2), ret, opts = _opts||{};
  12946. blob.l += 2;
  12947. if(type !== VT_VARIANT)
  12948. if(t !== type && VT_CUSTOM.indexOf(type)===-1) throw new Error('Expected type ' + type + ' saw ' + t);
  12949. switch(type === VT_VARIANT ? t : type) {
  12950. case 0x02 /*VT_I2*/: ret = blob.read_shift(2, 'i'); if(!opts.raw) blob.l += 2; return ret;
  12951. case 0x03 /*VT_I4*/: ret = blob.read_shift(4, 'i'); return ret;
  12952. case 0x0B /*VT_BOOL*/: return blob.read_shift(4) !== 0x0;
  12953. case 0x13 /*VT_UI4*/: ret = blob.read_shift(4); return ret;
  12954. case 0x1E /*VT_LPSTR*/: return parse_lpstr(blob, t, 4).replace(chr0,'');
  12955. case 0x1F /*VT_LPWSTR*/: return parse_lpwstr(blob);
  12956. case 0x40 /*VT_FILETIME*/: return parse_FILETIME(blob);
  12957. case 0x41 /*VT_BLOB*/: return parse_BLOB(blob);
  12958. case 0x47 /*VT_CF*/: return parse_ClipboardData(blob);
  12959. case 0x50 /*VT_STRING*/: return parse_VtString(blob, t, !opts.raw).replace(chr0,'');
  12960. case 0x51 /*VT_USTR*/: return parse_VtUnalignedString(blob, t/*, 4*/).replace(chr0,'');
  12961. case 0x100C /*VT_VECTOR|VT_VARIANT*/: return parse_VtVecHeadingPair(blob);
  12962. case 0x101E /*VT_LPSTR*/: return parse_VtVecUnalignedLpstr(blob);
  12963. default: throw new Error("TypedPropertyValue unrecognized type " + type + " " + t);
  12964. }
  12965. }
  12966. function write_TypedPropertyValue(type, value) {
  12967. var o = new_buf(4), p = new_buf(4);
  12968. o.write_shift(4, type == 0x50 ? 0x1F : type);
  12969. switch(type) {
  12970. case 0x03 /*VT_I4*/: p.write_shift(-4, value); break;
  12971. case 0x05 /*VT_I4*/: p = new_buf(8); p.write_shift(8, value, 'f'); break;
  12972. case 0x0B /*VT_BOOL*/: p.write_shift(4, value ? 0x01 : 0x00); break;
  12973. case 0x40 /*VT_FILETIME*/: p = write_FILETIME(value); break;
  12974. case 0x1F /*VT_LPWSTR*/:
  12975. case 0x50 /*VT_STRING*/:
  12976. p = new_buf(4 + 2 * (value.length + 1) + (value.length % 2 ? 0 : 2));
  12977. p.write_shift(4, value.length + 1);
  12978. p.write_shift(0, value, "dbcs");
  12979. while(p.l != p.length) p.write_shift(1, 0);
  12980. break;
  12981. default: throw new Error("TypedPropertyValue unrecognized type " + type + " " + value);
  12982. }
  12983. return bconcat([o, p]);
  12984. }
  12985. /* [MS-OLEPS] 2.20 PropertySet */
  12986. function parse_PropertySet(blob, PIDSI) {
  12987. var start_addr = blob.l;
  12988. var size = blob.read_shift(4);
  12989. var NumProps = blob.read_shift(4);
  12990. var Props = [], i = 0;
  12991. var CodePage = 0;
  12992. var Dictionary = -1, DictObj = ({});
  12993. for(i = 0; i != NumProps; ++i) {
  12994. var PropID = blob.read_shift(4);
  12995. var Offset = blob.read_shift(4);
  12996. Props[i] = [PropID, Offset + start_addr];
  12997. }
  12998. Props.sort(function(x,y) { return x[1] - y[1]; });
  12999. var PropH = {};
  13000. for(i = 0; i != NumProps; ++i) {
  13001. if(blob.l !== Props[i][1]) {
  13002. var fail = true;
  13003. if(i>0 && PIDSI) switch(PIDSI[Props[i-1][0]].t) {
  13004. case 0x02 /*VT_I2*/: if(blob.l+2 === Props[i][1]) { blob.l+=2; fail = false; } break;
  13005. case 0x50 /*VT_STRING*/: if(blob.l <= Props[i][1]) { blob.l=Props[i][1]; fail = false; } break;
  13006. case 0x100C /*VT_VECTOR|VT_VARIANT*/: if(blob.l <= Props[i][1]) { blob.l=Props[i][1]; fail = false; } break;
  13007. }
  13008. if((!PIDSI||i==0) && blob.l <= Props[i][1]) { fail=false; blob.l = Props[i][1]; }
  13009. if(fail) throw new Error("Read Error: Expected address " + Props[i][1] + ' at ' + blob.l + ' :' + i);
  13010. }
  13011. if(PIDSI) {
  13012. var piddsi = PIDSI[Props[i][0]];
  13013. PropH[piddsi.n] = parse_TypedPropertyValue(blob, piddsi.t, {raw:true});
  13014. if(piddsi.p === 'version') PropH[piddsi.n] = String(PropH[piddsi.n] >> 16) + "." + ("0000" + String(PropH[piddsi.n] & 0xFFFF)).slice(-4);
  13015. if(piddsi.n == "CodePage") switch(PropH[piddsi.n]) {
  13016. case 0: PropH[piddsi.n] = 1252;
  13017. /* falls through */
  13018. case 874:
  13019. case 932:
  13020. case 936:
  13021. case 949:
  13022. case 950:
  13023. case 1250:
  13024. case 1251:
  13025. case 1253:
  13026. case 1254:
  13027. case 1255:
  13028. case 1256:
  13029. case 1257:
  13030. case 1258:
  13031. case 10000:
  13032. case 1200:
  13033. case 1201:
  13034. case 1252:
  13035. case 65000: case -536:
  13036. case 65001: case -535:
  13037. set_cp(CodePage = (PropH[piddsi.n]>>>0) & 0xFFFF); break;
  13038. default: throw new Error("Unsupported CodePage: " + PropH[piddsi.n]);
  13039. }
  13040. } else {
  13041. if(Props[i][0] === 0x1) {
  13042. CodePage = PropH.CodePage = (parse_TypedPropertyValue(blob, VT_I2));
  13043. set_cp(CodePage);
  13044. if(Dictionary !== -1) {
  13045. var oldpos = blob.l;
  13046. blob.l = Props[Dictionary][1];
  13047. DictObj = parse_dictionary(blob,CodePage);
  13048. blob.l = oldpos;
  13049. }
  13050. } else if(Props[i][0] === 0) {
  13051. if(CodePage === 0) { Dictionary = i; blob.l = Props[i+1][1]; continue; }
  13052. DictObj = parse_dictionary(blob,CodePage);
  13053. } else {
  13054. var name = DictObj[Props[i][0]];
  13055. var val;
  13056. /* [MS-OSHARED] 2.3.3.2.3.1.2 + PROPVARIANT */
  13057. switch(blob[blob.l]) {
  13058. case 0x41 /*VT_BLOB*/: blob.l += 4; val = parse_BLOB(blob); break;
  13059. case 0x1E /*VT_LPSTR*/: blob.l += 4; val = parse_VtString(blob, blob[blob.l-4]).replace(/\u0000+$/,""); break;
  13060. case 0x1F /*VT_LPWSTR*/: blob.l += 4; val = parse_VtString(blob, blob[blob.l-4]).replace(/\u0000+$/,""); break;
  13061. case 0x03 /*VT_I4*/: blob.l += 4; val = blob.read_shift(4, 'i'); break;
  13062. case 0x13 /*VT_UI4*/: blob.l += 4; val = blob.read_shift(4); break;
  13063. case 0x05 /*VT_R8*/: blob.l += 4; val = blob.read_shift(8, 'f'); break;
  13064. case 0x0B /*VT_BOOL*/: blob.l += 4; val = parsebool(blob, 4); break;
  13065. case 0x40 /*VT_FILETIME*/: blob.l += 4; val = parseDate(parse_FILETIME(blob)); break;
  13066. default: throw new Error("unparsed value: " + blob[blob.l]);
  13067. }
  13068. PropH[name] = val;
  13069. }
  13070. }
  13071. }
  13072. blob.l = start_addr + size; /* step ahead to skip padding */
  13073. return PropH;
  13074. }
  13075. var XLSPSSkip = [ "CodePage", "Thumbnail", "_PID_LINKBASE", "_PID_HLINKS", "SystemIdentifier", "FMTID" ].concat(PseudoPropsPairs);
  13076. function guess_property_type(val) {
  13077. switch(typeof val) {
  13078. case "boolean": return 0x0B;
  13079. case "number": return ((val|0)==val) ? 0x03 : 0x05;
  13080. case "string": return 0x1F;
  13081. case "object": if(val instanceof Date) return 0x40; break;
  13082. }
  13083. return -1;
  13084. }
  13085. function write_PropertySet(entries, RE, PIDSI) {
  13086. var hdr = new_buf(8), piao = [], prop = [];
  13087. var sz = 8, i = 0;
  13088. var pr = new_buf(8), pio = new_buf(8);
  13089. pr.write_shift(4, 0x0002);
  13090. pr.write_shift(4, 0x04B0);
  13091. pio.write_shift(4, 0x0001);
  13092. prop.push(pr); piao.push(pio);
  13093. sz += 8 + pr.length;
  13094. if(!RE) {
  13095. pio = new_buf(8);
  13096. pio.write_shift(4, 0);
  13097. piao.unshift(pio);
  13098. var bufs = [new_buf(4)];
  13099. bufs[0].write_shift(4, entries.length);
  13100. for(i = 0; i < entries.length; ++i) {
  13101. var value = entries[i][0];
  13102. pr = new_buf(4 + 4 + 2 * (value.length + 1) + (value.length % 2 ? 0 : 2));
  13103. pr.write_shift(4, i+2);
  13104. pr.write_shift(4, value.length + 1);
  13105. pr.write_shift(0, value, "dbcs");
  13106. while(pr.l != pr.length) pr.write_shift(1, 0);
  13107. bufs.push(pr);
  13108. }
  13109. pr = bconcat(bufs);
  13110. prop.unshift(pr);
  13111. sz += 8 + pr.length;
  13112. }
  13113. for(i = 0; i < entries.length; ++i) {
  13114. if(RE && !RE[entries[i][0]]) continue;
  13115. if(XLSPSSkip.indexOf(entries[i][0]) > -1) continue;
  13116. if(entries[i][1] == null) continue;
  13117. var val = entries[i][1], idx = 0;
  13118. if(RE) {
  13119. idx = +RE[entries[i][0]];
  13120. var pinfo = (PIDSI)[idx];
  13121. if(pinfo.p == "version" && typeof val == "string") {
  13122. var arr = val.split(".");
  13123. val = ((+arr[0])<<16) + ((+arr[1])||0);
  13124. }
  13125. pr = write_TypedPropertyValue(pinfo.t, val);
  13126. } else {
  13127. var T = guess_property_type(val);
  13128. if(T == -1) { T = 0x1F; val = String(val); }
  13129. pr = write_TypedPropertyValue(T, val);
  13130. }
  13131. prop.push(pr);
  13132. pio = new_buf(8);
  13133. pio.write_shift(4, !RE ? 2+i : idx);
  13134. piao.push(pio);
  13135. sz += 8 + pr.length;
  13136. }
  13137. var w = 8 * (prop.length + 1);
  13138. for(i = 0; i < prop.length; ++i) { piao[i].write_shift(4, w); w += prop[i].length; }
  13139. hdr.write_shift(4, sz);
  13140. hdr.write_shift(4, prop.length);
  13141. return bconcat([hdr].concat(piao).concat(prop));
  13142. }
  13143. /* [MS-OLEPS] 2.21 PropertySetStream */
  13144. function parse_PropertySetStream(file, PIDSI, clsid) {
  13145. var blob = file.content;
  13146. if(!blob) return ({});
  13147. prep_blob(blob, 0);
  13148. var NumSets, FMTID0, FMTID1, Offset0, Offset1 = 0;
  13149. blob.chk('feff', 'Byte Order: ');
  13150. /*var vers = */blob.read_shift(2); // TODO: check version
  13151. var SystemIdentifier = blob.read_shift(4);
  13152. var CLSID = blob.read_shift(16);
  13153. if(CLSID !== CFB.utils.consts.HEADER_CLSID && CLSID !== clsid) throw new Error("Bad PropertySet CLSID " + CLSID);
  13154. NumSets = blob.read_shift(4);
  13155. if(NumSets !== 1 && NumSets !== 2) throw new Error("Unrecognized #Sets: " + NumSets);
  13156. FMTID0 = blob.read_shift(16); Offset0 = blob.read_shift(4);
  13157. if(NumSets === 1 && Offset0 !== blob.l) throw new Error("Length mismatch: " + Offset0 + " !== " + blob.l);
  13158. else if(NumSets === 2) { FMTID1 = blob.read_shift(16); Offset1 = blob.read_shift(4); }
  13159. var PSet0 = parse_PropertySet(blob, PIDSI);
  13160. var rval = ({ SystemIdentifier: SystemIdentifier });
  13161. for(var y in PSet0) rval[y] = PSet0[y];
  13162. //rval.blob = blob;
  13163. rval.FMTID = FMTID0;
  13164. //rval.PSet0 = PSet0;
  13165. if(NumSets === 1) return rval;
  13166. if(Offset1 - blob.l == 2) blob.l += 2;
  13167. if(blob.l !== Offset1) throw new Error("Length mismatch 2: " + blob.l + " !== " + Offset1);
  13168. var PSet1;
  13169. try { PSet1 = parse_PropertySet(blob, null); } catch(e) {/* empty */}
  13170. for(y in PSet1) rval[y] = PSet1[y];
  13171. rval.FMTID = [FMTID0, FMTID1]; // TODO: verify FMTID0/1
  13172. return rval;
  13173. }
  13174. function write_PropertySetStream(entries, clsid, RE, PIDSI, entries2, clsid2) {
  13175. var hdr = new_buf(entries2 ? 68 : 48);
  13176. var bufs = [hdr];
  13177. hdr.write_shift(2, 0xFFFE);
  13178. hdr.write_shift(2, 0x0000); /* TODO: type 1 props */
  13179. hdr.write_shift(4, 0x32363237);
  13180. hdr.write_shift(16, CFB.utils.consts.HEADER_CLSID, "hex");
  13181. hdr.write_shift(4, (entries2 ? 2 : 1));
  13182. hdr.write_shift(16, clsid, "hex");
  13183. hdr.write_shift(4, (entries2 ? 68 : 48));
  13184. var ps0 = write_PropertySet(entries, RE, PIDSI);
  13185. bufs.push(ps0);
  13186. if(entries2) {
  13187. var ps1 = write_PropertySet(entries2, null, null);
  13188. hdr.write_shift(16, clsid2, "hex");
  13189. hdr.write_shift(4, 68 + ps0.length);
  13190. bufs.push(ps1);
  13191. }
  13192. return bconcat(bufs);
  13193. }
  13194. function parsenoop2(blob, length) { blob.read_shift(length); return null; }
  13195. function writezeroes(n, o) { if(!o) o=new_buf(n); for(var j=0; j<n; ++j) o.write_shift(1, 0); return o; }
  13196. function parslurp(blob, length, cb) {
  13197. var arr = [], target = blob.l + length;
  13198. while(blob.l < target) arr.push(cb(blob, target - blob.l));
  13199. if(target !== blob.l) throw new Error("Slurp error");
  13200. return arr;
  13201. }
  13202. function parsebool(blob, length) { return blob.read_shift(length) === 0x1; }
  13203. function writebool(v, o) { if(!o) o=new_buf(2); o.write_shift(2, +!!v); return o; }
  13204. function parseuint16(blob) { return blob.read_shift(2, 'u'); }
  13205. function writeuint16(v, o) { if(!o) o=new_buf(2); o.write_shift(2, v); return o; }
  13206. function parseuint16a(blob, length) { return parslurp(blob,length,parseuint16);}
  13207. /* --- 2.5 Structures --- */
  13208. /* [MS-XLS] 2.5.10 Bes (boolean or error) */
  13209. function parse_Bes(blob) {
  13210. var v = blob.read_shift(1), t = blob.read_shift(1);
  13211. return t === 0x01 ? v : v === 0x01;
  13212. }
  13213. function write_Bes(v, t, o) {
  13214. if(!o) o = new_buf(2);
  13215. o.write_shift(1, +v);
  13216. o.write_shift(1, ((t == 'e') ? 1 : 0));
  13217. return o;
  13218. }
  13219. /* [MS-XLS] 2.5.240 ShortXLUnicodeString */
  13220. function parse_ShortXLUnicodeString(blob, length, opts) {
  13221. var cch = blob.read_shift(opts && opts.biff >= 12 ? 2 : 1);
  13222. var encoding = 'sbcs-cont';
  13223. var cp = current_codepage;
  13224. if(opts && opts.biff >= 8) current_codepage = 1200;
  13225. if(!opts || opts.biff == 8 ) {
  13226. var fHighByte = blob.read_shift(1);
  13227. if(fHighByte) { encoding = 'dbcs-cont'; }
  13228. } else if(opts.biff == 12) {
  13229. encoding = 'wstr';
  13230. }
  13231. if(opts.biff >= 2 && opts.biff <= 5) encoding = 'cpstr';
  13232. var o = cch ? blob.read_shift(cch, encoding) : "";
  13233. current_codepage = cp;
  13234. return o;
  13235. }
  13236. /* 2.5.293 XLUnicodeRichExtendedString */
  13237. function parse_XLUnicodeRichExtendedString(blob) {
  13238. var cp = current_codepage;
  13239. current_codepage = 1200;
  13240. var cch = blob.read_shift(2), flags = blob.read_shift(1);
  13241. var /*fHighByte = flags & 0x1,*/ fExtSt = flags & 0x4, fRichSt = flags & 0x8;
  13242. var width = 1 + (flags & 0x1); // 0x0 -> utf8, 0x1 -> dbcs
  13243. var cRun = 0, cbExtRst;
  13244. var z = {};
  13245. if(fRichSt) cRun = blob.read_shift(2);
  13246. if(fExtSt) cbExtRst = blob.read_shift(4);
  13247. var encoding = width == 2 ? 'dbcs-cont' : 'sbcs-cont';
  13248. var msg = cch === 0 ? "" : blob.read_shift(cch, encoding);
  13249. if(fRichSt) blob.l += 4 * cRun; //TODO: parse this
  13250. if(fExtSt) blob.l += cbExtRst; //TODO: parse this
  13251. z.t = msg;
  13252. if(!fRichSt) { z.raw = "<t>" + z.t + "</t>"; z.r = z.t; }
  13253. current_codepage = cp;
  13254. return z;
  13255. }
  13256. function write_XLUnicodeRichExtendedString(xlstr) {
  13257. var str = (xlstr.t||""), nfmts = 1;
  13258. var hdr = new_buf(3 + (nfmts > 1 ? 2 : 0));
  13259. hdr.write_shift(2, str.length);
  13260. hdr.write_shift(1, (nfmts > 1 ? 0x08 : 0x00) | 0x01);
  13261. if(nfmts > 1) hdr.write_shift(2, nfmts);
  13262. var otext = new_buf(2 * str.length);
  13263. otext.write_shift(2 * str.length, str, 'utf16le');
  13264. var out = [hdr, otext];
  13265. return bconcat(out);
  13266. }
  13267. /* 2.5.296 XLUnicodeStringNoCch */
  13268. function parse_XLUnicodeStringNoCch(blob, cch, opts) {
  13269. var retval;
  13270. if(opts) {
  13271. if(opts.biff >= 2 && opts.biff <= 5) return blob.read_shift(cch, 'cpstr');
  13272. if(opts.biff >= 12) return blob.read_shift(cch, 'dbcs-cont');
  13273. }
  13274. var fHighByte = blob.read_shift(1);
  13275. if(fHighByte===0) { retval = blob.read_shift(cch, 'sbcs-cont'); }
  13276. else { retval = blob.read_shift(cch, 'dbcs-cont'); }
  13277. return retval;
  13278. }
  13279. /* 2.5.294 XLUnicodeString */
  13280. function parse_XLUnicodeString(blob, length, opts) {
  13281. var cch = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  13282. if(cch === 0) { blob.l++; return ""; }
  13283. return parse_XLUnicodeStringNoCch(blob, cch, opts);
  13284. }
  13285. /* BIFF5 override */
  13286. function parse_XLUnicodeString2(blob, length, opts) {
  13287. if(opts.biff > 5) return parse_XLUnicodeString(blob, length, opts);
  13288. var cch = blob.read_shift(1);
  13289. if(cch === 0) { blob.l++; return ""; }
  13290. return blob.read_shift(cch, (opts.biff <= 4 || !blob.lens ) ? 'cpstr' : 'sbcs-cont');
  13291. }
  13292. /* TODO: BIFF5 and lower, codepage awareness */
  13293. function write_XLUnicodeString(str, opts, o) {
  13294. if(!o) o = new_buf(3 + 2 * str.length);
  13295. o.write_shift(2, str.length);
  13296. o.write_shift(1, 1);
  13297. o.write_shift(31, str, 'utf16le');
  13298. return o;
  13299. }
  13300. /* [MS-XLS] 2.5.61 ControlInfo */
  13301. function parse_ControlInfo(blob) {
  13302. var flags = blob.read_shift(1);
  13303. blob.l++;
  13304. var accel = blob.read_shift(2);
  13305. blob.l += 2;
  13306. return [flags, accel];
  13307. }
  13308. /* [MS-OSHARED] 2.3.7.6 URLMoniker TODO: flags */
  13309. function parse_URLMoniker(blob) {
  13310. var len = blob.read_shift(4), start = blob.l;
  13311. var extra = false;
  13312. if(len > 24) {
  13313. /* look ahead */
  13314. blob.l += len - 24;
  13315. if(blob.read_shift(16) === "795881f43b1d7f48af2c825dc4852763") extra = true;
  13316. blob.l = start;
  13317. }
  13318. var url = blob.read_shift((extra?len-24:len)>>1, 'utf16le').replace(chr0,"");
  13319. if(extra) blob.l += 24;
  13320. return url;
  13321. }
  13322. /* [MS-OSHARED] 2.3.7.8 FileMoniker TODO: all fields */
  13323. function parse_FileMoniker(blob) {
  13324. blob.l += 2; //var cAnti = blob.read_shift(2);
  13325. var ansiPath = blob.read_shift(0, 'lpstr-ansi');
  13326. blob.l += 2; //var endServer = blob.read_shift(2);
  13327. if(blob.read_shift(2) != 0xDEAD) throw new Error("Bad FileMoniker");
  13328. var sz = blob.read_shift(4);
  13329. if(sz === 0) return ansiPath.replace(/\\/g,"/");
  13330. var bytes = blob.read_shift(4);
  13331. if(blob.read_shift(2) != 3) throw new Error("Bad FileMoniker");
  13332. var unicodePath = blob.read_shift(bytes>>1, 'utf16le').replace(chr0,"");
  13333. return unicodePath;
  13334. }
  13335. /* [MS-OSHARED] 2.3.7.2 HyperlinkMoniker TODO: all the monikers */
  13336. function parse_HyperlinkMoniker(blob, length) {
  13337. var clsid = blob.read_shift(16); length -= 16;
  13338. switch(clsid) {
  13339. case "e0c9ea79f9bace118c8200aa004ba90b": return parse_URLMoniker(blob, length);
  13340. case "0303000000000000c000000000000046": return parse_FileMoniker(blob, length);
  13341. default: throw new Error("Unsupported Moniker " + clsid);
  13342. }
  13343. }
  13344. /* [MS-OSHARED] 2.3.7.9 HyperlinkString */
  13345. function parse_HyperlinkString(blob) {
  13346. var len = blob.read_shift(4);
  13347. var o = len > 0 ? blob.read_shift(len, 'utf16le').replace(chr0, "") : "";
  13348. return o;
  13349. }
  13350. /* [MS-OSHARED] 2.3.7.1 Hyperlink Object */
  13351. function parse_Hyperlink(blob, length) {
  13352. var end = blob.l + length;
  13353. var sVer = blob.read_shift(4);
  13354. if(sVer !== 2) throw new Error("Unrecognized streamVersion: " + sVer);
  13355. var flags = blob.read_shift(2);
  13356. blob.l += 2;
  13357. var displayName, targetFrameName, moniker, oleMoniker, Loc="", guid, fileTime;
  13358. if(flags & 0x0010) displayName = parse_HyperlinkString(blob, end - blob.l);
  13359. if(flags & 0x0080) targetFrameName = parse_HyperlinkString(blob, end - blob.l);
  13360. if((flags & 0x0101) === 0x0101) moniker = parse_HyperlinkString(blob, end - blob.l);
  13361. if((flags & 0x0101) === 0x0001) oleMoniker = parse_HyperlinkMoniker(blob, end - blob.l);
  13362. if(flags & 0x0008) Loc = parse_HyperlinkString(blob, end - blob.l);
  13363. if(flags & 0x0020) guid = blob.read_shift(16);
  13364. if(flags & 0x0040) fileTime = parse_FILETIME(blob/*, 8*/);
  13365. blob.l = end;
  13366. var target = targetFrameName||moniker||oleMoniker||"";
  13367. if(target && Loc) target+="#"+Loc;
  13368. if(!target) target = "#" + Loc;
  13369. var out = ({Target:target});
  13370. if(guid) out.guid = guid;
  13371. if(fileTime) out.time = fileTime;
  13372. if(displayName) out.Tooltip = displayName;
  13373. return out;
  13374. }
  13375. function write_Hyperlink(hl) {
  13376. var out = new_buf(512), i = 0;
  13377. var Target = hl.Target;
  13378. var F = Target.indexOf("#") > -1 ? 0x1f : 0x17;
  13379. switch(Target.charAt(0)) { case "#": F=0x1c; break; case ".": F&=~2; break; }
  13380. out.write_shift(4,2); out.write_shift(4, F);
  13381. var data = [8,6815827,6619237,4849780,83]; for(i = 0; i < data.length; ++i) out.write_shift(4, data[i]);
  13382. if(F == 0x1C) {
  13383. Target = Target.slice(1);
  13384. out.write_shift(4, Target.length + 1);
  13385. for(i = 0; i < Target.length; ++i) out.write_shift(2, Target.charCodeAt(i));
  13386. out.write_shift(2, 0);
  13387. } else if(F & 0x02) {
  13388. data = "e0 c9 ea 79 f9 ba ce 11 8c 82 00 aa 00 4b a9 0b".split(" ");
  13389. for(i = 0; i < data.length; ++i) out.write_shift(1, parseInt(data[i], 16));
  13390. out.write_shift(4, 2*(Target.length + 1));
  13391. for(i = 0; i < Target.length; ++i) out.write_shift(2, Target.charCodeAt(i));
  13392. out.write_shift(2, 0);
  13393. } else {
  13394. data = "03 03 00 00 00 00 00 00 c0 00 00 00 00 00 00 46".split(" ");
  13395. for(i = 0; i < data.length; ++i) out.write_shift(1, parseInt(data[i], 16));
  13396. var P = 0;
  13397. while(Target.slice(P*3,P*3+3)=="../"||Target.slice(P*3,P*3+3)=="..\\") ++P;
  13398. out.write_shift(2, P);
  13399. out.write_shift(4, Target.length + 1);
  13400. for(i = 0; i < Target.length; ++i) out.write_shift(1, Target.charCodeAt(i) & 0xFF);
  13401. out.write_shift(1, 0);
  13402. out.write_shift(2, 0xFFFF);
  13403. out.write_shift(2, 0xDEAD);
  13404. for(i = 0; i < 6; ++i) out.write_shift(4, 0);
  13405. }
  13406. return out.slice(0, out.l);
  13407. }
  13408. /* 2.5.178 LongRGBA */
  13409. function parse_LongRGBA(blob) { var r = blob.read_shift(1), g = blob.read_shift(1), b = blob.read_shift(1), a = blob.read_shift(1); return [r,g,b,a]; }
  13410. /* 2.5.177 LongRGB */
  13411. function parse_LongRGB(blob, length) { var x = parse_LongRGBA(blob, length); x[3] = 0; return x; }
  13412. /* [MS-XLS] 2.5.19 */
  13413. function parse_XLSCell(blob) {
  13414. var rw = blob.read_shift(2); // 0-indexed
  13415. var col = blob.read_shift(2);
  13416. var ixfe = blob.read_shift(2);
  13417. return ({r:rw, c:col, ixfe:ixfe});
  13418. }
  13419. function write_XLSCell(R, C, ixfe, o) {
  13420. if(!o) o = new_buf(6);
  13421. o.write_shift(2, R);
  13422. o.write_shift(2, C);
  13423. o.write_shift(2, ixfe||0);
  13424. return o;
  13425. }
  13426. /* [MS-XLS] 2.5.134 */
  13427. function parse_frtHeader(blob) {
  13428. var rt = blob.read_shift(2);
  13429. var flags = blob.read_shift(2); // TODO: parse these flags
  13430. blob.l += 8;
  13431. return {type: rt, flags: flags};
  13432. }
  13433. function parse_OptXLUnicodeString(blob, length, opts) { return length === 0 ? "" : parse_XLUnicodeString2(blob, length, opts); }
  13434. /* [MS-XLS] 2.5.344 */
  13435. function parse_XTI(blob, length, opts) {
  13436. var w = opts.biff > 8 ? 4 : 2;
  13437. var iSupBook = blob.read_shift(w), itabFirst = blob.read_shift(w,'i'), itabLast = blob.read_shift(w,'i');
  13438. return [iSupBook, itabFirst, itabLast];
  13439. }
  13440. /* [MS-XLS] 2.5.218 */
  13441. function parse_RkRec(blob) {
  13442. var ixfe = blob.read_shift(2);
  13443. var RK = parse_RkNumber(blob);
  13444. return [ixfe, RK];
  13445. }
  13446. /* [MS-XLS] 2.5.1 */
  13447. function parse_AddinUdf(blob, length, opts) {
  13448. blob.l += 4; length -= 4;
  13449. var l = blob.l + length;
  13450. var udfName = parse_ShortXLUnicodeString(blob, length, opts);
  13451. var cb = blob.read_shift(2);
  13452. l -= blob.l;
  13453. if(cb !== l) throw new Error("Malformed AddinUdf: padding = " + l + " != " + cb);
  13454. blob.l += cb;
  13455. return udfName;
  13456. }
  13457. /* [MS-XLS] 2.5.209 TODO: Check sizes */
  13458. function parse_Ref8U(blob) {
  13459. var rwFirst = blob.read_shift(2);
  13460. var rwLast = blob.read_shift(2);
  13461. var colFirst = blob.read_shift(2);
  13462. var colLast = blob.read_shift(2);
  13463. return {s:{c:colFirst, r:rwFirst}, e:{c:colLast,r:rwLast}};
  13464. }
  13465. function write_Ref8U(r, o) {
  13466. if(!o) o = new_buf(8);
  13467. o.write_shift(2, r.s.r);
  13468. o.write_shift(2, r.e.r);
  13469. o.write_shift(2, r.s.c);
  13470. o.write_shift(2, r.e.c);
  13471. return o;
  13472. }
  13473. /* [MS-XLS] 2.5.211 */
  13474. function parse_RefU(blob) {
  13475. var rwFirst = blob.read_shift(2);
  13476. var rwLast = blob.read_shift(2);
  13477. var colFirst = blob.read_shift(1);
  13478. var colLast = blob.read_shift(1);
  13479. return {s:{c:colFirst, r:rwFirst}, e:{c:colLast,r:rwLast}};
  13480. }
  13481. /* [MS-XLS] 2.5.207 */
  13482. var parse_Ref = parse_RefU;
  13483. /* [MS-XLS] 2.5.143 */
  13484. function parse_FtCmo(blob) {
  13485. blob.l += 4;
  13486. var ot = blob.read_shift(2);
  13487. var id = blob.read_shift(2);
  13488. var flags = blob.read_shift(2);
  13489. blob.l+=12;
  13490. return [id, ot, flags];
  13491. }
  13492. /* [MS-XLS] 2.5.149 */
  13493. function parse_FtNts(blob) {
  13494. var out = {};
  13495. blob.l += 4;
  13496. blob.l += 16; // GUID TODO
  13497. out.fSharedNote = blob.read_shift(2);
  13498. blob.l += 4;
  13499. return out;
  13500. }
  13501. /* [MS-XLS] 2.5.142 */
  13502. function parse_FtCf(blob) {
  13503. var out = {};
  13504. blob.l += 4;
  13505. blob.cf = blob.read_shift(2);
  13506. return out;
  13507. }
  13508. /* [MS-XLS] 2.5.140 - 2.5.154 and friends */
  13509. function parse_FtSkip(blob) { blob.l += 2; blob.l += blob.read_shift(2); }
  13510. var FtTab = {
  13511. 0x00: parse_FtSkip, /* FtEnd */
  13512. 0x04: parse_FtSkip, /* FtMacro */
  13513. 0x05: parse_FtSkip, /* FtButton */
  13514. 0x06: parse_FtSkip, /* FtGmo */
  13515. 0x07: parse_FtCf, /* FtCf */
  13516. 0x08: parse_FtSkip, /* FtPioGrbit */
  13517. 0x09: parse_FtSkip, /* FtPictFmla */
  13518. 0x0A: parse_FtSkip, /* FtCbls */
  13519. 0x0B: parse_FtSkip, /* FtRbo */
  13520. 0x0C: parse_FtSkip, /* FtSbs */
  13521. 0x0D: parse_FtNts, /* FtNts */
  13522. 0x0E: parse_FtSkip, /* FtSbsFmla */
  13523. 0x0F: parse_FtSkip, /* FtGboData */
  13524. 0x10: parse_FtSkip, /* FtEdoData */
  13525. 0x11: parse_FtSkip, /* FtRboData */
  13526. 0x12: parse_FtSkip, /* FtCblsData */
  13527. 0x13: parse_FtSkip, /* FtLbsData */
  13528. 0x14: parse_FtSkip, /* FtCblsFmla */
  13529. 0x15: parse_FtCmo
  13530. };
  13531. function parse_FtArray(blob, length) {
  13532. var tgt = blob.l + length;
  13533. var fts = [];
  13534. while(blob.l < tgt) {
  13535. var ft = blob.read_shift(2);
  13536. blob.l-=2;
  13537. try {
  13538. fts.push(FtTab[ft](blob, tgt - blob.l));
  13539. } catch(e) { blob.l = tgt; return fts; }
  13540. }
  13541. if(blob.l != tgt) blob.l = tgt; //throw new Error("bad Object Ft-sequence");
  13542. return fts;
  13543. }
  13544. /* --- 2.4 Records --- */
  13545. /* [MS-XLS] 2.4.21 */
  13546. function parse_BOF(blob, length) {
  13547. var o = {BIFFVer:0, dt:0};
  13548. o.BIFFVer = blob.read_shift(2); length -= 2;
  13549. if(length >= 2) { o.dt = blob.read_shift(2); blob.l -= 2; }
  13550. switch(o.BIFFVer) {
  13551. case 0x0600: /* BIFF8 */
  13552. case 0x0500: /* BIFF5 */
  13553. case 0x0400: /* BIFF4 */
  13554. case 0x0300: /* BIFF3 */
  13555. case 0x0200: /* BIFF2 */
  13556. case 0x0002: case 0x0007: /* BIFF2 */
  13557. break;
  13558. default: if(length > 6) throw new Error("Unexpected BIFF Ver " + o.BIFFVer);
  13559. }
  13560. blob.read_shift(length);
  13561. return o;
  13562. }
  13563. function write_BOF(wb, t, o) {
  13564. var h = 0x0600, w = 16;
  13565. switch(o.bookType) {
  13566. case 'biff8': break;
  13567. case 'biff5': h = 0x0500; w = 8; break;
  13568. case 'biff4': h = 0x0004; w = 6; break;
  13569. case 'biff3': h = 0x0003; w = 6; break;
  13570. case 'biff2': h = 0x0002; w = 4; break;
  13571. case 'xla': break;
  13572. default: throw new Error("unsupported BIFF version");
  13573. }
  13574. var out = new_buf(w);
  13575. out.write_shift(2, h);
  13576. out.write_shift(2, t);
  13577. if(w > 4) out.write_shift(2, 0x7262);
  13578. if(w > 6) out.write_shift(2, 0x07CD);
  13579. if(w > 8) {
  13580. out.write_shift(2, 0xC009);
  13581. out.write_shift(2, 0x0001);
  13582. out.write_shift(2, 0x0706);
  13583. out.write_shift(2, 0x0000);
  13584. }
  13585. return out;
  13586. }
  13587. /* [MS-XLS] 2.4.146 */
  13588. function parse_InterfaceHdr(blob, length) {
  13589. if(length === 0) return 0x04b0;
  13590. if((blob.read_shift(2))!==0x04b0){/* empty */}
  13591. return 0x04b0;
  13592. }
  13593. /* [MS-XLS] 2.4.349 */
  13594. function parse_WriteAccess(blob, length, opts) {
  13595. if(opts.enc) { blob.l += length; return ""; }
  13596. var l = blob.l;
  13597. // TODO: make sure XLUnicodeString doesnt overrun
  13598. var UserName = parse_XLUnicodeString2(blob, 0, opts);
  13599. blob.read_shift(length + l - blob.l);
  13600. return UserName;
  13601. }
  13602. function write_WriteAccess(s, opts) {
  13603. var b8 = !opts || opts.biff == 8;
  13604. var o = new_buf(b8 ? 112 : 54);
  13605. o.write_shift(opts.biff == 8 ? 2 : 1, 7);
  13606. if(b8) o.write_shift(1, 0);
  13607. o.write_shift(4, 0x33336853);
  13608. o.write_shift(4, (0x00534A74 | (b8 ? 0 : 0x20000000)));
  13609. while(o.l < o.length) o.write_shift(1, (b8 ? 0 : 32));
  13610. return o;
  13611. }
  13612. /* [MS-XLS] 2.4.351 */
  13613. function parse_WsBool(blob, length, opts) {
  13614. var flags = opts && opts.biff == 8 || length == 2 ? blob.read_shift(2) : (blob.l += length, 0);
  13615. return { fDialog: flags & 0x10 };
  13616. }
  13617. /* [MS-XLS] 2.4.28 */
  13618. function parse_BoundSheet8(blob, length, opts) {
  13619. var pos = blob.read_shift(4);
  13620. var hidden = blob.read_shift(1) & 0x03;
  13621. var dt = blob.read_shift(1);
  13622. switch(dt) {
  13623. case 0: dt = 'Worksheet'; break;
  13624. case 1: dt = 'Macrosheet'; break;
  13625. case 2: dt = 'Chartsheet'; break;
  13626. case 6: dt = 'VBAModule'; break;
  13627. }
  13628. var name = parse_ShortXLUnicodeString(blob, 0, opts);
  13629. if(name.length === 0) name = "Sheet1";
  13630. return { pos:pos, hs:hidden, dt:dt, name:name };
  13631. }
  13632. function write_BoundSheet8(data, opts) {
  13633. var w = (!opts || opts.biff >= 8 ? 2 : 1);
  13634. var o = new_buf(8 + w * data.name.length);
  13635. o.write_shift(4, data.pos);
  13636. o.write_shift(1, data.hs || 0);
  13637. o.write_shift(1, data.dt);
  13638. o.write_shift(1, data.name.length);
  13639. if(opts.biff >= 8) o.write_shift(1, 1);
  13640. o.write_shift(w * data.name.length, data.name, opts.biff < 8 ? 'sbcs' : 'utf16le');
  13641. var out = o.slice(0, o.l);
  13642. out.l = o.l; return out;
  13643. }
  13644. /* [MS-XLS] 2.4.265 TODO */
  13645. function parse_SST(blob, length) {
  13646. var end = blob.l + length;
  13647. var cnt = blob.read_shift(4);
  13648. var ucnt = blob.read_shift(4);
  13649. var strs = ([]);
  13650. for(var i = 0; i != ucnt && blob.l < end; ++i) {
  13651. strs.push(parse_XLUnicodeRichExtendedString(blob));
  13652. }
  13653. strs.Count = cnt; strs.Unique = ucnt;
  13654. return strs;
  13655. }
  13656. function write_SST(sst, opts) {
  13657. var header = new_buf(8);
  13658. header.write_shift(4, sst.Count);
  13659. header.write_shift(4, sst.Unique);
  13660. var strs = [];
  13661. for(var j = 0; j < sst.length; ++j) strs[j] = write_XLUnicodeRichExtendedString(sst[j], opts);
  13662. var o = bconcat([header].concat(strs));
  13663. o.parts = [header.length].concat(strs.map(function(str) { return str.length; }));
  13664. return o;
  13665. }
  13666. /* [MS-XLS] 2.4.107 */
  13667. function parse_ExtSST(blob, length) {
  13668. var extsst = {};
  13669. extsst.dsst = blob.read_shift(2);
  13670. blob.l += length-2;
  13671. return extsst;
  13672. }
  13673. /* [MS-XLS] 2.4.221 TODO: check BIFF2-4 */
  13674. function parse_Row(blob) {
  13675. var z = ({});
  13676. z.r = blob.read_shift(2);
  13677. z.c = blob.read_shift(2);
  13678. z.cnt = blob.read_shift(2) - z.c;
  13679. var miyRw = blob.read_shift(2);
  13680. blob.l += 4; // reserved(2), unused(2)
  13681. var flags = blob.read_shift(1); // various flags
  13682. blob.l += 3; // reserved(8), ixfe(12), flags(4)
  13683. if(flags & 0x07) z.level = flags & 0x07;
  13684. // collapsed: flags & 0x10
  13685. if(flags & 0x20) z.hidden = true;
  13686. if(flags & 0x40) z.hpt = miyRw / 20;
  13687. return z;
  13688. }
  13689. /* [MS-XLS] 2.4.125 */
  13690. function parse_ForceFullCalculation(blob) {
  13691. var header = parse_frtHeader(blob);
  13692. if(header.type != 0x08A3) throw new Error("Invalid Future Record " + header.type);
  13693. var fullcalc = blob.read_shift(4);
  13694. return fullcalc !== 0x0;
  13695. }
  13696. /* [MS-XLS] 2.4.215 rt */
  13697. function parse_RecalcId(blob) {
  13698. blob.read_shift(2);
  13699. return blob.read_shift(4);
  13700. }
  13701. /* [MS-XLS] 2.4.87 */
  13702. function parse_DefaultRowHeight(blob, length, opts) {
  13703. var f = 0;
  13704. if(!(opts && opts.biff == 2)) {
  13705. f = blob.read_shift(2);
  13706. }
  13707. var miyRw = blob.read_shift(2);
  13708. if((opts && opts.biff == 2)) {
  13709. f = 1 - (miyRw >> 15); miyRw &= 0x7fff;
  13710. }
  13711. var fl = {Unsynced:f&1,DyZero:(f&2)>>1,ExAsc:(f&4)>>2,ExDsc:(f&8)>>3};
  13712. return [fl, miyRw];
  13713. }
  13714. /* [MS-XLS] 2.4.345 TODO */
  13715. function parse_Window1(blob) {
  13716. var xWn = blob.read_shift(2), yWn = blob.read_shift(2), dxWn = blob.read_shift(2), dyWn = blob.read_shift(2);
  13717. var flags = blob.read_shift(2), iTabCur = blob.read_shift(2), iTabFirst = blob.read_shift(2);
  13718. var ctabSel = blob.read_shift(2), wTabRatio = blob.read_shift(2);
  13719. return { Pos: [xWn, yWn], Dim: [dxWn, dyWn], Flags: flags, CurTab: iTabCur,
  13720. FirstTab: iTabFirst, Selected: ctabSel, TabRatio: wTabRatio };
  13721. }
  13722. function write_Window1() {
  13723. var o = new_buf(18);
  13724. o.write_shift(2, 0);
  13725. o.write_shift(2, 0);
  13726. o.write_shift(2, 0x7260);
  13727. o.write_shift(2, 0x44c0);
  13728. o.write_shift(2, 0x38);
  13729. o.write_shift(2, 0);
  13730. o.write_shift(2, 0);
  13731. o.write_shift(2, 1);
  13732. o.write_shift(2, 0x01f4);
  13733. return o;
  13734. }
  13735. /* [MS-XLS] 2.4.346 TODO */
  13736. function parse_Window2(blob, length, opts) {
  13737. if(opts && opts.biff >= 2 && opts.biff < 5) return {};
  13738. var f = blob.read_shift(2);
  13739. return { RTL: f & 0x40 };
  13740. }
  13741. function write_Window2(view) {
  13742. var o = new_buf(18), f = 0x6b6;
  13743. if(view && view.RTL) f |= 0x40;
  13744. o.write_shift(2, f);
  13745. o.write_shift(4, 0);
  13746. o.write_shift(4, 64);
  13747. o.write_shift(4, 0);
  13748. o.write_shift(4, 0);
  13749. return o;
  13750. }
  13751. /* [MS-XLS] 2.4.189 TODO */
  13752. function parse_Pane(/*blob, length, opts*/) {
  13753. }
  13754. /* [MS-XLS] 2.4.122 TODO */
  13755. function parse_Font(blob, length, opts) {
  13756. var o = {
  13757. dyHeight: blob.read_shift(2),
  13758. fl: blob.read_shift(2)
  13759. };
  13760. switch((opts && opts.biff) || 8) {
  13761. case 2: break;
  13762. case 3: case 4: blob.l += 2; break;
  13763. default: blob.l += 10; break;
  13764. }
  13765. o.name = parse_ShortXLUnicodeString(blob, 0, opts);
  13766. return o;
  13767. }
  13768. function write_Font(data, opts) {
  13769. var name = data.name || "Arial";
  13770. var b5 = (opts && (opts.biff == 5)), w = (b5 ? (15 + name.length) : (16 + 2 * name.length));
  13771. var o = new_buf(w);
  13772. o.write_shift(2, (data.sz || 12) * 20);
  13773. o.write_shift(4, 0);
  13774. o.write_shift(2, 400);
  13775. o.write_shift(4, 0);
  13776. o.write_shift(2, 0);
  13777. o.write_shift(1, name.length);
  13778. if(!b5) o.write_shift(1, 1);
  13779. o.write_shift((b5 ? 1 : 2) * name.length, name, (b5 ? "sbcs" : "utf16le"));
  13780. return o;
  13781. }
  13782. /* [MS-XLS] 2.4.149 */
  13783. function parse_LabelSst(blob) {
  13784. var cell = parse_XLSCell(blob);
  13785. cell.isst = blob.read_shift(4);
  13786. return cell;
  13787. }
  13788. function write_LabelSst(R, C, v, os ) {
  13789. var o = new_buf(10);
  13790. write_XLSCell(R, C, os, o);
  13791. o.write_shift(4, v);
  13792. return o;
  13793. }
  13794. /* [MS-XLS] 2.4.148 */
  13795. function parse_Label(blob, length, opts) {
  13796. var target = blob.l + length;
  13797. var cell = parse_XLSCell(blob, 6);
  13798. if(opts.biff == 2) blob.l++;
  13799. var str = parse_XLUnicodeString(blob, target - blob.l, opts);
  13800. cell.val = str;
  13801. return cell;
  13802. }
  13803. function write_Label(R, C, v, os, opts) {
  13804. var b8 = !opts || opts.biff == 8;
  13805. var o = new_buf(6 + 2 + (+b8) + (1 + b8) * v.length);
  13806. write_XLSCell(R, C, os, o);
  13807. o.write_shift(2, v.length);
  13808. if(b8) o.write_shift(1, 1);
  13809. o.write_shift((1 + b8) * v.length, v, b8 ? 'utf16le' : 'sbcs');
  13810. return o;
  13811. }
  13812. /* [MS-XLS] 2.4.126 Number Formats */
  13813. function parse_Format(blob, length, opts) {
  13814. var numFmtId = blob.read_shift(2);
  13815. var fmtstr = parse_XLUnicodeString2(blob, 0, opts);
  13816. return [numFmtId, fmtstr];
  13817. }
  13818. function write_Format(i, f, opts, o) {
  13819. var b5 = (opts && (opts.biff == 5));
  13820. if(!o) o = new_buf(b5 ? (3 + f.length) : (5 + 2 * f.length));
  13821. o.write_shift(2, i);
  13822. o.write_shift((b5 ? 1 : 2), f.length);
  13823. if(!b5) o.write_shift(1, 1);
  13824. o.write_shift((b5 ? 1 : 2) * f.length, f, (b5 ? 'sbcs' : 'utf16le'));
  13825. var out = (o.length > o.l) ? o.slice(0, o.l) : o;
  13826. if(out.l == null) out.l = out.length;
  13827. return out;
  13828. }
  13829. var parse_BIFF2Format = parse_XLUnicodeString2;
  13830. /* [MS-XLS] 2.4.90 */
  13831. function parse_Dimensions(blob, length, opts) {
  13832. var end = blob.l + length;
  13833. var w = opts.biff == 8 || !opts.biff ? 4 : 2;
  13834. var r = blob.read_shift(w), R = blob.read_shift(w);
  13835. var c = blob.read_shift(2), C = blob.read_shift(2);
  13836. blob.l = end;
  13837. return {s: {r:r, c:c}, e: {r:R, c:C}};
  13838. }
  13839. function write_Dimensions(range, opts) {
  13840. var w = opts.biff == 8 || !opts.biff ? 4 : 2;
  13841. var o = new_buf(2*w + 6);
  13842. o.write_shift(w, range.s.r);
  13843. o.write_shift(w, range.e.r + 1);
  13844. o.write_shift(2, range.s.c);
  13845. o.write_shift(2, range.e.c + 1);
  13846. o.write_shift(2, 0);
  13847. return o;
  13848. }
  13849. /* [MS-XLS] 2.4.220 */
  13850. function parse_RK(blob) {
  13851. var rw = blob.read_shift(2), col = blob.read_shift(2);
  13852. var rkrec = parse_RkRec(blob);
  13853. return {r:rw, c:col, ixfe:rkrec[0], rknum:rkrec[1]};
  13854. }
  13855. /* [MS-XLS] 2.4.175 */
  13856. function parse_MulRk(blob, length) {
  13857. var target = blob.l + length - 2;
  13858. var rw = blob.read_shift(2), col = blob.read_shift(2);
  13859. var rkrecs = [];
  13860. while(blob.l < target) rkrecs.push(parse_RkRec(blob));
  13861. if(blob.l !== target) throw new Error("MulRK read error");
  13862. var lastcol = blob.read_shift(2);
  13863. if(rkrecs.length != lastcol - col + 1) throw new Error("MulRK length mismatch");
  13864. return {r:rw, c:col, C:lastcol, rkrec:rkrecs};
  13865. }
  13866. /* [MS-XLS] 2.4.174 */
  13867. function parse_MulBlank(blob, length) {
  13868. var target = blob.l + length - 2;
  13869. var rw = blob.read_shift(2), col = blob.read_shift(2);
  13870. var ixfes = [];
  13871. while(blob.l < target) ixfes.push(blob.read_shift(2));
  13872. if(blob.l !== target) throw new Error("MulBlank read error");
  13873. var lastcol = blob.read_shift(2);
  13874. if(ixfes.length != lastcol - col + 1) throw new Error("MulBlank length mismatch");
  13875. return {r:rw, c:col, C:lastcol, ixfe:ixfes};
  13876. }
  13877. /* [MS-XLS] 2.5.20 2.5.249 TODO: interpret values here */
  13878. function parse_CellStyleXF(blob, length, style, opts) {
  13879. var o = {};
  13880. var a = blob.read_shift(4), b = blob.read_shift(4);
  13881. var c = blob.read_shift(4), d = blob.read_shift(2);
  13882. o.patternType = XLSFillPattern[c >> 26];
  13883. if(!opts.cellStyles) return o;
  13884. o.alc = a & 0x07;
  13885. o.fWrap = (a >> 3) & 0x01;
  13886. o.alcV = (a >> 4) & 0x07;
  13887. o.fJustLast = (a >> 7) & 0x01;
  13888. o.trot = (a >> 8) & 0xFF;
  13889. o.cIndent = (a >> 16) & 0x0F;
  13890. o.fShrinkToFit = (a >> 20) & 0x01;
  13891. o.iReadOrder = (a >> 22) & 0x02;
  13892. o.fAtrNum = (a >> 26) & 0x01;
  13893. o.fAtrFnt = (a >> 27) & 0x01;
  13894. o.fAtrAlc = (a >> 28) & 0x01;
  13895. o.fAtrBdr = (a >> 29) & 0x01;
  13896. o.fAtrPat = (a >> 30) & 0x01;
  13897. o.fAtrProt = (a >> 31) & 0x01;
  13898. o.dgLeft = b & 0x0F;
  13899. o.dgRight = (b >> 4) & 0x0F;
  13900. o.dgTop = (b >> 8) & 0x0F;
  13901. o.dgBottom = (b >> 12) & 0x0F;
  13902. o.icvLeft = (b >> 16) & 0x7F;
  13903. o.icvRight = (b >> 23) & 0x7F;
  13904. o.grbitDiag = (b >> 30) & 0x03;
  13905. o.icvTop = c & 0x7F;
  13906. o.icvBottom = (c >> 7) & 0x7F;
  13907. o.icvDiag = (c >> 14) & 0x7F;
  13908. o.dgDiag = (c >> 21) & 0x0F;
  13909. o.icvFore = d & 0x7F;
  13910. o.icvBack = (d >> 7) & 0x7F;
  13911. o.fsxButton = (d >> 14) & 0x01;
  13912. return o;
  13913. }
  13914. //function parse_CellXF(blob, length, opts) {return parse_CellStyleXF(blob,length,0, opts);}
  13915. //function parse_StyleXF(blob, length, opts) {return parse_CellStyleXF(blob,length,1, opts);}
  13916. /* [MS-XLS] 2.4.353 TODO: actually do this right */
  13917. function parse_XF(blob, length, opts) {
  13918. var o = {};
  13919. o.ifnt = blob.read_shift(2); o.numFmtId = blob.read_shift(2); o.flags = blob.read_shift(2);
  13920. o.fStyle = (o.flags >> 2) & 0x01;
  13921. length -= 6;
  13922. o.data = parse_CellStyleXF(blob, length, o.fStyle, opts);
  13923. return o;
  13924. }
  13925. function write_XF(data, ixfeP, opts, o) {
  13926. var b5 = (opts && (opts.biff == 5));
  13927. if(!o) o = new_buf(b5 ? 16 : 20);
  13928. o.write_shift(2, 0);
  13929. if(data.style) {
  13930. o.write_shift(2, (data.numFmtId||0));
  13931. o.write_shift(2, 0xFFF4);
  13932. } else {
  13933. o.write_shift(2, (data.numFmtId||0));
  13934. o.write_shift(2, (ixfeP<<4));
  13935. }
  13936. o.write_shift(4, 0);
  13937. o.write_shift(4, 0);
  13938. if(!b5) o.write_shift(4, 0);
  13939. o.write_shift(2, 0);
  13940. return o;
  13941. }
  13942. /* [MS-XLS] 2.4.134 */
  13943. function parse_Guts(blob) {
  13944. blob.l += 4;
  13945. var out = [blob.read_shift(2), blob.read_shift(2)];
  13946. if(out[0] !== 0) out[0]--;
  13947. if(out[1] !== 0) out[1]--;
  13948. if(out[0] > 7 || out[1] > 7) throw new Error("Bad Gutters: " + out.join("|"));
  13949. return out;
  13950. }
  13951. function write_Guts(guts) {
  13952. var o = new_buf(8);
  13953. o.write_shift(4, 0);
  13954. o.write_shift(2, guts[0] ? guts[0] + 1 : 0);
  13955. o.write_shift(2, guts[1] ? guts[1] + 1 : 0);
  13956. return o;
  13957. }
  13958. /* [MS-XLS] 2.4.24 */
  13959. function parse_BoolErr(blob, length, opts) {
  13960. var cell = parse_XLSCell(blob, 6);
  13961. if(opts.biff == 2) ++blob.l;
  13962. var val = parse_Bes(blob, 2);
  13963. cell.val = val;
  13964. cell.t = (val === true || val === false) ? 'b' : 'e';
  13965. return cell;
  13966. }
  13967. function write_BoolErr(R, C, v, os, opts, t) {
  13968. var o = new_buf(8);
  13969. write_XLSCell(R, C, os, o);
  13970. write_Bes(v, t, o);
  13971. return o;
  13972. }
  13973. /* [MS-XLS] 2.4.180 Number */
  13974. function parse_Number(blob) {
  13975. var cell = parse_XLSCell(blob, 6);
  13976. var xnum = parse_Xnum(blob, 8);
  13977. cell.val = xnum;
  13978. return cell;
  13979. }
  13980. function write_Number(R, C, v, os) {
  13981. var o = new_buf(14);
  13982. write_XLSCell(R, C, os, o);
  13983. write_Xnum(v, o);
  13984. return o;
  13985. }
  13986. var parse_XLHeaderFooter = parse_OptXLUnicodeString; // TODO: parse 2.4.136
  13987. /* [MS-XLS] 2.4.271 */
  13988. function parse_SupBook(blob, length, opts) {
  13989. var end = blob.l + length;
  13990. var ctab = blob.read_shift(2);
  13991. var cch = blob.read_shift(2);
  13992. opts.sbcch = cch;
  13993. if(cch == 0x0401 || cch == 0x3A01) return [cch, ctab];
  13994. if(cch < 0x01 || cch >0xff) throw new Error("Unexpected SupBook type: "+cch);
  13995. var virtPath = parse_XLUnicodeStringNoCch(blob, cch);
  13996. /* TODO: 2.5.277 Virtual Path */
  13997. var rgst = [];
  13998. while(end > blob.l) rgst.push(parse_XLUnicodeString(blob));
  13999. return [cch, ctab, virtPath, rgst];
  14000. }
  14001. /* [MS-XLS] 2.4.105 TODO */
  14002. function parse_ExternName(blob, length, opts) {
  14003. var flags = blob.read_shift(2);
  14004. var body;
  14005. var o = ({
  14006. fBuiltIn: flags & 0x01,
  14007. fWantAdvise: (flags >>> 1) & 0x01,
  14008. fWantPict: (flags >>> 2) & 0x01,
  14009. fOle: (flags >>> 3) & 0x01,
  14010. fOleLink: (flags >>> 4) & 0x01,
  14011. cf: (flags >>> 5) & 0x3FF,
  14012. fIcon: flags >>> 15 & 0x01
  14013. });
  14014. if(opts.sbcch === 0x3A01) body = parse_AddinUdf(blob, length-2, opts);
  14015. //else throw new Error("unsupported SupBook cch: " + opts.sbcch);
  14016. o.body = body || blob.read_shift(length-2);
  14017. if(typeof body === "string") o.Name = body;
  14018. return o;
  14019. }
  14020. /* [MS-XLS] 2.4.150 TODO */
  14021. var XLSLblBuiltIn = [
  14022. "_xlnm.Consolidate_Area",
  14023. "_xlnm.Auto_Open",
  14024. "_xlnm.Auto_Close",
  14025. "_xlnm.Extract",
  14026. "_xlnm.Database",
  14027. "_xlnm.Criteria",
  14028. "_xlnm.Print_Area",
  14029. "_xlnm.Print_Titles",
  14030. "_xlnm.Recorder",
  14031. "_xlnm.Data_Form",
  14032. "_xlnm.Auto_Activate",
  14033. "_xlnm.Auto_Deactivate",
  14034. "_xlnm.Sheet_Title",
  14035. "_xlnm._FilterDatabase"
  14036. ];
  14037. function parse_Lbl(blob, length, opts) {
  14038. var target = blob.l + length;
  14039. var flags = blob.read_shift(2);
  14040. var chKey = blob.read_shift(1);
  14041. var cch = blob.read_shift(1);
  14042. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  14043. var itab = 0;
  14044. if(!opts || opts.biff >= 5) {
  14045. if(opts.biff != 5) blob.l += 2;
  14046. itab = blob.read_shift(2);
  14047. if(opts.biff == 5) blob.l += 2;
  14048. blob.l += 4;
  14049. }
  14050. var name = parse_XLUnicodeStringNoCch(blob, cch, opts);
  14051. if(flags & 0x20) name = XLSLblBuiltIn[name.charCodeAt(0)];
  14052. var npflen = target - blob.l; if(opts && opts.biff == 2) --npflen;
  14053. var rgce = target == blob.l || cce === 0 ? [] : parse_NameParsedFormula(blob, npflen, opts, cce);
  14054. return {
  14055. chKey: chKey,
  14056. Name: name,
  14057. itab: itab,
  14058. rgce: rgce
  14059. };
  14060. }
  14061. /* [MS-XLS] 2.4.106 TODO: verify filename encoding */
  14062. function parse_ExternSheet(blob, length, opts) {
  14063. if(opts.biff < 8) return parse_BIFF5ExternSheet(blob, length, opts);
  14064. var o = [], target = blob.l + length, len = blob.read_shift(opts.biff > 8 ? 4 : 2);
  14065. while(len-- !== 0) o.push(parse_XTI(blob, opts.biff > 8 ? 12 : 6, opts));
  14066. // [iSupBook, itabFirst, itabLast];
  14067. if(blob.l != target) throw new Error("Bad ExternSheet: " + blob.l + " != " + target);
  14068. return o;
  14069. }
  14070. function parse_BIFF5ExternSheet(blob, length, opts) {
  14071. if(blob[blob.l + 1] == 0x03) blob[blob.l]++;
  14072. var o = parse_ShortXLUnicodeString(blob, length, opts);
  14073. return o.charCodeAt(0) == 0x03 ? o.slice(1) : o;
  14074. }
  14075. /* [MS-XLS] 2.4.176 TODO: check older biff */
  14076. function parse_NameCmt(blob, length, opts) {
  14077. if(opts.biff < 8) { blob.l += length; return; }
  14078. var cchName = blob.read_shift(2);
  14079. var cchComment = blob.read_shift(2);
  14080. var name = parse_XLUnicodeStringNoCch(blob, cchName, opts);
  14081. var comment = parse_XLUnicodeStringNoCch(blob, cchComment, opts);
  14082. return [name, comment];
  14083. }
  14084. /* [MS-XLS] 2.4.260 */
  14085. function parse_ShrFmla(blob, length, opts) {
  14086. var ref = parse_RefU(blob, 6);
  14087. blob.l++;
  14088. var cUse = blob.read_shift(1);
  14089. length -= 8;
  14090. return [parse_SharedParsedFormula(blob, length, opts), cUse, ref];
  14091. }
  14092. /* [MS-XLS] 2.4.4 TODO */
  14093. function parse_Array(blob, length, opts) {
  14094. var ref = parse_Ref(blob, 6);
  14095. /* TODO: fAlwaysCalc */
  14096. switch(opts.biff) {
  14097. case 2: blob.l ++; length -= 7; break;
  14098. case 3: case 4: blob.l += 2; length -= 8; break;
  14099. default: blob.l += 6; length -= 12;
  14100. }
  14101. return [ref, parse_ArrayParsedFormula(blob, length, opts, ref)];
  14102. }
  14103. /* [MS-XLS] 2.4.173 */
  14104. function parse_MTRSettings(blob) {
  14105. var fMTREnabled = blob.read_shift(4) !== 0x00;
  14106. var fUserSetThreadCount = blob.read_shift(4) !== 0x00;
  14107. var cUserThreadCount = blob.read_shift(4);
  14108. return [fMTREnabled, fUserSetThreadCount, cUserThreadCount];
  14109. }
  14110. /* [MS-XLS] 2.5.186 TODO: BIFF5 */
  14111. function parse_NoteSh(blob, length, opts) {
  14112. if(opts.biff < 8) return;
  14113. var row = blob.read_shift(2), col = blob.read_shift(2);
  14114. var flags = blob.read_shift(2), idObj = blob.read_shift(2);
  14115. var stAuthor = parse_XLUnicodeString2(blob, 0, opts);
  14116. if(opts.biff < 8) blob.read_shift(1);
  14117. return [{r:row,c:col}, stAuthor, idObj, flags];
  14118. }
  14119. /* [MS-XLS] 2.4.179 */
  14120. function parse_Note(blob, length, opts) {
  14121. /* TODO: Support revisions */
  14122. return parse_NoteSh(blob, length, opts);
  14123. }
  14124. /* [MS-XLS] 2.4.168 */
  14125. function parse_MergeCells(blob, length) {
  14126. var merges = [];
  14127. var cmcs = blob.read_shift(2);
  14128. while (cmcs--) merges.push(parse_Ref8U(blob,length));
  14129. return merges;
  14130. }
  14131. function write_MergeCells(merges) {
  14132. var o = new_buf(2 + merges.length * 8);
  14133. o.write_shift(2, merges.length);
  14134. for(var i = 0; i < merges.length; ++i) write_Ref8U(merges[i], o);
  14135. return o;
  14136. }
  14137. /* [MS-XLS] 2.4.181 TODO: parse all the things! */
  14138. function parse_Obj(blob, length, opts) {
  14139. if(opts && opts.biff < 8) return parse_BIFF5Obj(blob, length, opts);
  14140. var cmo = parse_FtCmo(blob, 22); // id, ot, flags
  14141. var fts = parse_FtArray(blob, length-22, cmo[1]);
  14142. return { cmo: cmo, ft:fts };
  14143. }
  14144. /* from older spec */
  14145. var parse_BIFF5OT = [];
  14146. parse_BIFF5OT[0x08] = function(blob, length) {
  14147. var tgt = blob.l + length;
  14148. blob.l += 10; // todo
  14149. var cf = blob.read_shift(2);
  14150. blob.l += 4;
  14151. blob.l += 2; //var cbPictFmla = blob.read_shift(2);
  14152. blob.l += 2;
  14153. blob.l += 2; //var grbit = blob.read_shift(2);
  14154. blob.l += 4;
  14155. var cchName = blob.read_shift(1);
  14156. blob.l += cchName; // TODO: stName
  14157. blob.l = tgt; // TODO: fmla
  14158. return { fmt:cf };
  14159. };
  14160. function parse_BIFF5Obj(blob, length, opts) {
  14161. blob.l += 4; //var cnt = blob.read_shift(4);
  14162. var ot = blob.read_shift(2);
  14163. var id = blob.read_shift(2);
  14164. var grbit = blob.read_shift(2);
  14165. blob.l += 2; //var colL = blob.read_shift(2);
  14166. blob.l += 2; //var dxL = blob.read_shift(2);
  14167. blob.l += 2; //var rwT = blob.read_shift(2);
  14168. blob.l += 2; //var dyT = blob.read_shift(2);
  14169. blob.l += 2; //var colR = blob.read_shift(2);
  14170. blob.l += 2; //var dxR = blob.read_shift(2);
  14171. blob.l += 2; //var rwB = blob.read_shift(2);
  14172. blob.l += 2; //var dyB = blob.read_shift(2);
  14173. blob.l += 2; //var cbMacro = blob.read_shift(2);
  14174. blob.l += 6;
  14175. length -= 36;
  14176. var fts = [];
  14177. fts.push((parse_BIFF5OT[ot]||parsenoop)(blob, length, opts));
  14178. return { cmo: [id, ot, grbit], ft:fts };
  14179. }
  14180. /* [MS-XLS] 2.4.329 TODO: parse properly */
  14181. function parse_TxO(blob, length, opts) {
  14182. var s = blob.l;
  14183. var texts = "";
  14184. try {
  14185. blob.l += 4;
  14186. var ot = (opts.lastobj||{cmo:[0,0]}).cmo[1];
  14187. var controlInfo; // eslint-disable-line no-unused-vars
  14188. if([0,5,7,11,12,14].indexOf(ot) == -1) blob.l += 6;
  14189. else controlInfo = parse_ControlInfo(blob, 6, opts);
  14190. var cchText = blob.read_shift(2);
  14191. /*var cbRuns = */blob.read_shift(2);
  14192. /*var ifntEmpty = */parseuint16(blob, 2);
  14193. var len = blob.read_shift(2);
  14194. blob.l += len;
  14195. //var fmla = parse_ObjFmla(blob, s + length - blob.l);
  14196. for(var i = 1; i < blob.lens.length-1; ++i) {
  14197. if(blob.l-s != blob.lens[i]) throw new Error("TxO: bad continue record");
  14198. var hdr = blob[blob.l];
  14199. var t = parse_XLUnicodeStringNoCch(blob, blob.lens[i+1]-blob.lens[i]-1);
  14200. texts += t;
  14201. if(texts.length >= (hdr ? cchText : 2*cchText)) break;
  14202. }
  14203. if(texts.length !== cchText && texts.length !== cchText*2) {
  14204. throw new Error("cchText: " + cchText + " != " + texts.length);
  14205. }
  14206. blob.l = s + length;
  14207. /* [MS-XLS] 2.5.272 TxORuns */
  14208. // var rgTxoRuns = [];
  14209. // for(var j = 0; j != cbRuns/8-1; ++j) blob.l += 8;
  14210. // var cchText2 = blob.read_shift(2);
  14211. // if(cchText2 !== cchText) throw new Error("TxOLastRun mismatch: " + cchText2 + " " + cchText);
  14212. // blob.l += 6;
  14213. // if(s + length != blob.l) throw new Error("TxO " + (s + length) + ", at " + blob.l);
  14214. return { t: texts };
  14215. } catch(e) { blob.l = s + length; return { t: texts }; }
  14216. }
  14217. /* [MS-XLS] 2.4.140 */
  14218. function parse_HLink(blob, length) {
  14219. var ref = parse_Ref8U(blob, 8);
  14220. blob.l += 16; /* CLSID */
  14221. var hlink = parse_Hyperlink(blob, length-24);
  14222. return [ref, hlink];
  14223. }
  14224. function write_HLink(hl) {
  14225. var O = new_buf(24);
  14226. var ref = decode_cell(hl[0]);
  14227. O.write_shift(2, ref.r); O.write_shift(2, ref.r);
  14228. O.write_shift(2, ref.c); O.write_shift(2, ref.c);
  14229. var clsid = "d0 c9 ea 79 f9 ba ce 11 8c 82 00 aa 00 4b a9 0b".split(" ");
  14230. for(var i = 0; i < 16; ++i) O.write_shift(1, parseInt(clsid[i], 16));
  14231. return bconcat([O, write_Hyperlink(hl[1])]);
  14232. }
  14233. /* [MS-XLS] 2.4.141 */
  14234. function parse_HLinkTooltip(blob, length) {
  14235. blob.read_shift(2);
  14236. var ref = parse_Ref8U(blob, 8);
  14237. var wzTooltip = blob.read_shift((length-10)/2, 'dbcs-cont');
  14238. wzTooltip = wzTooltip.replace(chr0,"");
  14239. return [ref, wzTooltip];
  14240. }
  14241. function write_HLinkTooltip(hl) {
  14242. var TT = hl[1].Tooltip;
  14243. var O = new_buf(10 + 2 * (TT.length + 1));
  14244. O.write_shift(2, 0x0800);
  14245. var ref = decode_cell(hl[0]);
  14246. O.write_shift(2, ref.r); O.write_shift(2, ref.r);
  14247. O.write_shift(2, ref.c); O.write_shift(2, ref.c);
  14248. for(var i = 0; i < TT.length; ++i) O.write_shift(2, TT.charCodeAt(i));
  14249. O.write_shift(2, 0);
  14250. return O;
  14251. }
  14252. /* [MS-XLS] 2.4.63 */
  14253. function parse_Country(blob) {
  14254. var o = [0,0], d;
  14255. d = blob.read_shift(2); o[0] = CountryEnum[d] || d;
  14256. d = blob.read_shift(2); o[1] = CountryEnum[d] || d;
  14257. return o;
  14258. }
  14259. function write_Country(o) {
  14260. if(!o) o = new_buf(4);
  14261. o.write_shift(2, 0x01);
  14262. o.write_shift(2, 0x01);
  14263. return o;
  14264. }
  14265. /* [MS-XLS] 2.4.50 ClrtClient */
  14266. function parse_ClrtClient(blob) {
  14267. var ccv = blob.read_shift(2);
  14268. var o = [];
  14269. while(ccv-->0) o.push(parse_LongRGB(blob, 8));
  14270. return o;
  14271. }
  14272. /* [MS-XLS] 2.4.188 */
  14273. function parse_Palette(blob) {
  14274. var ccv = blob.read_shift(2);
  14275. var o = [];
  14276. while(ccv-->0) o.push(parse_LongRGB(blob, 8));
  14277. return o;
  14278. }
  14279. /* [MS-XLS] 2.4.354 */
  14280. function parse_XFCRC(blob) {
  14281. blob.l += 2;
  14282. var o = {cxfs:0, crc:0};
  14283. o.cxfs = blob.read_shift(2);
  14284. o.crc = blob.read_shift(4);
  14285. return o;
  14286. }
  14287. /* [MS-XLS] 2.4.53 TODO: parse flags */
  14288. /* [MS-XLSB] 2.4.323 TODO: parse flags */
  14289. function parse_ColInfo(blob, length, opts) {
  14290. if(!opts.cellStyles) return parsenoop(blob, length);
  14291. var w = opts && opts.biff >= 12 ? 4 : 2;
  14292. var colFirst = blob.read_shift(w);
  14293. var colLast = blob.read_shift(w);
  14294. var coldx = blob.read_shift(w);
  14295. var ixfe = blob.read_shift(w);
  14296. var flags = blob.read_shift(2);
  14297. if(w == 2) blob.l += 2;
  14298. var o = ({s:colFirst, e:colLast, w:coldx, ixfe:ixfe, flags:flags});
  14299. if(opts.biff >= 5 || !opts.biff) o.level = (flags >> 8) & 0x7;
  14300. return o;
  14301. }
  14302. /* [MS-XLS] 2.4.257 */
  14303. function parse_Setup(blob, length) {
  14304. var o = {};
  14305. if(length < 32) return o;
  14306. blob.l += 16;
  14307. o.header = parse_Xnum(blob, 8);
  14308. o.footer = parse_Xnum(blob, 8);
  14309. blob.l += 2;
  14310. return o;
  14311. }
  14312. /* [MS-XLS] 2.4.261 */
  14313. function parse_ShtProps(blob, length, opts) {
  14314. var def = {area:false};
  14315. if(opts.biff != 5) { blob.l += length; return def; }
  14316. var d = blob.read_shift(1); blob.l += 3;
  14317. if((d & 0x10)) def.area = true;
  14318. return def;
  14319. }
  14320. /* [MS-XLS] 2.4.241 */
  14321. function write_RRTabId(n) {
  14322. var out = new_buf(2 * n);
  14323. for(var i = 0; i < n; ++i) out.write_shift(2, i+1);
  14324. return out;
  14325. }
  14326. var parse_Blank = parse_XLSCell; /* [MS-XLS] 2.4.20 Just the cell */
  14327. var parse_Scl = parseuint16a; /* [MS-XLS] 2.4.247 num, den */
  14328. var parse_String = parse_XLUnicodeString; /* [MS-XLS] 2.4.268 */
  14329. /* --- Specific to versions before BIFF8 --- */
  14330. function parse_ImData(blob) {
  14331. var cf = blob.read_shift(2);
  14332. var env = blob.read_shift(2);
  14333. var lcb = blob.read_shift(4);
  14334. var o = {fmt:cf, env:env, len:lcb, data:blob.slice(blob.l,blob.l+lcb)};
  14335. blob.l += lcb;
  14336. return o;
  14337. }
  14338. /* BIFF2_??? where ??? is the name from [XLS] */
  14339. function parse_BIFF2STR(blob, length, opts) {
  14340. var cell = parse_XLSCell(blob, 6);
  14341. ++blob.l;
  14342. var str = parse_XLUnicodeString2(blob, length-7, opts);
  14343. cell.t = 'str';
  14344. cell.val = str;
  14345. return cell;
  14346. }
  14347. function parse_BIFF2NUM(blob) {
  14348. var cell = parse_XLSCell(blob, 6);
  14349. ++blob.l;
  14350. var num = parse_Xnum(blob, 8);
  14351. cell.t = 'n';
  14352. cell.val = num;
  14353. return cell;
  14354. }
  14355. function write_BIFF2NUM(r, c, val) {
  14356. var out = new_buf(15);
  14357. write_BIFF2Cell(out, r, c);
  14358. out.write_shift(8, val, 'f');
  14359. return out;
  14360. }
  14361. function parse_BIFF2INT(blob) {
  14362. var cell = parse_XLSCell(blob, 6);
  14363. ++blob.l;
  14364. var num = blob.read_shift(2);
  14365. cell.t = 'n';
  14366. cell.val = num;
  14367. return cell;
  14368. }
  14369. function write_BIFF2INT(r, c, val) {
  14370. var out = new_buf(9);
  14371. write_BIFF2Cell(out, r, c);
  14372. out.write_shift(2, val);
  14373. return out;
  14374. }
  14375. function parse_BIFF2STRING(blob) {
  14376. var cch = blob.read_shift(1);
  14377. if(cch === 0) { blob.l++; return ""; }
  14378. return blob.read_shift(cch, 'sbcs-cont');
  14379. }
  14380. /* TODO: convert to BIFF8 font struct */
  14381. function parse_BIFF2FONTXTRA(blob, length) {
  14382. blob.l += 6; // unknown
  14383. blob.l += 2; // font weight "bls"
  14384. blob.l += 1; // charset
  14385. blob.l += 3; // unknown
  14386. blob.l += 1; // font family
  14387. blob.l += length - 13;
  14388. }
  14389. /* TODO: parse rich text runs */
  14390. function parse_RString(blob, length, opts) {
  14391. var end = blob.l + length;
  14392. var cell = parse_XLSCell(blob, 6);
  14393. var cch = blob.read_shift(2);
  14394. var str = parse_XLUnicodeStringNoCch(blob, cch, opts);
  14395. blob.l = end;
  14396. cell.t = 'str';
  14397. cell.val = str;
  14398. return cell;
  14399. }
  14400. /* from js-harb (C) 2014-present SheetJS */
  14401. var DBF = (function() {
  14402. var dbf_codepage_map = {
  14403. /* Code Pages Supported by Visual FoxPro */
  14404. 0x01: 437, 0x02: 850,
  14405. 0x03: 1252, 0x04: 10000,
  14406. 0x64: 852, 0x65: 866,
  14407. 0x66: 865, 0x67: 861,
  14408. 0x68: 895, 0x69: 620,
  14409. 0x6A: 737, 0x6B: 857,
  14410. 0x78: 950, 0x79: 949,
  14411. 0x7A: 936, 0x7B: 932,
  14412. 0x7C: 874, 0x7D: 1255,
  14413. 0x7E: 1256, 0x96: 10007,
  14414. 0x97: 10029, 0x98: 10006,
  14415. 0xC8: 1250, 0xC9: 1251,
  14416. 0xCA: 1254, 0xCB: 1253,
  14417. /* shapefile DBF extension */
  14418. 0x00: 20127, 0x08: 865,
  14419. 0x09: 437, 0x0A: 850,
  14420. 0x0B: 437, 0x0D: 437,
  14421. 0x0E: 850, 0x0F: 437,
  14422. 0x10: 850, 0x11: 437,
  14423. 0x12: 850, 0x13: 932,
  14424. 0x14: 850, 0x15: 437,
  14425. 0x16: 850, 0x17: 865,
  14426. 0x18: 437, 0x19: 437,
  14427. 0x1A: 850, 0x1B: 437,
  14428. 0x1C: 863, 0x1D: 850,
  14429. 0x1F: 852, 0x22: 852,
  14430. 0x23: 852, 0x24: 860,
  14431. 0x25: 850, 0x26: 866,
  14432. 0x37: 850, 0x40: 852,
  14433. 0x4D: 936, 0x4E: 949,
  14434. 0x4F: 950, 0x50: 874,
  14435. 0x57: 1252, 0x58: 1252,
  14436. 0x59: 1252,
  14437. 0xFF: 16969
  14438. };
  14439. var dbf_reverse_map = evert({
  14440. 0x01: 437, 0x02: 850,
  14441. 0x03: 1252, 0x04: 10000,
  14442. 0x64: 852, 0x65: 866,
  14443. 0x66: 865, 0x67: 861,
  14444. 0x68: 895, 0x69: 620,
  14445. 0x6A: 737, 0x6B: 857,
  14446. 0x78: 950, 0x79: 949,
  14447. 0x7A: 936, 0x7B: 932,
  14448. 0x7C: 874, 0x7D: 1255,
  14449. 0x7E: 1256, 0x96: 10007,
  14450. 0x97: 10029, 0x98: 10006,
  14451. 0xC8: 1250, 0xC9: 1251,
  14452. 0xCA: 1254, 0xCB: 1253,
  14453. 0x00: 20127
  14454. });
  14455. var DBF_SUPPORTED_VERSIONS = [0x02, 0x03, 0x30, 0x31, 0x83, 0x8B, 0x8C, 0xF5];
  14456. /* TODO: find an actual specification */
  14457. function dbf_to_aoa(buf, opts) {
  14458. var out = [];
  14459. /* TODO: browser based */
  14460. var d = (new_raw_buf(1));
  14461. switch(opts.type) {
  14462. case 'base64': d = s2a(Base64.decode(buf)); break;
  14463. case 'binary': d = s2a(buf); break;
  14464. case 'buffer':
  14465. case 'array': d = buf; break;
  14466. }
  14467. prep_blob(d, 0);
  14468. /* header */
  14469. var ft = d.read_shift(1);
  14470. var memo = false;
  14471. var vfp = false, l7 = false;
  14472. switch(ft) {
  14473. case 0x02: case 0x03: break;
  14474. case 0x30: vfp = true; memo = true; break;
  14475. case 0x31: vfp = true; break;
  14476. case 0x83: memo = true; break;
  14477. case 0x8B: memo = true; break;
  14478. case 0x8C: memo = true; l7 = true; break;
  14479. case 0xF5: memo = true; break;
  14480. default: throw new Error("DBF Unsupported Version: " + ft.toString(16));
  14481. }
  14482. var /*filedate = new Date(),*/ nrow = 0, fpos = 0;
  14483. if(ft == 0x02) nrow = d.read_shift(2);
  14484. /*filedate = new Date(d.read_shift(1) + 1900, d.read_shift(1) - 1, d.read_shift(1));*/d.l += 3;
  14485. if(ft != 0x02) nrow = d.read_shift(4);
  14486. if(ft != 0x02) fpos = d.read_shift(2);
  14487. var rlen = d.read_shift(2);
  14488. var /*flags = 0,*/ current_cp = 1252;
  14489. if(ft != 0x02) {
  14490. d.l+=16;
  14491. /*flags = */d.read_shift(1);
  14492. //if(memo && ((flags & 0x02) === 0)) throw new Error("DBF Flags " + flags.toString(16) + " ft " + ft.toString(16));
  14493. /* codepage present in FoxPro */
  14494. if(d[d.l] !== 0) current_cp = dbf_codepage_map[d[d.l]];
  14495. d.l+=1;
  14496. d.l+=2;
  14497. }
  14498. if(l7) d.l += 36;
  14499. var fields = [], field = ({});
  14500. var hend = fpos - 10 - (vfp ? 264 : 0), ww = l7 ? 32 : 11;
  14501. while(ft == 0x02 ? d.l < d.length && d[d.l] != 0x0d: d.l < hend) {
  14502. field = ({});
  14503. field.name = cptable.utils.decode(current_cp, d.slice(d.l, d.l+ww)).replace(/[\u0000\r\n].*$/g,"");
  14504. d.l += ww;
  14505. field.type = String.fromCharCode(d.read_shift(1));
  14506. if(ft != 0x02 && !l7) field.offset = d.read_shift(4);
  14507. field.len = d.read_shift(1);
  14508. if(ft == 0x02) field.offset = d.read_shift(2);
  14509. field.dec = d.read_shift(1);
  14510. if(field.name.length) fields.push(field);
  14511. if(ft != 0x02) d.l += l7 ? 13 : 14;
  14512. switch(field.type) {
  14513. case 'B': // VFP Double
  14514. if((!vfp || field.len != 8) && opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  14515. break;
  14516. case 'G': // General
  14517. case 'P': // Picture
  14518. if(opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  14519. break;
  14520. case 'C': // character
  14521. case 'D': // date
  14522. case 'F': // floating point
  14523. case 'I': // long
  14524. case 'L': // boolean
  14525. case 'M': // memo
  14526. case 'N': // number
  14527. case 'O': // double
  14528. case 'T': // datetime
  14529. case 'Y': // currency
  14530. case '0': // VFP _NullFlags
  14531. case '@': // timestamp
  14532. case '+': // autoincrement
  14533. break;
  14534. default: throw new Error('Unknown Field Type: ' + field.type);
  14535. }
  14536. }
  14537. if(d[d.l] !== 0x0D) d.l = fpos-1;
  14538. else if(ft == 0x02) d.l = 0x209;
  14539. if(ft != 0x02) {
  14540. if(d.read_shift(1) !== 0x0D) throw new Error("DBF Terminator not found " + d.l + " " + d[d.l]);
  14541. d.l = fpos;
  14542. }
  14543. /* data */
  14544. var R = 0, C = 0;
  14545. out[0] = [];
  14546. for(C = 0; C != fields.length; ++C) out[0][C] = fields[C].name;
  14547. while(nrow-- > 0) {
  14548. if(d[d.l] === 0x2A) { d.l+=rlen; continue; }
  14549. ++d.l;
  14550. out[++R] = []; C = 0;
  14551. for(C = 0; C != fields.length; ++C) {
  14552. var dd = d.slice(d.l, d.l+fields[C].len); d.l+=fields[C].len;
  14553. prep_blob(dd, 0);
  14554. var s = cptable.utils.decode(current_cp, dd);
  14555. switch(fields[C].type) {
  14556. case 'C':
  14557. out[R][C] = cptable.utils.decode(current_cp, dd);
  14558. out[R][C] = out[R][C].trim();
  14559. break;
  14560. case 'D':
  14561. if(s.length === 8) out[R][C] = new Date(+s.slice(0,4), +s.slice(4,6)-1, +s.slice(6,8));
  14562. else out[R][C] = s;
  14563. break;
  14564. case 'F': out[R][C] = parseFloat(s.trim()); break;
  14565. case '+': case 'I': out[R][C] = l7 ? dd.read_shift(-4, 'i') ^ 0x80000000 : dd.read_shift(4, 'i'); break;
  14566. case 'L': switch(s.toUpperCase()) {
  14567. case 'Y': case 'T': out[R][C] = true; break;
  14568. case 'N': case 'F': out[R][C] = false; break;
  14569. case ' ': case '?': out[R][C] = false; break; /* NOTE: technically uninitialized */
  14570. default: throw new Error("DBF Unrecognized L:|" + s + "|");
  14571. } break;
  14572. case 'M': /* TODO: handle memo files */
  14573. if(!memo) throw new Error("DBF Unexpected MEMO for type " + ft.toString(16));
  14574. out[R][C] = "##MEMO##" + (l7 ? parseInt(s.trim(), 10): dd.read_shift(4));
  14575. break;
  14576. case 'N': out[R][C] = +s.replace(/\u0000/g,"").trim(); break;
  14577. case '@': out[R][C] = new Date(dd.read_shift(-8, 'f') - 0x388317533400); break;
  14578. case 'T': out[R][C] = new Date((dd.read_shift(4) - 0x253D8C) * 0x5265C00 + dd.read_shift(4)); break;
  14579. case 'Y': out[R][C] = dd.read_shift(4,'i')/1e4; break;
  14580. case 'O': out[R][C] = -dd.read_shift(-8, 'f'); break;
  14581. case 'B': if(vfp && fields[C].len == 8) { out[R][C] = dd.read_shift(8,'f'); break; }
  14582. /* falls through */
  14583. case 'G': case 'P': dd.l += fields[C].len; break;
  14584. case '0':
  14585. if(fields[C].name === '_NullFlags') break;
  14586. /* falls through */
  14587. default: throw new Error("DBF Unsupported data type " + fields[C].type);
  14588. }
  14589. }
  14590. }
  14591. if(ft != 0x02) if(d.l < d.length && d[d.l++] != 0x1A) throw new Error("DBF EOF Marker missing " + (d.l-1) + " of " + d.length + " " + d[d.l-1].toString(16));
  14592. if(opts && opts.sheetRows) out = out.slice(0, opts.sheetRows);
  14593. return out;
  14594. }
  14595. function dbf_to_sheet(buf, opts) {
  14596. var o = opts || {};
  14597. if(!o.dateNF) o.dateNF = "yyyymmdd";
  14598. return aoa_to_sheet(dbf_to_aoa(buf, o), o);
  14599. }
  14600. function dbf_to_workbook(buf, opts) {
  14601. try { return sheet_to_workbook(dbf_to_sheet(buf, opts), opts); }
  14602. catch(e) { if(opts && opts.WTF) throw e; }
  14603. return ({SheetNames:[],Sheets:{}});
  14604. }
  14605. var _RLEN = { 'B': 8, 'C': 250, 'L': 1, 'D': 8, '?': 0, '': 0 };
  14606. function sheet_to_dbf(ws, opts) {
  14607. var o = opts || {};
  14608. if(+o.codepage >= 0) set_cp(+o.codepage);
  14609. if(o.type == "string") throw new Error("Cannot write DBF to JS string");
  14610. var ba = buf_array();
  14611. var aoa = sheet_to_json(ws, {header:1, raw:true, cellDates:true});
  14612. var headers = aoa[0], data = aoa.slice(1);
  14613. var i = 0, j = 0, hcnt = 0, rlen = 1;
  14614. for(i = 0; i < headers.length; ++i) {
  14615. if(i == null) continue;
  14616. ++hcnt;
  14617. if(typeof headers[i] === 'number') headers[i] = headers[i].toString(10);
  14618. if(typeof headers[i] !== 'string') throw new Error("DBF Invalid column name " + headers[i] + " |" + (typeof headers[i]) + "|");
  14619. if(headers.indexOf(headers[i]) !== i) for(j=0; j<1024;++j)
  14620. if(headers.indexOf(headers[i] + "_" + j) == -1) { headers[i] += "_" + j; break; }
  14621. }
  14622. var range = safe_decode_range(ws['!ref']);
  14623. var coltypes = [];
  14624. for(i = 0; i <= range.e.c - range.s.c; ++i) {
  14625. var col = [];
  14626. for(j=0; j < data.length; ++j) {
  14627. if(data[j][i] != null) col.push(data[j][i]);
  14628. }
  14629. if(col.length == 0 || headers[i] == null) { coltypes[i] = '?'; continue; }
  14630. var guess = '', _guess = '';
  14631. for(j = 0; j < col.length; ++j) {
  14632. switch(typeof col[j]) {
  14633. /* TODO: check if L2 compat is desired */
  14634. case 'number': _guess = 'B'; break;
  14635. case 'string': _guess = 'C'; break;
  14636. case 'boolean': _guess = 'L'; break;
  14637. case 'object': _guess = col[j] instanceof Date ? 'D' : 'C'; break;
  14638. default: _guess = 'C';
  14639. }
  14640. guess = guess && guess != _guess ? 'C' : _guess;
  14641. if(guess == 'C') break;
  14642. }
  14643. rlen += _RLEN[guess] || 0;
  14644. coltypes[i] = guess;
  14645. }
  14646. var h = ba.next(32);
  14647. h.write_shift(4, 0x13021130);
  14648. h.write_shift(4, data.length);
  14649. h.write_shift(2, 296 + 32 * hcnt);
  14650. h.write_shift(2, rlen);
  14651. for(i=0; i < 4; ++i) h.write_shift(4, 0);
  14652. h.write_shift(4, 0x00000000 | ((+dbf_reverse_map[current_ansi] || 0x03)<<8));
  14653. for(i = 0, j = 0; i < headers.length; ++i) {
  14654. if(headers[i] == null) continue;
  14655. var hf = ba.next(32);
  14656. var _f = (headers[i].slice(-10) + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00").slice(0, 11);
  14657. hf.write_shift(1, _f, "sbcs");
  14658. hf.write_shift(1, coltypes[i] == '?' ? 'C' : coltypes[i], "sbcs");
  14659. hf.write_shift(4, j);
  14660. hf.write_shift(1, _RLEN[coltypes[i]] || 0);
  14661. hf.write_shift(1, 0);
  14662. hf.write_shift(1, 0x02);
  14663. hf.write_shift(4, 0);
  14664. hf.write_shift(1, 0);
  14665. hf.write_shift(4, 0);
  14666. hf.write_shift(4, 0);
  14667. j += _RLEN[coltypes[i]] || 0;
  14668. }
  14669. var hb = ba.next(264);
  14670. hb.write_shift(4, 0x0000000D);
  14671. for(i=0; i < 65;++i) hb.write_shift(4, 0x00000000);
  14672. for(i=0; i < data.length; ++i) {
  14673. var rout = ba.next(rlen);
  14674. rout.write_shift(1, 0);
  14675. for(j=0; j<headers.length; ++j) {
  14676. if(headers[j] == null) continue;
  14677. switch(coltypes[j]) {
  14678. case 'L': rout.write_shift(1, data[i][j] == null ? 0x3F : data[i][j] ? 0x54 : 0x46); break;
  14679. case 'B': rout.write_shift(8, data[i][j]||0, 'f'); break;
  14680. case 'D':
  14681. if(!data[i][j]) rout.write_shift(8, "00000000", "sbcs");
  14682. else {
  14683. rout.write_shift(4, ("0000"+data[i][j].getFullYear()).slice(-4), "sbcs");
  14684. rout.write_shift(2, ("00"+(data[i][j].getMonth()+1)).slice(-2), "sbcs");
  14685. rout.write_shift(2, ("00"+data[i][j].getDate()).slice(-2), "sbcs");
  14686. } break;
  14687. case 'C':
  14688. var _s = String(data[i][j]||"");
  14689. rout.write_shift(1, _s, "sbcs");
  14690. for(hcnt=0; hcnt < 250-_s.length; ++hcnt) rout.write_shift(1, 0x20); break;
  14691. }
  14692. }
  14693. // data
  14694. }
  14695. ba.next(1).write_shift(1, 0x1A);
  14696. return ba.end();
  14697. }
  14698. return {
  14699. versions: DBF_SUPPORTED_VERSIONS,
  14700. to_workbook: dbf_to_workbook,
  14701. to_sheet: dbf_to_sheet,
  14702. from_sheet: sheet_to_dbf
  14703. };
  14704. })();
  14705. var SYLK = (function() {
  14706. /* TODO: stress test sequences */
  14707. var sylk_escapes = ({
  14708. AA:'À', BA:'Á', CA:'Â', DA:195, HA:'Ä', JA:197,
  14709. AE:'È', BE:'É', CE:'Ê', HE:'Ë',
  14710. AI:'Ì', BI:'Í', CI:'Î', HI:'Ï',
  14711. AO:'Ò', BO:'Ó', CO:'Ô', DO:213, HO:'Ö',
  14712. AU:'Ù', BU:'Ú', CU:'Û', HU:'Ü',
  14713. Aa:'à', Ba:'á', Ca:'â', Da:227, Ha:'ä', Ja:229,
  14714. Ae:'è', Be:'é', Ce:'ê', He:'ë',
  14715. Ai:'ì', Bi:'í', Ci:'î', Hi:'ï',
  14716. Ao:'ò', Bo:'ó', Co:'ô', Do:245, Ho:'ö',
  14717. Au:'ù', Bu:'ú', Cu:'û', Hu:'ü',
  14718. KC:'Ç', Kc:'ç', q:'æ', z:'œ', a:'Æ', j:'Œ',
  14719. DN:209, Dn:241, Hy:255,
  14720. S:169, c:170, R:174, B:180,
  14721. 0:176, 1:177, 2:178,
  14722. 3:179, 5:181, 6:182,
  14723. 7:183, Q:185, k:186, b:208, i:216, l:222, s:240, y:248,
  14724. "!":161, '"':162, "#":163, "(":164, "%":165, "'":167, "H ":168,
  14725. "+":171, ";":187, "<":188, "=":189, ">":190, "?":191, "{":223
  14726. });
  14727. var sylk_char_regex = new RegExp("\u001BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g,"\\$1") + "|\\|)", "gm");
  14728. var sylk_char_fn = function(_, $1){ var o = sylk_escapes[$1]; return typeof o == "number" ? _getansi(o) : o; };
  14729. var decode_sylk_char = function($$, $1, $2) { var newcc = (($1.charCodeAt(0) - 0x20)<<4) | ($2.charCodeAt(0) - 0x30); return newcc == 59 ? $$ : _getansi(newcc); };
  14730. sylk_escapes["|"] = 254;
  14731. /* TODO: find an actual specification */
  14732. function sylk_to_aoa(d, opts) {
  14733. switch(opts.type) {
  14734. case 'base64': return sylk_to_aoa_str(Base64.decode(d), opts);
  14735. case 'binary': return sylk_to_aoa_str(d, opts);
  14736. case 'buffer': return sylk_to_aoa_str(d.toString('binary'), opts);
  14737. case 'array': return sylk_to_aoa_str(cc2str(d), opts);
  14738. }
  14739. throw new Error("Unrecognized type " + opts.type);
  14740. }
  14741. function sylk_to_aoa_str(str, opts) {
  14742. var records = str.split(/[\n\r]+/), R = -1, C = -1, ri = 0, rj = 0, arr = [];
  14743. var formats = [];
  14744. var next_cell_format = null;
  14745. var sht = {}, rowinfo = [], colinfo = [], cw = [];
  14746. var Mval = 0, j;
  14747. if(+opts.codepage >= 0) set_cp(+opts.codepage);
  14748. for (; ri !== records.length; ++ri) {
  14749. Mval = 0;
  14750. var rstr=records[ri].trim().replace(/\x1B([\x20-\x2F])([\x30-\x3F])/g, decode_sylk_char).replace(sylk_char_regex, sylk_char_fn);
  14751. var record=rstr.replace(/;;/g, "\u0000").split(";").map(function(x) { return x.replace(/\u0000/g, ";"); });
  14752. var RT=record[0], val;
  14753. if(rstr.length > 0) switch(RT) {
  14754. case 'ID': break; /* header */
  14755. case 'E': break; /* EOF */
  14756. case 'B': break; /* dimensions */
  14757. case 'O': break; /* options? */
  14758. case 'P':
  14759. if(record[1].charAt(0) == 'P')
  14760. formats.push(rstr.slice(3).replace(/;;/g, ";"));
  14761. break;
  14762. case 'C':
  14763. var C_seen_K = false, C_seen_X = false;
  14764. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  14765. case 'X': C = parseInt(record[rj].slice(1))-1; C_seen_X = true; break;
  14766. case 'Y':
  14767. R = parseInt(record[rj].slice(1))-1; if(!C_seen_X) C = 0;
  14768. for(j = arr.length; j <= R; ++j) arr[j] = [];
  14769. break;
  14770. case 'K':
  14771. val = record[rj].slice(1);
  14772. if(val.charAt(0) === '"') val = val.slice(1,val.length - 1);
  14773. else if(val === 'TRUE') val = true;
  14774. else if(val === 'FALSE') val = false;
  14775. else if(!isNaN(fuzzynum(val))) {
  14776. val = fuzzynum(val);
  14777. if(next_cell_format !== null && SSF.is_date(next_cell_format)) val = numdate(val);
  14778. } else if(!isNaN(fuzzydate(val).getDate())) {
  14779. val = parseDate(val);
  14780. }
  14781. if(typeof cptable !== 'undefined' && typeof val == "string" && ((opts||{}).type != "string") && (opts||{}).codepage) val = cptable.utils.decode(opts.codepage, val);
  14782. C_seen_K = true;
  14783. break;
  14784. case 'E':
  14785. var formula = rc_to_a1(record[rj].slice(1), {r:R,c:C});
  14786. arr[R][C] = [arr[R][C], formula];
  14787. break;
  14788. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  14789. }
  14790. if(C_seen_K) { arr[R][C] = val; next_cell_format = null; }
  14791. break;
  14792. case 'F':
  14793. var F_seen = 0;
  14794. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  14795. case 'X': C = parseInt(record[rj].slice(1))-1; ++F_seen; break;
  14796. case 'Y':
  14797. R = parseInt(record[rj].slice(1))-1; /*C = 0;*/
  14798. for(j = arr.length; j <= R; ++j) arr[j] = [];
  14799. break;
  14800. case 'M': Mval = parseInt(record[rj].slice(1)) / 20; break;
  14801. case 'F': break; /* ??? */
  14802. case 'G': break; /* hide grid */
  14803. case 'P':
  14804. next_cell_format = formats[parseInt(record[rj].slice(1))];
  14805. break;
  14806. case 'S': break; /* cell style */
  14807. case 'D': break; /* column */
  14808. case 'N': break; /* font */
  14809. case 'W':
  14810. cw = record[rj].slice(1).split(" ");
  14811. for(j = parseInt(cw[0], 10); j <= parseInt(cw[1], 10); ++j) {
  14812. Mval = parseInt(cw[2], 10);
  14813. colinfo[j-1] = Mval === 0 ? {hidden:true}: {wch:Mval}; process_col(colinfo[j-1]);
  14814. } break;
  14815. case 'C': /* default column format */
  14816. C = parseInt(record[rj].slice(1))-1;
  14817. if(!colinfo[C]) colinfo[C] = {};
  14818. break;
  14819. case 'R': /* row properties */
  14820. R = parseInt(record[rj].slice(1))-1;
  14821. if(!rowinfo[R]) rowinfo[R] = {};
  14822. if(Mval > 0) { rowinfo[R].hpt = Mval; rowinfo[R].hpx = pt2px(Mval); }
  14823. else if(Mval === 0) rowinfo[R].hidden = true;
  14824. break;
  14825. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  14826. }
  14827. if(F_seen < 1) next_cell_format = null; break;
  14828. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  14829. }
  14830. }
  14831. if(rowinfo.length > 0) sht['!rows'] = rowinfo;
  14832. if(colinfo.length > 0) sht['!cols'] = colinfo;
  14833. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  14834. return [arr, sht];
  14835. }
  14836. function sylk_to_sheet(d, opts) {
  14837. var aoasht = sylk_to_aoa(d, opts);
  14838. var aoa = aoasht[0], ws = aoasht[1];
  14839. var o = aoa_to_sheet(aoa, opts);
  14840. keys(ws).forEach(function(k) { o[k] = ws[k]; });
  14841. return o;
  14842. }
  14843. function sylk_to_workbook(d, opts) { return sheet_to_workbook(sylk_to_sheet(d, opts), opts); }
  14844. function write_ws_cell_sylk(cell, ws, R, C) {
  14845. var o = "C;Y" + (R+1) + ";X" + (C+1) + ";K";
  14846. switch(cell.t) {
  14847. case 'n':
  14848. o += (cell.v||0);
  14849. if(cell.f && !cell.F) o += ";E" + a1_to_rc(cell.f, {r:R, c:C}); break;
  14850. case 'b': o += cell.v ? "TRUE" : "FALSE"; break;
  14851. case 'e': o += cell.w || cell.v; break;
  14852. case 'd': o += '"' + (cell.w || cell.v) + '"'; break;
  14853. case 's': o += '"' + cell.v.replace(/"/g,"") + '"'; break;
  14854. }
  14855. return o;
  14856. }
  14857. function write_ws_cols_sylk(out, cols) {
  14858. cols.forEach(function(col, i) {
  14859. var rec = "F;W" + (i+1) + " " + (i+1) + " ";
  14860. if(col.hidden) rec += "0";
  14861. else {
  14862. if(typeof col.width == 'number') col.wpx = width2px(col.width);
  14863. if(typeof col.wpx == 'number') col.wch = px2char(col.wpx);
  14864. if(typeof col.wch == 'number') rec += Math.round(col.wch);
  14865. }
  14866. if(rec.charAt(rec.length - 1) != " ") out.push(rec);
  14867. });
  14868. }
  14869. function write_ws_rows_sylk(out, rows) {
  14870. rows.forEach(function(row, i) {
  14871. var rec = "F;";
  14872. if(row.hidden) rec += "M0;";
  14873. else if(row.hpt) rec += "M" + 20 * row.hpt + ";";
  14874. else if(row.hpx) rec += "M" + 20 * px2pt(row.hpx) + ";";
  14875. if(rec.length > 2) out.push(rec + "R" + (i+1));
  14876. });
  14877. }
  14878. function sheet_to_sylk(ws, opts) {
  14879. var preamble = ["ID;PWXL;N;E"], o = [];
  14880. var r = safe_decode_range(ws['!ref']), cell;
  14881. var dense = Array.isArray(ws);
  14882. var RS = "\r\n";
  14883. preamble.push("P;PGeneral");
  14884. preamble.push("F;P0;DG0G8;M255");
  14885. if(ws['!cols']) write_ws_cols_sylk(preamble, ws['!cols']);
  14886. if(ws['!rows']) write_ws_rows_sylk(preamble, ws['!rows']);
  14887. preamble.push("B;Y" + (r.e.r - r.s.r + 1) + ";X" + (r.e.c - r.s.c + 1) + ";D" + [r.s.c,r.s.r,r.e.c,r.e.r].join(" "));
  14888. for(var R = r.s.r; R <= r.e.r; ++R) {
  14889. for(var C = r.s.c; C <= r.e.c; ++C) {
  14890. var coord = encode_cell({r:R,c:C});
  14891. cell = dense ? (ws[R]||[])[C]: ws[coord];
  14892. if(!cell || (cell.v == null && (!cell.f || cell.F))) continue;
  14893. o.push(write_ws_cell_sylk(cell, ws, R, C, opts));
  14894. }
  14895. }
  14896. return preamble.join(RS) + RS + o.join(RS) + RS + "E" + RS;
  14897. }
  14898. return {
  14899. to_workbook: sylk_to_workbook,
  14900. to_sheet: sylk_to_sheet,
  14901. from_sheet: sheet_to_sylk
  14902. };
  14903. })();
  14904. var DIF = (function() {
  14905. function dif_to_aoa(d, opts) {
  14906. switch(opts.type) {
  14907. case 'base64': return dif_to_aoa_str(Base64.decode(d), opts);
  14908. case 'binary': return dif_to_aoa_str(d, opts);
  14909. case 'buffer': return dif_to_aoa_str(d.toString('binary'), opts);
  14910. case 'array': return dif_to_aoa_str(cc2str(d), opts);
  14911. }
  14912. throw new Error("Unrecognized type " + opts.type);
  14913. }
  14914. function dif_to_aoa_str(str, opts) {
  14915. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  14916. for (; ri !== records.length; ++ri) {
  14917. if (records[ri].trim() === 'BOT') { arr[++R] = []; C = 0; continue; }
  14918. if (R < 0) continue;
  14919. var metadata = records[ri].trim().split(",");
  14920. var type = metadata[0], value = metadata[1];
  14921. ++ri;
  14922. var data = records[ri].trim();
  14923. switch (+type) {
  14924. case -1:
  14925. if (data === 'BOT') { arr[++R] = []; C = 0; continue; }
  14926. else if (data !== 'EOD') throw new Error("Unrecognized DIF special command " + data);
  14927. break;
  14928. case 0:
  14929. if(data === 'TRUE') arr[R][C] = true;
  14930. else if(data === 'FALSE') arr[R][C] = false;
  14931. else if(!isNaN(fuzzynum(value))) arr[R][C] = fuzzynum(value);
  14932. else if(!isNaN(fuzzydate(value).getDate())) arr[R][C] = parseDate(value);
  14933. else arr[R][C] = value;
  14934. ++C; break;
  14935. case 1:
  14936. data = data.slice(1,data.length-1);
  14937. arr[R][C++] = data !== '' ? data : null;
  14938. break;
  14939. }
  14940. if (data === 'EOD') break;
  14941. }
  14942. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  14943. return arr;
  14944. }
  14945. function dif_to_sheet(str, opts) { return aoa_to_sheet(dif_to_aoa(str, opts), opts); }
  14946. function dif_to_workbook(str, opts) { return sheet_to_workbook(dif_to_sheet(str, opts), opts); }
  14947. var sheet_to_dif = (function() {
  14948. var push_field = function pf(o, topic, v, n, s) {
  14949. o.push(topic);
  14950. o.push(v + "," + n);
  14951. o.push('"' + s.replace(/"/g,'""') + '"');
  14952. };
  14953. var push_value = function po(o, type, v, s) {
  14954. o.push(type + "," + v);
  14955. o.push(type == 1 ? '"' + s.replace(/"/g,'""') + '"' : s);
  14956. };
  14957. return function sheet_to_dif(ws) {
  14958. var o = [];
  14959. var r = safe_decode_range(ws['!ref']), cell;
  14960. var dense = Array.isArray(ws);
  14961. push_field(o, "TABLE", 0, 1, "sheetjs");
  14962. push_field(o, "VECTORS", 0, r.e.r - r.s.r + 1,"");
  14963. push_field(o, "TUPLES", 0, r.e.c - r.s.c + 1,"");
  14964. push_field(o, "DATA", 0, 0,"");
  14965. for(var R = r.s.r; R <= r.e.r; ++R) {
  14966. push_value(o, -1, 0, "BOT");
  14967. for(var C = r.s.c; C <= r.e.c; ++C) {
  14968. var coord = encode_cell({r:R,c:C});
  14969. cell = dense ? (ws[R]||[])[C] : ws[coord];
  14970. if(!cell) { push_value(o, 1, 0, ""); continue;}
  14971. switch(cell.t) {
  14972. case 'n':
  14973. var val = DIF_XL ? cell.w : cell.v;
  14974. if(!val && cell.v != null) val = cell.v;
  14975. if(val == null) {
  14976. if(DIF_XL && cell.f && !cell.F) push_value(o, 1, 0, "=" + cell.f);
  14977. else push_value(o, 1, 0, "");
  14978. }
  14979. else push_value(o, 0, val, "V");
  14980. break;
  14981. case 'b':
  14982. push_value(o, 0, cell.v ? 1 : 0, cell.v ? "TRUE" : "FALSE");
  14983. break;
  14984. case 's':
  14985. push_value(o, 1, 0, (!DIF_XL || isNaN(cell.v)) ? cell.v : '="' + cell.v + '"');
  14986. break;
  14987. case 'd':
  14988. if(!cell.w) cell.w = SSF.format(cell.z || SSF._table[14], datenum(parseDate(cell.v)));
  14989. if(DIF_XL) push_value(o, 0, cell.w, "V");
  14990. else push_value(o, 1, 0, cell.w);
  14991. break;
  14992. default: push_value(o, 1, 0, "");
  14993. }
  14994. }
  14995. }
  14996. push_value(o, -1, 0, "EOD");
  14997. var RS = "\r\n";
  14998. var oo = o.join(RS);
  14999. //while((oo.length & 0x7F) != 0) oo += "\0";
  15000. return oo;
  15001. };
  15002. })();
  15003. return {
  15004. to_workbook: dif_to_workbook,
  15005. to_sheet: dif_to_sheet,
  15006. from_sheet: sheet_to_dif
  15007. };
  15008. })();
  15009. var ETH = (function() {
  15010. function decode(s) { return s.replace(/\\b/g,"\\").replace(/\\c/g,":").replace(/\\n/g,"\n"); }
  15011. function encode(s) { return s.replace(/\\/g, "\\b").replace(/:/g, "\\c").replace(/\n/g,"\\n"); }
  15012. function eth_to_aoa(str, opts) {
  15013. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  15014. for (; ri !== records.length; ++ri) {
  15015. var record = records[ri].trim().split(":");
  15016. if(record[0] !== 'cell') continue;
  15017. var addr = decode_cell(record[1]);
  15018. if(arr.length <= addr.r) for(R = arr.length; R <= addr.r; ++R) if(!arr[R]) arr[R] = [];
  15019. R = addr.r; C = addr.c;
  15020. switch(record[2]) {
  15021. case 't': arr[R][C] = decode(record[3]); break;
  15022. case 'v': arr[R][C] = +record[3]; break;
  15023. case 'vtf': var _f = record[record.length - 1];
  15024. /* falls through */
  15025. case 'vtc':
  15026. switch(record[3]) {
  15027. case 'nl': arr[R][C] = +record[4] ? true : false; break;
  15028. default: arr[R][C] = +record[4]; break;
  15029. }
  15030. if(record[2] == 'vtf') arr[R][C] = [arr[R][C], _f];
  15031. }
  15032. }
  15033. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  15034. return arr;
  15035. }
  15036. function eth_to_sheet(d, opts) { return aoa_to_sheet(eth_to_aoa(d, opts), opts); }
  15037. function eth_to_workbook(d, opts) { return sheet_to_workbook(eth_to_sheet(d, opts), opts); }
  15038. var header = [
  15039. "socialcalc:version:1.5",
  15040. "MIME-Version: 1.0",
  15041. "Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave"
  15042. ].join("\n");
  15043. var sep = [
  15044. "--SocialCalcSpreadsheetControlSave",
  15045. "Content-type: text/plain; charset=UTF-8"
  15046. ].join("\n") + "\n";
  15047. /* TODO: the other parts */
  15048. var meta = [
  15049. "# SocialCalc Spreadsheet Control Save",
  15050. "part:sheet"
  15051. ].join("\n");
  15052. var end = "--SocialCalcSpreadsheetControlSave--";
  15053. function sheet_to_eth_data(ws) {
  15054. if(!ws || !ws['!ref']) return "";
  15055. var o = [], oo = [], cell, coord = "";
  15056. var r = decode_range(ws['!ref']);
  15057. var dense = Array.isArray(ws);
  15058. for(var R = r.s.r; R <= r.e.r; ++R) {
  15059. for(var C = r.s.c; C <= r.e.c; ++C) {
  15060. coord = encode_cell({r:R,c:C});
  15061. cell = dense ? (ws[R]||[])[C] : ws[coord];
  15062. if(!cell || cell.v == null || cell.t === 'z') continue;
  15063. oo = ["cell", coord, 't'];
  15064. switch(cell.t) {
  15065. case 's': case 'str': oo.push(encode(cell.v)); break;
  15066. case 'n':
  15067. if(!cell.f) { oo[2]='v'; oo[3]=cell.v; }
  15068. else { oo[2]='vtf'; oo[3]='n'; oo[4]=cell.v; oo[5]=encode(cell.f); }
  15069. break;
  15070. case 'b':
  15071. oo[2] = 'vt'+(cell.f?'f':'c'); oo[3]='nl'; oo[4]=cell.v?"1":"0";
  15072. oo[5] = encode(cell.f||(cell.v?'TRUE':'FALSE'));
  15073. break;
  15074. case 'd':
  15075. var t = datenum(parseDate(cell.v));
  15076. oo[2] = 'vtc'; oo[3] = 'nd'; oo[4] = ""+t;
  15077. oo[5] = cell.w || SSF.format(cell.z || SSF._table[14], t);
  15078. break;
  15079. case 'e': continue;
  15080. }
  15081. o.push(oo.join(":"));
  15082. }
  15083. }
  15084. o.push("sheet:c:" + (r.e.c-r.s.c+1) + ":r:" + (r.e.r-r.s.r+1) + ":tvf:1");
  15085. o.push("valueformat:1:text-wiki");
  15086. //o.push("copiedfrom:" + ws['!ref']); // clipboard only
  15087. return o.join("\n");
  15088. }
  15089. function sheet_to_eth(ws) {
  15090. return [header, sep, meta, sep, sheet_to_eth_data(ws), end].join("\n");
  15091. // return ["version:1.5", sheet_to_eth_data(ws)].join("\n"); // clipboard form
  15092. }
  15093. return {
  15094. to_workbook: eth_to_workbook,
  15095. to_sheet: eth_to_sheet,
  15096. from_sheet: sheet_to_eth
  15097. };
  15098. })();
  15099. var PRN = (function() {
  15100. function set_text_arr(data, arr, R, C, o) {
  15101. if(o.raw) arr[R][C] = data;
  15102. else if(data === 'TRUE') arr[R][C] = true;
  15103. else if(data === 'FALSE') arr[R][C] = false;
  15104. else if(data === ""){/* empty */}
  15105. else if(!isNaN(fuzzynum(data))) arr[R][C] = fuzzynum(data);
  15106. else if(!isNaN(fuzzydate(data).getDate())) arr[R][C] = parseDate(data);
  15107. else arr[R][C] = data;
  15108. }
  15109. function prn_to_aoa_str(f, opts) {
  15110. var o = opts || {};
  15111. var arr = ([]);
  15112. if(!f || f.length === 0) return arr;
  15113. var lines = f.split(/[\r\n]/);
  15114. var L = lines.length - 1;
  15115. while(L >= 0 && lines[L].length === 0) --L;
  15116. var start = 10, idx = 0;
  15117. var R = 0;
  15118. for(; R <= L; ++R) {
  15119. idx = lines[R].indexOf(" ");
  15120. if(idx == -1) idx = lines[R].length; else idx++;
  15121. start = Math.max(start, idx);
  15122. }
  15123. for(R = 0; R <= L; ++R) {
  15124. arr[R] = [];
  15125. /* TODO: confirm that widths are always 10 */
  15126. var C = 0;
  15127. set_text_arr(lines[R].slice(0, start).trim(), arr, R, C, o);
  15128. for(C = 1; C <= (lines[R].length - start)/10 + 1; ++C)
  15129. set_text_arr(lines[R].slice(start+(C-1)*10,start+C*10).trim(),arr,R,C,o);
  15130. }
  15131. if(o.sheetRows) arr = arr.slice(0, o.sheetRows);
  15132. return arr;
  15133. }
  15134. // List of accepted CSV separators
  15135. var guess_seps = {
  15136. 0x2C: ',',
  15137. 0x09: "\t",
  15138. 0x3B: ';'
  15139. };
  15140. // CSV separator weights to be used in case of equal numbers
  15141. var guess_sep_weights = {
  15142. 0x2C: 3,
  15143. 0x09: 2,
  15144. 0x3B: 1
  15145. };
  15146. function guess_sep(str) {
  15147. var cnt = {}, instr = false, end = 0, cc = 0;
  15148. for(;end < str.length;++end) {
  15149. if((cc=str.charCodeAt(end)) == 0x22) instr = !instr;
  15150. else if(!instr && cc in guess_seps) cnt[cc] = (cnt[cc]||0)+1;
  15151. }
  15152. cc = [];
  15153. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  15154. cc.push([ cnt[end], end ]);
  15155. }
  15156. if ( !cc.length ) {
  15157. cnt = guess_sep_weights;
  15158. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  15159. cc.push([ cnt[end], end ]);
  15160. }
  15161. }
  15162. cc.sort(function(a, b) { return a[0] - b[0] || guess_sep_weights[a[1]] - guess_sep_weights[b[1]]; });
  15163. return guess_seps[cc.pop()[1]];
  15164. }
  15165. function dsv_to_sheet_str(str, opts) {
  15166. var o = opts || {};
  15167. var sep = "";
  15168. if(DENSE != null && o.dense == null) o.dense = DENSE;
  15169. var ws = o.dense ? ([]) : ({});
  15170. var range = ({s: {c:0, r:0}, e: {c:0, r:0}});
  15171. if(str.slice(0,4) == "sep=") {
  15172. // If the line ends in \r\n
  15173. if(str.charCodeAt(5) == 13 && str.charCodeAt(6) == 10 ) {
  15174. sep = str.charAt(4); str = str.slice(7);
  15175. }
  15176. // If line ends in \r OR \n
  15177. else if(str.charCodeAt(5) == 13 || str.charCodeAt(5) == 10 ) {
  15178. //
  15179. sep = str.charAt(4); str = str.slice(6);
  15180. }
  15181. }
  15182. else sep = guess_sep(str.slice(0,1024));
  15183. var R = 0, C = 0, v = 0;
  15184. var start = 0, end = 0, sepcc = sep.charCodeAt(0), instr = false, cc=0;
  15185. str = str.replace(/\r\n/mg, "\n");
  15186. var _re = o.dateNF != null ? dateNF_regex(o.dateNF) : null;
  15187. function finish_cell() {
  15188. var s = str.slice(start, end);
  15189. var cell = ({});
  15190. if(s.charAt(0) == '"' && s.charAt(s.length - 1) == '"') s = s.slice(1,-1).replace(/""/g,'"');
  15191. if(s.length === 0) cell.t = 'z';
  15192. else if(o.raw) { cell.t = 's'; cell.v = s; }
  15193. else if(s.trim().length === 0) { cell.t = 's'; cell.v = s; }
  15194. else if(s.charCodeAt(0) == 0x3D) {
  15195. if(s.charCodeAt(1) == 0x22 && s.charCodeAt(s.length - 1) == 0x22) { cell.t = 's'; cell.v = s.slice(2,-1).replace(/""/g,'"'); }
  15196. else if(fuzzyfmla(s)) { cell.t = 'n'; cell.f = s.slice(1); }
  15197. else { cell.t = 's'; cell.v = s; } }
  15198. else if(s == "TRUE") { cell.t = 'b'; cell.v = true; }
  15199. else if(s == "FALSE") { cell.t = 'b'; cell.v = false; }
  15200. else if(!isNaN(v = fuzzynum(s))) { cell.t = 'n'; if(o.cellText !== false) cell.w = s; cell.v = v; }
  15201. else if(!isNaN(fuzzydate(s).getDate()) || _re && s.match(_re)) {
  15202. cell.z = o.dateNF || SSF._table[14];
  15203. var k = 0;
  15204. if(_re && s.match(_re)){ s=dateNF_fix(s, o.dateNF, (s.match(_re)||[])); k=1; }
  15205. if(o.cellDates) { cell.t = 'd'; cell.v = parseDate(s, k); }
  15206. else { cell.t = 'n'; cell.v = datenum(parseDate(s, k)); }
  15207. if(o.cellText !== false) cell.w = SSF.format(cell.z, cell.v instanceof Date ? datenum(cell.v):cell.v);
  15208. if(!o.cellNF) delete cell.z;
  15209. } else {
  15210. cell.t = 's';
  15211. cell.v = s;
  15212. }
  15213. if(cell.t == 'z'){}
  15214. else if(o.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = cell; }
  15215. else ws[encode_cell({c:C,r:R})] = cell;
  15216. start = end+1;
  15217. if(range.e.c < C) range.e.c = C;
  15218. if(range.e.r < R) range.e.r = R;
  15219. if(cc == sepcc) ++C; else { C = 0; ++R; if(o.sheetRows && o.sheetRows <= R) return true; }
  15220. }
  15221. outer: for(;end < str.length;++end) switch((cc=str.charCodeAt(end))) {
  15222. case 0x22: instr = !instr; break;
  15223. case sepcc: case 0x0a: case 0x0d: if(!instr && finish_cell()) break outer; break;
  15224. default: break;
  15225. }
  15226. if(end - start > 0) finish_cell();
  15227. ws['!ref'] = encode_range(range);
  15228. return ws;
  15229. }
  15230. function prn_to_sheet_str(str, opts) {
  15231. if(!(opts && opts.PRN)) return dsv_to_sheet_str(str, opts);
  15232. if(str.slice(0,4) == "sep=") return dsv_to_sheet_str(str, opts);
  15233. if(str.indexOf("\t") >= 0 || str.indexOf(",") >= 0 || str.indexOf(";") >= 0) return dsv_to_sheet_str(str, opts);
  15234. return aoa_to_sheet(prn_to_aoa_str(str, opts), opts);
  15235. }
  15236. function prn_to_sheet(d, opts) {
  15237. var str = "", bytes = opts.type == 'string' ? [0,0,0,0] : firstbyte(d, opts);
  15238. switch(opts.type) {
  15239. case 'base64': str = Base64.decode(d); break;
  15240. case 'binary': str = d; break;
  15241. case 'buffer':
  15242. if(opts.codepage == 65001) str = d.toString('utf8');
  15243. else if(opts.codepage && typeof cptable !== 'undefined') str = cptable.utils.decode(opts.codepage, d);
  15244. else str = d.toString('binary');
  15245. break;
  15246. case 'array': str = cc2str(d); break;
  15247. case 'string': str = d; break;
  15248. default: throw new Error("Unrecognized type " + opts.type);
  15249. }
  15250. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str.slice(3));
  15251. else if((opts.type == 'binary') && typeof cptable !== 'undefined' && opts.codepage) str = cptable.utils.decode(opts.codepage, cptable.utils.encode(1252,str));
  15252. if(str.slice(0,19) == "socialcalc:version:") return ETH.to_sheet(opts.type == 'string' ? str : utf8read(str), opts);
  15253. return prn_to_sheet_str(str, opts);
  15254. }
  15255. function prn_to_workbook(d, opts) { return sheet_to_workbook(prn_to_sheet(d, opts), opts); }
  15256. function sheet_to_prn(ws) {
  15257. var o = [];
  15258. var r = safe_decode_range(ws['!ref']), cell;
  15259. var dense = Array.isArray(ws);
  15260. for(var R = r.s.r; R <= r.e.r; ++R) {
  15261. var oo = [];
  15262. for(var C = r.s.c; C <= r.e.c; ++C) {
  15263. var coord = encode_cell({r:R,c:C});
  15264. cell = dense ? (ws[R]||[])[C] : ws[coord];
  15265. if(!cell || cell.v == null) { oo.push(" "); continue; }
  15266. var w = (cell.w || (format_cell(cell), cell.w) || "").slice(0,10);
  15267. while(w.length < 10) w += " ";
  15268. oo.push(w + (C === 0 ? " " : ""));
  15269. }
  15270. o.push(oo.join(""));
  15271. }
  15272. return o.join("\n");
  15273. }
  15274. return {
  15275. to_workbook: prn_to_workbook,
  15276. to_sheet: prn_to_sheet,
  15277. from_sheet: sheet_to_prn
  15278. };
  15279. })();
  15280. /* Excel defaults to SYLK but warns if data is not valid */
  15281. function read_wb_ID(d, opts) {
  15282. var o = opts || {}, OLD_WTF = !!o.WTF; o.WTF = true;
  15283. try {
  15284. var out = SYLK.to_workbook(d, o);
  15285. o.WTF = OLD_WTF;
  15286. return out;
  15287. } catch(e) {
  15288. o.WTF = OLD_WTF;
  15289. if(!e.message.match(/SYLK bad record ID/) && OLD_WTF) throw e;
  15290. return PRN.to_workbook(d, opts);
  15291. }
  15292. }
  15293. var WK_ = (function() {
  15294. function lotushopper(data, cb, opts) {
  15295. if(!data) return;
  15296. prep_blob(data, data.l || 0);
  15297. var Enum = opts.Enum || WK1Enum;
  15298. while(data.l < data.length) {
  15299. var RT = data.read_shift(2);
  15300. var R = Enum[RT] || Enum[0xFF];
  15301. var length = data.read_shift(2);
  15302. var tgt = data.l + length;
  15303. var d = (R.f||parsenoop)(data, length, opts);
  15304. data.l = tgt;
  15305. if(cb(d, R.n, RT)) return;
  15306. }
  15307. }
  15308. function lotus_to_workbook(d, opts) {
  15309. switch(opts.type) {
  15310. case 'base64': return lotus_to_workbook_buf(s2a(Base64.decode(d)), opts);
  15311. case 'binary': return lotus_to_workbook_buf(s2a(d), opts);
  15312. case 'buffer':
  15313. case 'array': return lotus_to_workbook_buf(d, opts);
  15314. }
  15315. throw "Unsupported type " + opts.type;
  15316. }
  15317. function lotus_to_workbook_buf(d, opts) {
  15318. if(!d) return d;
  15319. var o = opts || {};
  15320. if(DENSE != null && o.dense == null) o.dense = DENSE;
  15321. var s = ((o.dense ? [] : {})), n = "Sheet1", sidx = 0;
  15322. var sheets = {}, snames = [n];
  15323. var refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
  15324. var sheetRows = o.sheetRows || 0;
  15325. if(d[2] == 0x02) o.Enum = WK1Enum;
  15326. else if(d[2] == 0x1a) o.Enum = WK3Enum;
  15327. else if(d[2] == 0x0e) { o.Enum = WK3Enum; o.qpro = true; d.l = 0; }
  15328. else throw new Error("Unrecognized LOTUS BOF " + d[2]);
  15329. lotushopper(d, function(val, Rn, RT) {
  15330. if(d[2] == 0x02) switch(RT) {
  15331. case 0x00:
  15332. o.vers = val;
  15333. if(val >= 0x1000) o.qpro = true;
  15334. break;
  15335. case 0x06: refguess = val; break; /* RANGE */
  15336. case 0x0F: /* LABEL */
  15337. if(!o.qpro) val[1].v = val[1].v.slice(1);
  15338. /* falls through */
  15339. case 0x0D: /* INTEGER */
  15340. case 0x0E: /* NUMBER */
  15341. case 0x10: /* FORMULA */
  15342. case 0x33: /* STRING */
  15343. /* TODO: actual translation of the format code */
  15344. if(RT == 0x0E && (val[2] & 0x70) == 0x70 && (val[2] & 0x0F) > 1 && (val[2] & 0x0F) < 15) {
  15345. val[1].z = o.dateNF || SSF._table[14];
  15346. if(o.cellDates) { val[1].t = 'd'; val[1].v = numdate(val[1].v); }
  15347. }
  15348. if(o.dense) {
  15349. if(!s[val[0].r]) s[val[0].r] = [];
  15350. s[val[0].r][val[0].c] = val[1];
  15351. } else s[encode_cell(val[0])] = val[1];
  15352. break;
  15353. } else switch(RT) {
  15354. case 0x16: /* LABEL16 */
  15355. val[1].v = val[1].v.slice(1);
  15356. /* falls through */
  15357. case 0x17: /* NUMBER17 */
  15358. case 0x18: /* NUMBER18 */
  15359. case 0x19: /* FORMULA19 */
  15360. case 0x25: /* NUMBER25 */
  15361. case 0x27: /* NUMBER27 */
  15362. case 0x28: /* FORMULA28 */
  15363. if(val[3] > sidx) {
  15364. s["!ref"] = encode_range(refguess);
  15365. sheets[n] = s;
  15366. s = (o.dense ? [] : {});
  15367. refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
  15368. sidx = val[3]; n = "Sheet" + (sidx + 1);
  15369. snames.push(n);
  15370. }
  15371. if(sheetRows > 0 && val[0].r >= sheetRows) break;
  15372. if(o.dense) {
  15373. if(!s[val[0].r]) s[val[0].r] = [];
  15374. s[val[0].r][val[0].c] = val[1];
  15375. } else s[encode_cell(val[0])] = val[1];
  15376. if(refguess.e.c < val[0].c) refguess.e.c = val[0].c;
  15377. if(refguess.e.r < val[0].r) refguess.e.r = val[0].r;
  15378. break;
  15379. default: break;
  15380. }
  15381. }, o);
  15382. s["!ref"] = encode_range(refguess);
  15383. sheets[n] = s;
  15384. return { SheetNames: snames, Sheets:sheets };
  15385. }
  15386. function parse_RANGE(blob) {
  15387. var o = {s:{c:0,r:0},e:{c:0,r:0}};
  15388. o.s.c = blob.read_shift(2);
  15389. o.s.r = blob.read_shift(2);
  15390. o.e.c = blob.read_shift(2);
  15391. o.e.r = blob.read_shift(2);
  15392. if(o.s.c == 0xFFFF) o.s.c = o.e.c = o.s.r = o.e.r = 0;
  15393. return o;
  15394. }
  15395. function parse_cell(blob, length, opts) {
  15396. var o = [{c:0,r:0}, {t:'n',v:0}, 0];
  15397. if(opts.qpro && opts.vers != 0x5120) {
  15398. o[0].c = blob.read_shift(1);
  15399. blob.l++;
  15400. o[0].r = blob.read_shift(2);
  15401. blob.l+=2;
  15402. } else {
  15403. o[2] = blob.read_shift(1);
  15404. o[0].c = blob.read_shift(2); o[0].r = blob.read_shift(2);
  15405. }
  15406. return o;
  15407. }
  15408. function parse_LABEL(blob, length, opts) {
  15409. var tgt = blob.l + length;
  15410. var o = parse_cell(blob, length, opts);
  15411. o[1].t = 's';
  15412. if(opts.vers == 0x5120) {
  15413. blob.l++;
  15414. var len = blob.read_shift(1);
  15415. o[1].v = blob.read_shift(len, 'utf8');
  15416. return o;
  15417. }
  15418. if(opts.qpro) blob.l++;
  15419. o[1].v = blob.read_shift(tgt - blob.l, 'cstr');
  15420. return o;
  15421. }
  15422. function parse_INTEGER(blob, length, opts) {
  15423. var o = parse_cell(blob, length, opts);
  15424. o[1].v = blob.read_shift(2, 'i');
  15425. return o;
  15426. }
  15427. function parse_NUMBER(blob, length, opts) {
  15428. var o = parse_cell(blob, length, opts);
  15429. o[1].v = blob.read_shift(8, 'f');
  15430. return o;
  15431. }
  15432. function parse_FORMULA(blob, length, opts) {
  15433. var tgt = blob.l + length;
  15434. var o = parse_cell(blob, length, opts);
  15435. /* TODO: formula */
  15436. o[1].v = blob.read_shift(8, 'f');
  15437. if(opts.qpro) blob.l = tgt;
  15438. else {
  15439. var flen = blob.read_shift(2);
  15440. blob.l += flen;
  15441. }
  15442. return o;
  15443. }
  15444. function parse_cell_3(blob) {
  15445. var o = [{c:0,r:0}, {t:'n',v:0}, 0];
  15446. o[0].r = blob.read_shift(2); o[3] = blob[blob.l++]; o[0].c = blob[blob.l++];
  15447. return o;
  15448. }
  15449. function parse_LABEL_16(blob, length) {
  15450. var o = parse_cell_3(blob, length);
  15451. o[1].t = 's';
  15452. o[1].v = blob.read_shift(length - 4, 'cstr');
  15453. return o;
  15454. }
  15455. function parse_NUMBER_18(blob, length) {
  15456. var o = parse_cell_3(blob, length);
  15457. o[1].v = blob.read_shift(2);
  15458. var v = o[1].v >> 1;
  15459. /* TODO: figure out all of the corner cases */
  15460. if(o[1].v & 0x1) {
  15461. switch(v & 0x07) {
  15462. case 1: v = (v >> 3) * 500; break;
  15463. case 2: v = (v >> 3) / 20; break;
  15464. case 4: v = (v >> 3) / 2000; break;
  15465. case 6: v = (v >> 3) / 16; break;
  15466. case 7: v = (v >> 3) / 64; break;
  15467. default: throw "unknown NUMBER_18 encoding " + (v & 0x07);
  15468. }
  15469. }
  15470. o[1].v = v;
  15471. return o;
  15472. }
  15473. function parse_NUMBER_17(blob, length) {
  15474. var o = parse_cell_3(blob, length);
  15475. var v1 = blob.read_shift(4);
  15476. var v2 = blob.read_shift(4);
  15477. var e = blob.read_shift(2);
  15478. if(e == 0xFFFF) { o[1].v = 0; return o; }
  15479. var s = e & 0x8000; e = (e&0x7FFF) - 16446;
  15480. o[1].v = (s*2 - 1) * ((e > 0 ? (v2 << e) : (v2 >>> -e)) + (e > -32 ? (v1 << (e + 32)) : (v1 >>> -(e + 32))));
  15481. return o;
  15482. }
  15483. function parse_FORMULA_19(blob, length) {
  15484. var o = parse_NUMBER_17(blob, 14);
  15485. blob.l += length - 14; /* TODO: formula */
  15486. return o;
  15487. }
  15488. function parse_NUMBER_25(blob, length) {
  15489. var o = parse_cell_3(blob, length);
  15490. var v1 = blob.read_shift(4);
  15491. o[1].v = v1 >> 6;
  15492. return o;
  15493. }
  15494. function parse_NUMBER_27(blob, length) {
  15495. var o = parse_cell_3(blob, length);
  15496. var v1 = blob.read_shift(8,'f');
  15497. o[1].v = v1;
  15498. return o;
  15499. }
  15500. function parse_FORMULA_28(blob, length) {
  15501. var o = parse_NUMBER_27(blob, 14);
  15502. blob.l += length - 10; /* TODO: formula */
  15503. return o;
  15504. }
  15505. var WK1Enum = {
  15506. 0x0000: { n:"BOF", f:parseuint16 },
  15507. 0x0001: { n:"EOF" },
  15508. 0x0002: { n:"CALCMODE" },
  15509. 0x0003: { n:"CALCORDER" },
  15510. 0x0004: { n:"SPLIT" },
  15511. 0x0005: { n:"SYNC" },
  15512. 0x0006: { n:"RANGE", f:parse_RANGE },
  15513. 0x0007: { n:"WINDOW1" },
  15514. 0x0008: { n:"COLW1" },
  15515. 0x0009: { n:"WINTWO" },
  15516. 0x000A: { n:"COLW2" },
  15517. 0x000B: { n:"NAME" },
  15518. 0x000C: { n:"BLANK" },
  15519. 0x000D: { n:"INTEGER", f:parse_INTEGER },
  15520. 0x000E: { n:"NUMBER", f:parse_NUMBER },
  15521. 0x000F: { n:"LABEL", f:parse_LABEL },
  15522. 0x0010: { n:"FORMULA", f:parse_FORMULA },
  15523. 0x0018: { n:"TABLE" },
  15524. 0x0019: { n:"ORANGE" },
  15525. 0x001A: { n:"PRANGE" },
  15526. 0x001B: { n:"SRANGE" },
  15527. 0x001C: { n:"FRANGE" },
  15528. 0x001D: { n:"KRANGE1" },
  15529. 0x0020: { n:"HRANGE" },
  15530. 0x0023: { n:"KRANGE2" },
  15531. 0x0024: { n:"PROTEC" },
  15532. 0x0025: { n:"FOOTER" },
  15533. 0x0026: { n:"HEADER" },
  15534. 0x0027: { n:"SETUP" },
  15535. 0x0028: { n:"MARGINS" },
  15536. 0x0029: { n:"LABELFMT" },
  15537. 0x002A: { n:"TITLES" },
  15538. 0x002B: { n:"SHEETJS" },
  15539. 0x002D: { n:"GRAPH" },
  15540. 0x002E: { n:"NGRAPH" },
  15541. 0x002F: { n:"CALCCOUNT" },
  15542. 0x0030: { n:"UNFORMATTED" },
  15543. 0x0031: { n:"CURSORW12" },
  15544. 0x0032: { n:"WINDOW" },
  15545. 0x0033: { n:"STRING", f:parse_LABEL },
  15546. 0x0037: { n:"PASSWORD" },
  15547. 0x0038: { n:"LOCKED" },
  15548. 0x003C: { n:"QUERY" },
  15549. 0x003D: { n:"QUERYNAME" },
  15550. 0x003E: { n:"PRINT" },
  15551. 0x003F: { n:"PRINTNAME" },
  15552. 0x0040: { n:"GRAPH2" },
  15553. 0x0041: { n:"GRAPHNAME" },
  15554. 0x0042: { n:"ZOOM" },
  15555. 0x0043: { n:"SYMSPLIT" },
  15556. 0x0044: { n:"NSROWS" },
  15557. 0x0045: { n:"NSCOLS" },
  15558. 0x0046: { n:"RULER" },
  15559. 0x0047: { n:"NNAME" },
  15560. 0x0048: { n:"ACOMM" },
  15561. 0x0049: { n:"AMACRO" },
  15562. 0x004A: { n:"PARSE" },
  15563. 0x00FF: { n:"", f:parsenoop }
  15564. };
  15565. var WK3Enum = {
  15566. 0x0000: { n:"BOF" },
  15567. 0x0001: { n:"EOF" },
  15568. 0x0003: { n:"??" },
  15569. 0x0004: { n:"??" },
  15570. 0x0005: { n:"??" },
  15571. 0x0006: { n:"??" },
  15572. 0x0007: { n:"??" },
  15573. 0x0009: { n:"??" },
  15574. 0x000a: { n:"??" },
  15575. 0x000b: { n:"??" },
  15576. 0x000c: { n:"??" },
  15577. 0x000e: { n:"??" },
  15578. 0x000f: { n:"??" },
  15579. 0x0010: { n:"??" },
  15580. 0x0011: { n:"??" },
  15581. 0x0012: { n:"??" },
  15582. 0x0013: { n:"??" },
  15583. 0x0015: { n:"??" },
  15584. 0x0016: { n:"LABEL16", f:parse_LABEL_16},
  15585. 0x0017: { n:"NUMBER17", f:parse_NUMBER_17 },
  15586. 0x0018: { n:"NUMBER18", f:parse_NUMBER_18 },
  15587. 0x0019: { n:"FORMULA19", f:parse_FORMULA_19},
  15588. 0x001a: { n:"??" },
  15589. 0x001b: { n:"??" },
  15590. 0x001c: { n:"??" },
  15591. 0x001d: { n:"??" },
  15592. 0x001e: { n:"??" },
  15593. 0x001f: { n:"??" },
  15594. 0x0021: { n:"??" },
  15595. 0x0025: { n:"NUMBER25", f:parse_NUMBER_25 },
  15596. 0x0027: { n:"NUMBER27", f:parse_NUMBER_27 },
  15597. 0x0028: { n:"FORMULA28", f:parse_FORMULA_28 },
  15598. 0x00FF: { n:"", f:parsenoop }
  15599. };
  15600. return {
  15601. to_workbook: lotus_to_workbook
  15602. };
  15603. })();
  15604. /* 18.4.7 rPr CT_RPrElt */
  15605. function parse_rpr(rpr) {
  15606. var font = {}, m = rpr.match(tagregex), i = 0;
  15607. var pass = false;
  15608. if(m) for(;i!=m.length; ++i) {
  15609. var y = parsexmltag(m[i]);
  15610. switch(y[0].replace(/\w*:/g,"")) {
  15611. /* 18.8.12 condense CT_BooleanProperty */
  15612. /* ** not required . */
  15613. case '<condense': break;
  15614. /* 18.8.17 extend CT_BooleanProperty */
  15615. /* ** not required . */
  15616. case '<extend': break;
  15617. /* 18.8.36 shadow CT_BooleanProperty */
  15618. /* ** not required . */
  15619. case '<shadow':
  15620. if(!y.val) break;
  15621. /* falls through */
  15622. case '<shadow>':
  15623. case '<shadow/>': font.shadow = 1; break;
  15624. case '</shadow>': break;
  15625. /* 18.4.1 charset CT_IntProperty TODO */
  15626. case '<charset':
  15627. if(y.val == '1') break;
  15628. font.cp = CS2CP[parseInt(y.val, 10)];
  15629. break;
  15630. /* 18.4.2 outline CT_BooleanProperty TODO */
  15631. case '<outline':
  15632. if(!y.val) break;
  15633. /* falls through */
  15634. case '<outline>':
  15635. case '<outline/>': font.outline = 1; break;
  15636. case '</outline>': break;
  15637. /* 18.4.5 rFont CT_FontName */
  15638. case '<rFont': font.name = y.val; break;
  15639. /* 18.4.11 sz CT_FontSize */
  15640. case '<sz': font.sz = y.val; break;
  15641. /* 18.4.10 strike CT_BooleanProperty */
  15642. case '<strike':
  15643. if(!y.val) break;
  15644. /* falls through */
  15645. case '<strike>':
  15646. case '<strike/>': font.strike = 1; break;
  15647. case '</strike>': break;
  15648. /* 18.4.13 u CT_UnderlineProperty */
  15649. case '<u':
  15650. if(!y.val) break;
  15651. switch(y.val) {
  15652. case 'double': font.uval = "double"; break;
  15653. case 'singleAccounting': font.uval = "single-accounting"; break;
  15654. case 'doubleAccounting': font.uval = "double-accounting"; break;
  15655. }
  15656. /* falls through */
  15657. case '<u>':
  15658. case '<u/>': font.u = 1; break;
  15659. case '</u>': break;
  15660. /* 18.8.2 b */
  15661. case '<b':
  15662. if(y.val == '0') break;
  15663. /* falls through */
  15664. case '<b>':
  15665. case '<b/>': font.b = 1; break;
  15666. case '</b>': break;
  15667. /* 18.8.26 i */
  15668. case '<i':
  15669. if(y.val == '0') break;
  15670. /* falls through */
  15671. case '<i>':
  15672. case '<i/>': font.i = 1; break;
  15673. case '</i>': break;
  15674. /* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
  15675. case '<color':
  15676. if(y.rgb) font.color = y.rgb.slice(2,8);
  15677. break;
  15678. /* 18.8.18 family ST_FontFamily */
  15679. case '<family': font.family = y.val; break;
  15680. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
  15681. case '<vertAlign': font.valign = y.val; break;
  15682. /* 18.8.35 scheme CT_FontScheme TODO */
  15683. case '<scheme': break;
  15684. /* 18.2.10 extLst CT_ExtensionList ? */
  15685. case '<extLst': case '<extLst>': case '</extLst>': break;
  15686. case '<ext': pass = true; break;
  15687. case '</ext>': pass = false; break;
  15688. default:
  15689. if(y[0].charCodeAt(1) !== 47 && !pass) throw new Error('Unrecognized rich format ' + y[0]);
  15690. }
  15691. }
  15692. return font;
  15693. }
  15694. var parse_rs = (function() {
  15695. var tregex = matchtag("t"), rpregex = matchtag("rPr");
  15696. /* 18.4.4 r CT_RElt */
  15697. function parse_r(r) {
  15698. /* 18.4.12 t ST_Xstring */
  15699. var t = r.match(tregex)/*, cp = 65001*/;
  15700. if(!t) return {t:"s", v:""};
  15701. var o = ({t:'s', v:unescapexml(t[1])});
  15702. var rpr = r.match(rpregex);
  15703. if(rpr) o.s = parse_rpr(rpr[1]);
  15704. return o;
  15705. }
  15706. var rregex = /<(?:\w+:)?r>/g, rend = /<\/(?:\w+:)?r>/;
  15707. return function parse_rs(rs) {
  15708. return rs.replace(rregex,"").split(rend).map(parse_r).filter(function(r) { return r.v; });
  15709. };
  15710. })();
  15711. /* Parse a list of <r> tags */
  15712. var rs_to_html = (function parse_rs_factory() {
  15713. var nlregex = /(\r\n|\n)/g;
  15714. function parse_rpr2(font, intro, outro) {
  15715. var style = [];
  15716. if(font.u) style.push("text-decoration: underline;");
  15717. if(font.uval) style.push("text-underline-style:" + font.uval + ";");
  15718. if(font.sz) style.push("font-size:" + font.sz + "pt;");
  15719. if(font.outline) style.push("text-effect: outline;");
  15720. if(font.shadow) style.push("text-shadow: auto;");
  15721. intro.push('<span style="' + style.join("") + '">');
  15722. if(font.b) { intro.push("<b>"); outro.push("</b>"); }
  15723. if(font.i) { intro.push("<i>"); outro.push("</i>"); }
  15724. if(font.strike) { intro.push("<s>"); outro.push("</s>"); }
  15725. var align = font.valign || "";
  15726. if(align == "superscript" || align == "super") align = "sup";
  15727. else if(align == "subscript") align = "sub";
  15728. if(align != "") { intro.push("<" + align + ">"); outro.push("</" + align + ">"); }
  15729. outro.push("</span>");
  15730. return font;
  15731. }
  15732. /* 18.4.4 r CT_RElt */
  15733. function r_to_html(r) {
  15734. var terms = [[],r.v,[]];
  15735. if(!r.v) return "";
  15736. if(r.s) parse_rpr2(r.s, terms[0], terms[2]);
  15737. return terms[0].join("") + terms[1].replace(nlregex,'<br/>') + terms[2].join("");
  15738. }
  15739. return function parse_rs(rs) {
  15740. return rs.map(r_to_html).join("");
  15741. };
  15742. })();
  15743. /* 18.4.8 si CT_Rst */
  15744. var sitregex = /<(?:\w+:)?t[^>]*>([^<]*)<\/(?:\w+:)?t>/g, sirregex = /<(?:\w+:)?r>/;
  15745. var sirphregex = /<(?:\w+:)?rPh.*?>([\s\S]*?)<\/(?:\w+:)?rPh>/g;
  15746. function parse_si(x, opts) {
  15747. var html = opts ? opts.cellHTML : true;
  15748. var z = {};
  15749. if(!x) return { t: "" };
  15750. //var y;
  15751. /* 18.4.12 t ST_Xstring (Plaintext String) */
  15752. // TODO: is whitespace actually valid here?
  15753. if(x.match(/^\s*<(?:\w+:)?t[^>]*>/)) {
  15754. z.t = unescapexml(utf8read(x.slice(x.indexOf(">")+1).split(/<\/(?:\w+:)?t>/)[0]||""));
  15755. z.r = utf8read(x);
  15756. if(html) z.h = escapehtml(z.t);
  15757. }
  15758. /* 18.4.4 r CT_RElt (Rich Text Run) */
  15759. else if((/*y = */x.match(sirregex))) {
  15760. z.r = utf8read(x);
  15761. z.t = unescapexml(utf8read((x.replace(sirphregex, '').match(sitregex)||[]).join("").replace(tagregex,"")));
  15762. if(html) z.h = rs_to_html(parse_rs(z.r));
  15763. }
  15764. /* 18.4.3 phoneticPr CT_PhoneticPr (TODO: needed for Asian support) */
  15765. /* 18.4.6 rPh CT_PhoneticRun (TODO: needed for Asian support) */
  15766. return z;
  15767. }
  15768. /* 18.4 Shared String Table */
  15769. var sstr0 = /<(?:\w+:)?sst([^>]*)>([\s\S]*)<\/(?:\w+:)?sst>/;
  15770. var sstr1 = /<(?:\w+:)?(?:si|sstItem)>/g;
  15771. var sstr2 = /<\/(?:\w+:)?(?:si|sstItem)>/;
  15772. function parse_sst_xml(data, opts) {
  15773. var s = ([]), ss = "";
  15774. if(!data) return s;
  15775. /* 18.4.9 sst CT_Sst */
  15776. var sst = data.match(sstr0);
  15777. if(sst) {
  15778. ss = sst[2].replace(sstr1,"").split(sstr2);
  15779. for(var i = 0; i != ss.length; ++i) {
  15780. var o = parse_si(ss[i].trim(), opts);
  15781. if(o != null) s[s.length] = o;
  15782. }
  15783. sst = parsexmltag(sst[1]); s.Count = sst.count; s.Unique = sst.uniqueCount;
  15784. }
  15785. return s;
  15786. }
  15787. RELS.SST = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
  15788. var straywsregex = /^\s|\s$|[\t\n\r]/;
  15789. function write_sst_xml(sst, opts) {
  15790. if(!opts.bookSST) return "";
  15791. var o = [XML_HEADER];
  15792. o[o.length] = (writextag('sst', null, {
  15793. xmlns: XMLNS.main[0],
  15794. count: sst.Count,
  15795. uniqueCount: sst.Unique
  15796. }));
  15797. for(var i = 0; i != sst.length; ++i) { if(sst[i] == null) continue;
  15798. var s = sst[i];
  15799. var sitag = "<si>";
  15800. if(s.r) sitag += s.r;
  15801. else {
  15802. sitag += "<t";
  15803. if(!s.t) s.t = "";
  15804. if(s.t.match(straywsregex)) sitag += ' xml:space="preserve"';
  15805. sitag += ">" + escapexml(s.t) + "</t>";
  15806. }
  15807. sitag += "</si>";
  15808. o[o.length] = (sitag);
  15809. }
  15810. if(o.length>2){ o[o.length] = ('</sst>'); o[1]=o[1].replace("/>",">"); }
  15811. return o.join("");
  15812. }
  15813. /* [MS-XLSB] 2.4.221 BrtBeginSst */
  15814. function parse_BrtBeginSst(data) {
  15815. return [data.read_shift(4), data.read_shift(4)];
  15816. }
  15817. /* [MS-XLSB] 2.1.7.45 Shared Strings */
  15818. function parse_sst_bin(data, opts) {
  15819. var s = ([]);
  15820. var pass = false;
  15821. recordhopper(data, function hopper_sst(val, R_n, RT) {
  15822. switch(RT) {
  15823. case 0x009F: /* 'BrtBeginSst' */
  15824. s.Count = val[0]; s.Unique = val[1]; break;
  15825. case 0x0013: /* 'BrtSSTItem' */
  15826. s.push(val); break;
  15827. case 0x00A0: /* 'BrtEndSst' */
  15828. return true;
  15829. case 0x0023: /* 'BrtFRTBegin' */
  15830. pass = true; break;
  15831. case 0x0024: /* 'BrtFRTEnd' */
  15832. pass = false; break;
  15833. default:
  15834. if(R_n.indexOf("Begin") > 0){/* empty */}
  15835. else if(R_n.indexOf("End") > 0){/* empty */}
  15836. if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  15837. }
  15838. });
  15839. return s;
  15840. }
  15841. function write_BrtBeginSst(sst, o) {
  15842. if(!o) o = new_buf(8);
  15843. o.write_shift(4, sst.Count);
  15844. o.write_shift(4, sst.Unique);
  15845. return o;
  15846. }
  15847. var write_BrtSSTItem = write_RichStr;
  15848. function write_sst_bin(sst) {
  15849. var ba = buf_array();
  15850. write_record(ba, "BrtBeginSst", write_BrtBeginSst(sst));
  15851. for(var i = 0; i < sst.length; ++i) write_record(ba, "BrtSSTItem", write_BrtSSTItem(sst[i]));
  15852. /* FRTSST */
  15853. write_record(ba, "BrtEndSst");
  15854. return ba.end();
  15855. }
  15856. function _JS2ANSI(str) {
  15857. if(typeof cptable !== 'undefined') return cptable.utils.encode(current_ansi, str);
  15858. var o = [], oo = str.split("");
  15859. for(var i = 0; i < oo.length; ++i) o[i] = oo[i].charCodeAt(0);
  15860. return o;
  15861. }
  15862. /* [MS-OFFCRYPTO] 2.1.4 Version */
  15863. function parse_CRYPTOVersion(blob, length) {
  15864. var o = {};
  15865. o.Major = blob.read_shift(2);
  15866. o.Minor = blob.read_shift(2);
  15867. if(length >= 4) blob.l += length - 4;
  15868. return o;
  15869. }
  15870. /* [MS-OFFCRYPTO] 2.1.5 DataSpaceVersionInfo */
  15871. function parse_DataSpaceVersionInfo(blob) {
  15872. var o = {};
  15873. o.id = blob.read_shift(0, 'lpp4');
  15874. o.R = parse_CRYPTOVersion(blob, 4);
  15875. o.U = parse_CRYPTOVersion(blob, 4);
  15876. o.W = parse_CRYPTOVersion(blob, 4);
  15877. return o;
  15878. }
  15879. /* [MS-OFFCRYPTO] 2.1.6.1 DataSpaceMapEntry Structure */
  15880. function parse_DataSpaceMapEntry(blob) {
  15881. var len = blob.read_shift(4);
  15882. var end = blob.l + len - 4;
  15883. var o = {};
  15884. var cnt = blob.read_shift(4);
  15885. var comps = [];
  15886. /* [MS-OFFCRYPTO] 2.1.6.2 DataSpaceReferenceComponent Structure */
  15887. while(cnt-- > 0) comps.push({ t: blob.read_shift(4), v: blob.read_shift(0, 'lpp4') });
  15888. o.name = blob.read_shift(0, 'lpp4');
  15889. o.comps = comps;
  15890. if(blob.l != end) throw new Error("Bad DataSpaceMapEntry: " + blob.l + " != " + end);
  15891. return o;
  15892. }
  15893. /* [MS-OFFCRYPTO] 2.1.6 DataSpaceMap */
  15894. function parse_DataSpaceMap(blob) {
  15895. var o = [];
  15896. blob.l += 4; // must be 0x8
  15897. var cnt = blob.read_shift(4);
  15898. while(cnt-- > 0) o.push(parse_DataSpaceMapEntry(blob));
  15899. return o;
  15900. }
  15901. /* [MS-OFFCRYPTO] 2.1.7 DataSpaceDefinition */
  15902. function parse_DataSpaceDefinition(blob) {
  15903. var o = [];
  15904. blob.l += 4; // must be 0x8
  15905. var cnt = blob.read_shift(4);
  15906. while(cnt-- > 0) o.push(blob.read_shift(0, 'lpp4'));
  15907. return o;
  15908. }
  15909. /* [MS-OFFCRYPTO] 2.1.8 DataSpaceDefinition */
  15910. function parse_TransformInfoHeader(blob) {
  15911. var o = {};
  15912. /*var len = */blob.read_shift(4);
  15913. blob.l += 4; // must be 0x1
  15914. o.id = blob.read_shift(0, 'lpp4');
  15915. o.name = blob.read_shift(0, 'lpp4');
  15916. o.R = parse_CRYPTOVersion(blob, 4);
  15917. o.U = parse_CRYPTOVersion(blob, 4);
  15918. o.W = parse_CRYPTOVersion(blob, 4);
  15919. return o;
  15920. }
  15921. function parse_Primary(blob) {
  15922. /* [MS-OFFCRYPTO] 2.2.6 IRMDSTransformInfo */
  15923. var hdr = parse_TransformInfoHeader(blob);
  15924. /* [MS-OFFCRYPTO] 2.1.9 EncryptionTransformInfo */
  15925. hdr.ename = blob.read_shift(0, '8lpp4');
  15926. hdr.blksz = blob.read_shift(4);
  15927. hdr.cmode = blob.read_shift(4);
  15928. if(blob.read_shift(4) != 0x04) throw new Error("Bad !Primary record");
  15929. return hdr;
  15930. }
  15931. /* [MS-OFFCRYPTO] 2.3.2 Encryption Header */
  15932. function parse_EncryptionHeader(blob, length) {
  15933. var tgt = blob.l + length;
  15934. var o = {};
  15935. o.Flags = (blob.read_shift(4) & 0x3F);
  15936. blob.l += 4;
  15937. o.AlgID = blob.read_shift(4);
  15938. var valid = false;
  15939. switch(o.AlgID) {
  15940. case 0x660E: case 0x660F: case 0x6610: valid = (o.Flags == 0x24); break;
  15941. case 0x6801: valid = (o.Flags == 0x04); break;
  15942. case 0: valid = (o.Flags == 0x10 || o.Flags == 0x04 || o.Flags == 0x24); break;
  15943. default: throw 'Unrecognized encryption algorithm: ' + o.AlgID;
  15944. }
  15945. if(!valid) throw new Error("Encryption Flags/AlgID mismatch");
  15946. o.AlgIDHash = blob.read_shift(4);
  15947. o.KeySize = blob.read_shift(4);
  15948. o.ProviderType = blob.read_shift(4);
  15949. blob.l += 8;
  15950. o.CSPName = blob.read_shift((tgt-blob.l)>>1, 'utf16le');
  15951. blob.l = tgt;
  15952. return o;
  15953. }
  15954. /* [MS-OFFCRYPTO] 2.3.3 Encryption Verifier */
  15955. function parse_EncryptionVerifier(blob, length) {
  15956. var o = {}, tgt = blob.l + length;
  15957. blob.l += 4; // SaltSize must be 0x10
  15958. o.Salt = blob.slice(blob.l, blob.l+16); blob.l += 16;
  15959. o.Verifier = blob.slice(blob.l, blob.l+16); blob.l += 16;
  15960. /*var sz = */blob.read_shift(4);
  15961. o.VerifierHash = blob.slice(blob.l, tgt); blob.l = tgt;
  15962. return o;
  15963. }
  15964. /* [MS-OFFCRYPTO] 2.3.4.* EncryptionInfo Stream */
  15965. function parse_EncryptionInfo(blob) {
  15966. var vers = parse_CRYPTOVersion(blob);
  15967. switch(vers.Minor) {
  15968. case 0x02: return [vers.Minor, parse_EncInfoStd(blob, vers)];
  15969. case 0x03: return [vers.Minor, parse_EncInfoExt(blob, vers)];
  15970. case 0x04: return [vers.Minor, parse_EncInfoAgl(blob, vers)];
  15971. }
  15972. throw new Error("ECMA-376 Encrypted file unrecognized Version: " + vers.Minor);
  15973. }
  15974. /* [MS-OFFCRYPTO] 2.3.4.5 EncryptionInfo Stream (Standard Encryption) */
  15975. function parse_EncInfoStd(blob) {
  15976. var flags = blob.read_shift(4);
  15977. if((flags & 0x3F) != 0x24) throw new Error("EncryptionInfo mismatch");
  15978. var sz = blob.read_shift(4);
  15979. //var tgt = blob.l + sz;
  15980. var hdr = parse_EncryptionHeader(blob, sz);
  15981. var verifier = parse_EncryptionVerifier(blob, blob.length - blob.l);
  15982. return { t:"Std", h:hdr, v:verifier };
  15983. }
  15984. /* [MS-OFFCRYPTO] 2.3.4.6 EncryptionInfo Stream (Extensible Encryption) */
  15985. function parse_EncInfoExt() { throw new Error("File is password-protected: ECMA-376 Extensible"); }
  15986. /* [MS-OFFCRYPTO] 2.3.4.10 EncryptionInfo Stream (Agile Encryption) */
  15987. function parse_EncInfoAgl(blob) {
  15988. var KeyData = ["saltSize","blockSize","keyBits","hashSize","cipherAlgorithm","cipherChaining","hashAlgorithm","saltValue"];
  15989. blob.l+=4;
  15990. var xml = blob.read_shift(blob.length - blob.l, 'utf8');
  15991. var o = {};
  15992. xml.replace(tagregex, function xml_agile(x) {
  15993. var y = parsexmltag(x);
  15994. switch(strip_ns(y[0])) {
  15995. case '<?xml': break;
  15996. case '<encryption': case '</encryption>': break;
  15997. case '<keyData': KeyData.forEach(function(k) { o[k] = y[k]; }); break;
  15998. case '<dataIntegrity': o.encryptedHmacKey = y.encryptedHmacKey; o.encryptedHmacValue = y.encryptedHmacValue; break;
  15999. case '<keyEncryptors>': case '<keyEncryptors': o.encs = []; break;
  16000. case '</keyEncryptors>': break;
  16001. case '<keyEncryptor': o.uri = y.uri; break;
  16002. case '</keyEncryptor>': break;
  16003. case '<encryptedKey': o.encs.push(y); break;
  16004. default: throw y[0];
  16005. }
  16006. });
  16007. return o;
  16008. }
  16009. /* [MS-OFFCRYPTO] 2.3.5.1 RC4 CryptoAPI Encryption Header */
  16010. function parse_RC4CryptoHeader(blob, length) {
  16011. var o = {};
  16012. var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4); length -= 4;
  16013. if(vers.Minor != 2) throw new Error('unrecognized minor version code: ' + vers.Minor);
  16014. if(vers.Major > 4 || vers.Major < 2) throw new Error('unrecognized major version code: ' + vers.Major);
  16015. o.Flags = blob.read_shift(4); length -= 4;
  16016. var sz = blob.read_shift(4); length -= 4;
  16017. o.EncryptionHeader = parse_EncryptionHeader(blob, sz); length -= sz;
  16018. o.EncryptionVerifier = parse_EncryptionVerifier(blob, length);
  16019. return o;
  16020. }
  16021. /* [MS-OFFCRYPTO] 2.3.6.1 RC4 Encryption Header */
  16022. function parse_RC4Header(blob) {
  16023. var o = {};
  16024. var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4);
  16025. if(vers.Major != 1 || vers.Minor != 1) throw 'unrecognized version code ' + vers.Major + ' : ' + vers.Minor;
  16026. o.Salt = blob.read_shift(16);
  16027. o.EncryptedVerifier = blob.read_shift(16);
  16028. o.EncryptedVerifierHash = blob.read_shift(16);
  16029. return o;
  16030. }
  16031. /* [MS-OFFCRYPTO] 2.3.7.1 Binary Document Password Verifier Derivation */
  16032. function crypto_CreatePasswordVerifier_Method1(Password) {
  16033. var Verifier = 0x0000, PasswordArray;
  16034. var PasswordDecoded = _JS2ANSI(Password);
  16035. var len = PasswordDecoded.length + 1, i, PasswordByte;
  16036. var Intermediate1, Intermediate2, Intermediate3;
  16037. PasswordArray = new_raw_buf(len);
  16038. PasswordArray[0] = PasswordDecoded.length;
  16039. for(i = 1; i != len; ++i) PasswordArray[i] = PasswordDecoded[i-1];
  16040. for(i = len-1; i >= 0; --i) {
  16041. PasswordByte = PasswordArray[i];
  16042. Intermediate1 = ((Verifier & 0x4000) === 0x0000) ? 0 : 1;
  16043. Intermediate2 = (Verifier << 1) & 0x7FFF;
  16044. Intermediate3 = Intermediate1 | Intermediate2;
  16045. Verifier = Intermediate3 ^ PasswordByte;
  16046. }
  16047. return Verifier ^ 0xCE4B;
  16048. }
  16049. /* [MS-OFFCRYPTO] 2.3.7.2 Binary Document XOR Array Initialization */
  16050. var crypto_CreateXorArray_Method1 = (function() {
  16051. var PadArray = [0xBB, 0xFF, 0xFF, 0xBA, 0xFF, 0xFF, 0xB9, 0x80, 0x00, 0xBE, 0x0F, 0x00, 0xBF, 0x0F, 0x00];
  16052. var InitialCode = [0xE1F0, 0x1D0F, 0xCC9C, 0x84C0, 0x110C, 0x0E10, 0xF1CE, 0x313E, 0x1872, 0xE139, 0xD40F, 0x84F9, 0x280C, 0xA96A, 0x4EC3];
  16053. var XorMatrix = [0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09, 0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF, 0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0, 0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40, 0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5, 0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A, 0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9, 0x47D3, 0x8FA6, 0x0F6D, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0, 0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC, 0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10, 0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168, 0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C, 0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD, 0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC, 0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4];
  16054. var Ror = function(Byte) { return ((Byte/2) | (Byte*128)) & 0xFF; };
  16055. var XorRor = function(byte1, byte2) { return Ror(byte1 ^ byte2); };
  16056. var CreateXorKey_Method1 = function(Password) {
  16057. var XorKey = InitialCode[Password.length - 1];
  16058. var CurrentElement = 0x68;
  16059. for(var i = Password.length-1; i >= 0; --i) {
  16060. var Char = Password[i];
  16061. for(var j = 0; j != 7; ++j) {
  16062. if(Char & 0x40) XorKey ^= XorMatrix[CurrentElement];
  16063. Char *= 2; --CurrentElement;
  16064. }
  16065. }
  16066. return XorKey;
  16067. };
  16068. return function(password) {
  16069. var Password = _JS2ANSI(password);
  16070. var XorKey = CreateXorKey_Method1(Password);
  16071. var Index = Password.length;
  16072. var ObfuscationArray = new_raw_buf(16);
  16073. for(var i = 0; i != 16; ++i) ObfuscationArray[i] = 0x00;
  16074. var Temp, PasswordLastChar, PadIndex;
  16075. if((Index & 1) === 1) {
  16076. Temp = XorKey >> 8;
  16077. ObfuscationArray[Index] = XorRor(PadArray[0], Temp);
  16078. --Index;
  16079. Temp = XorKey & 0xFF;
  16080. PasswordLastChar = Password[Password.length - 1];
  16081. ObfuscationArray[Index] = XorRor(PasswordLastChar, Temp);
  16082. }
  16083. while(Index > 0) {
  16084. --Index;
  16085. Temp = XorKey >> 8;
  16086. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  16087. --Index;
  16088. Temp = XorKey & 0xFF;
  16089. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  16090. }
  16091. Index = 15;
  16092. PadIndex = 15 - Password.length;
  16093. while(PadIndex > 0) {
  16094. Temp = XorKey >> 8;
  16095. ObfuscationArray[Index] = XorRor(PadArray[PadIndex], Temp);
  16096. --Index;
  16097. --PadIndex;
  16098. Temp = XorKey & 0xFF;
  16099. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  16100. --Index;
  16101. --PadIndex;
  16102. }
  16103. return ObfuscationArray;
  16104. };
  16105. })();
  16106. /* [MS-OFFCRYPTO] 2.3.7.3 Binary Document XOR Data Transformation Method 1 */
  16107. var crypto_DecryptData_Method1 = function(password, Data, XorArrayIndex, XorArray, O) {
  16108. /* If XorArray is set, use it; if O is not set, make changes in-place */
  16109. if(!O) O = Data;
  16110. if(!XorArray) XorArray = crypto_CreateXorArray_Method1(password);
  16111. var Index, Value;
  16112. for(Index = 0; Index != Data.length; ++Index) {
  16113. Value = Data[Index];
  16114. Value ^= XorArray[XorArrayIndex];
  16115. Value = ((Value>>5) | (Value<<3)) & 0xFF;
  16116. O[Index] = Value;
  16117. ++XorArrayIndex;
  16118. }
  16119. return [O, XorArrayIndex, XorArray];
  16120. };
  16121. var crypto_MakeXorDecryptor = function(password) {
  16122. var XorArrayIndex = 0, XorArray = crypto_CreateXorArray_Method1(password);
  16123. return function(Data) {
  16124. var O = crypto_DecryptData_Method1("", Data, XorArrayIndex, XorArray);
  16125. XorArrayIndex = O[1];
  16126. return O[0];
  16127. };
  16128. };
  16129. /* 2.5.343 */
  16130. function parse_XORObfuscation(blob, length, opts, out) {
  16131. var o = ({ key: parseuint16(blob), verificationBytes: parseuint16(blob) });
  16132. if(opts.password) o.verifier = crypto_CreatePasswordVerifier_Method1(opts.password);
  16133. out.valid = o.verificationBytes === o.verifier;
  16134. if(out.valid) out.insitu = crypto_MakeXorDecryptor(opts.password);
  16135. return o;
  16136. }
  16137. /* 2.4.117 */
  16138. function parse_FilePassHeader(blob, length, oo) {
  16139. var o = oo || {}; o.Info = blob.read_shift(2); blob.l -= 2;
  16140. if(o.Info === 1) o.Data = parse_RC4Header(blob, length);
  16141. else o.Data = parse_RC4CryptoHeader(blob, length);
  16142. return o;
  16143. }
  16144. function parse_FilePass(blob, length, opts) {
  16145. var o = ({ Type: opts.biff >= 8 ? blob.read_shift(2) : 0 }); /* wEncryptionType */
  16146. if(o.Type) parse_FilePassHeader(blob, length-2, o);
  16147. else parse_XORObfuscation(blob, opts.biff >= 8 ? length : length - 2, opts, o);
  16148. return o;
  16149. }
  16150. var RTF = (function() {
  16151. function rtf_to_sheet(d, opts) {
  16152. switch(opts.type) {
  16153. case 'base64': return rtf_to_sheet_str(Base64.decode(d), opts);
  16154. case 'binary': return rtf_to_sheet_str(d, opts);
  16155. case 'buffer': return rtf_to_sheet_str(d.toString('binary'), opts);
  16156. case 'array': return rtf_to_sheet_str(cc2str(d), opts);
  16157. }
  16158. throw new Error("Unrecognized type " + opts.type);
  16159. }
  16160. function rtf_to_sheet_str(str, opts) {
  16161. var o = opts || {};
  16162. var ws = o.dense ? ([]) : ({});
  16163. var range = ({s: {c:0, r:0}, e: {c:0, r:0}});
  16164. // TODO: parse
  16165. if(!str.match(/\\trowd/)) throw new Error("RTF missing table");
  16166. ws['!ref'] = encode_range(range);
  16167. return ws;
  16168. }
  16169. function rtf_to_workbook(d, opts) { return sheet_to_workbook(rtf_to_sheet(d, opts), opts); }
  16170. /* TODO: this is a stub */
  16171. function sheet_to_rtf(ws) {
  16172. var o = ["{\\rtf1\\ansi"];
  16173. var r = safe_decode_range(ws['!ref']), cell;
  16174. var dense = Array.isArray(ws);
  16175. for(var R = r.s.r; R <= r.e.r; ++R) {
  16176. o.push("\\trowd\\trautofit1");
  16177. for(var C = r.s.c; C <= r.e.c; ++C) o.push("\\cellx" + (C+1));
  16178. o.push("\\pard\\intbl");
  16179. for(C = r.s.c; C <= r.e.c; ++C) {
  16180. var coord = encode_cell({r:R,c:C});
  16181. cell = dense ? (ws[R]||[])[C]: ws[coord];
  16182. if(!cell || cell.v == null && (!cell.f || cell.F)) continue;
  16183. o.push(" " + (cell.w || (format_cell(cell), cell.w)));
  16184. o.push("\\cell");
  16185. }
  16186. o.push("\\pard\\intbl\\row");
  16187. }
  16188. return o.join("") + "}";
  16189. }
  16190. return {
  16191. to_workbook: rtf_to_workbook,
  16192. to_sheet: rtf_to_sheet,
  16193. from_sheet: sheet_to_rtf
  16194. };
  16195. })();
  16196. function hex2RGB(h) {
  16197. var o = h.slice(h[0]==="#"?1:0).slice(0,6);
  16198. return [parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];
  16199. }
  16200. function rgb2Hex(rgb) {
  16201. for(var i=0,o=1; i!=3; ++i) o = o*256 + (rgb[i]>255?255:rgb[i]<0?0:rgb[i]);
  16202. return o.toString(16).toUpperCase().slice(1);
  16203. }
  16204. function rgb2HSL(rgb) {
  16205. var R = rgb[0]/255, G = rgb[1]/255, B=rgb[2]/255;
  16206. var M = Math.max(R, G, B), m = Math.min(R, G, B), C = M - m;
  16207. if(C === 0) return [0, 0, R];
  16208. var H6 = 0, S = 0, L2 = (M + m);
  16209. S = C / (L2 > 1 ? 2 - L2 : L2);
  16210. switch(M){
  16211. case R: H6 = ((G - B) / C + 6)%6; break;
  16212. case G: H6 = ((B - R) / C + 2); break;
  16213. case B: H6 = ((R - G) / C + 4); break;
  16214. }
  16215. return [H6 / 6, S, L2 / 2];
  16216. }
  16217. function hsl2RGB(hsl){
  16218. var H = hsl[0], S = hsl[1], L = hsl[2];
  16219. var C = S * 2 * (L < 0.5 ? L : 1 - L), m = L - C/2;
  16220. var rgb = [m,m,m], h6 = 6*H;
  16221. var X;
  16222. if(S !== 0) switch(h6|0) {
  16223. case 0: case 6: X = C * h6; rgb[0] += C; rgb[1] += X; break;
  16224. case 1: X = C * (2 - h6); rgb[0] += X; rgb[1] += C; break;
  16225. case 2: X = C * (h6 - 2); rgb[1] += C; rgb[2] += X; break;
  16226. case 3: X = C * (4 - h6); rgb[1] += X; rgb[2] += C; break;
  16227. case 4: X = C * (h6 - 4); rgb[2] += C; rgb[0] += X; break;
  16228. case 5: X = C * (6 - h6); rgb[2] += X; rgb[0] += C; break;
  16229. }
  16230. for(var i = 0; i != 3; ++i) rgb[i] = Math.round(rgb[i]*255);
  16231. return rgb;
  16232. }
  16233. /* 18.8.3 bgColor tint algorithm */
  16234. function rgb_tint(hex, tint) {
  16235. if(tint === 0) return hex;
  16236. var hsl = rgb2HSL(hex2RGB(hex));
  16237. if (tint < 0) hsl[2] = hsl[2] * (1 + tint);
  16238. else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint);
  16239. return rgb2Hex(hsl2RGB(hsl));
  16240. }
  16241. /* 18.3.1.13 width calculations */
  16242. /* [MS-OI29500] 2.1.595 Column Width & Formatting */
  16243. var DEF_MDW = 6, MAX_MDW = 15, MIN_MDW = 1, MDW = DEF_MDW;
  16244. function width2px(width) { return Math.floor(( width + (Math.round(128/MDW))/256 )* MDW ); }
  16245. function px2char(px) { return (Math.floor((px - 5)/MDW * 100 + 0.5))/100; }
  16246. function char2width(chr) { return (Math.round((chr * MDW + 5)/MDW*256))/256; }
  16247. //function px2char_(px) { return (((px - 5)/MDW * 100 + 0.5))/100; }
  16248. //function char2width_(chr) { return (((chr * MDW + 5)/MDW*256))/256; }
  16249. function cycle_width(collw) { return char2width(px2char(width2px(collw))); }
  16250. /* XLSX/XLSB/XLS specify width in units of MDW */
  16251. function find_mdw_colw(collw) {
  16252. var delta = Math.abs(collw - cycle_width(collw)), _MDW = MDW;
  16253. if(delta > 0.005) for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) if(Math.abs(collw - cycle_width(collw)) <= delta) { delta = Math.abs(collw - cycle_width(collw)); _MDW = MDW; }
  16254. MDW = _MDW;
  16255. }
  16256. /* XLML specifies width in terms of pixels */
  16257. /*function find_mdw_wpx(wpx) {
  16258. var delta = Infinity, guess = 0, _MDW = MIN_MDW;
  16259. for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) {
  16260. guess = char2width_(px2char_(wpx))*256;
  16261. guess = (guess) % 1;
  16262. if(guess > 0.5) guess--;
  16263. if(Math.abs(guess) < delta) { delta = Math.abs(guess); _MDW = MDW; }
  16264. }
  16265. MDW = _MDW;
  16266. }*/
  16267. function process_col(coll) {
  16268. if(coll.width) {
  16269. coll.wpx = width2px(coll.width);
  16270. coll.wch = px2char(coll.wpx);
  16271. coll.MDW = MDW;
  16272. } else if(coll.wpx) {
  16273. coll.wch = px2char(coll.wpx);
  16274. coll.width = char2width(coll.wch);
  16275. coll.MDW = MDW;
  16276. } else if(typeof coll.wch == 'number') {
  16277. coll.width = char2width(coll.wch);
  16278. coll.wpx = width2px(coll.width);
  16279. coll.MDW = MDW;
  16280. }
  16281. if(coll.customWidth) delete coll.customWidth;
  16282. }
  16283. var DEF_PPI = 96, PPI = DEF_PPI;
  16284. function px2pt(px) { return px * 96 / PPI; }
  16285. function pt2px(pt) { return pt * PPI / 96; }
  16286. /* [MS-EXSPXML3] 2.4.54 ST_enmPattern */
  16287. var XLMLPatternTypeMap = {
  16288. "None": "none",
  16289. "Solid": "solid",
  16290. "Gray50": "mediumGray",
  16291. "Gray75": "darkGray",
  16292. "Gray25": "lightGray",
  16293. "HorzStripe": "darkHorizontal",
  16294. "VertStripe": "darkVertical",
  16295. "ReverseDiagStripe": "darkDown",
  16296. "DiagStripe": "darkUp",
  16297. "DiagCross": "darkGrid",
  16298. "ThickDiagCross": "darkTrellis",
  16299. "ThinHorzStripe": "lightHorizontal",
  16300. "ThinVertStripe": "lightVertical",
  16301. "ThinReverseDiagStripe": "lightDown",
  16302. "ThinHorzCross": "lightGrid"
  16303. };
  16304. /* 18.8.5 borders CT_Borders */
  16305. function parse_borders(t, styles, themes, opts) {
  16306. styles.Borders = [];
  16307. var border = {};
  16308. var pass = false;
  16309. (t[0].match(tagregex)||[]).forEach(function(x) {
  16310. var y = parsexmltag(x);
  16311. switch(strip_ns(y[0])) {
  16312. case '<borders': case '<borders>': case '</borders>': break;
  16313. /* 18.8.4 border CT_Border */
  16314. case '<border': case '<border>': case '<border/>':
  16315. border = {};
  16316. if(y.diagonalUp) border.diagonalUp = parsexmlbool(y.diagonalUp);
  16317. if(y.diagonalDown) border.diagonalDown = parsexmlbool(y.diagonalDown);
  16318. styles.Borders.push(border);
  16319. break;
  16320. case '</border>': break;
  16321. /* note: not in spec, appears to be CT_BorderPr */
  16322. case '<left/>': break;
  16323. case '<left': case '<left>': break;
  16324. case '</left>': break;
  16325. /* note: not in spec, appears to be CT_BorderPr */
  16326. case '<right/>': break;
  16327. case '<right': case '<right>': break;
  16328. case '</right>': break;
  16329. /* 18.8.43 top CT_BorderPr */
  16330. case '<top/>': break;
  16331. case '<top': case '<top>': break;
  16332. case '</top>': break;
  16333. /* 18.8.6 bottom CT_BorderPr */
  16334. case '<bottom/>': break;
  16335. case '<bottom': case '<bottom>': break;
  16336. case '</bottom>': break;
  16337. /* 18.8.13 diagonal CT_BorderPr */
  16338. case '<diagonal': case '<diagonal>': case '<diagonal/>': break;
  16339. case '</diagonal>': break;
  16340. /* 18.8.25 horizontal CT_BorderPr */
  16341. case '<horizontal': case '<horizontal>': case '<horizontal/>': break;
  16342. case '</horizontal>': break;
  16343. /* 18.8.44 vertical CT_BorderPr */
  16344. case '<vertical': case '<vertical>': case '<vertical/>': break;
  16345. case '</vertical>': break;
  16346. /* 18.8.37 start CT_BorderPr */
  16347. case '<start': case '<start>': case '<start/>': break;
  16348. case '</start>': break;
  16349. /* 18.8.16 end CT_BorderPr */
  16350. case '<end': case '<end>': case '<end/>': break;
  16351. case '</end>': break;
  16352. /* 18.8.? color CT_Color */
  16353. case '<color': case '<color>':
  16354. break;
  16355. case '<color/>': case '</color>': break;
  16356. /* 18.2.10 extLst CT_ExtensionList ? */
  16357. case '<extLst': case '<extLst>': case '</extLst>': break;
  16358. case '<ext': pass = true; break;
  16359. case '</ext>': pass = false; break;
  16360. default: if(opts && opts.WTF) {
  16361. if(!pass) throw new Error('unrecognized ' + y[0] + ' in borders');
  16362. }
  16363. }
  16364. });
  16365. }
  16366. /* 18.8.21 fills CT_Fills */
  16367. function parse_fills(t, styles, themes, opts) {
  16368. styles.Fills = [];
  16369. var fill = {};
  16370. var pass = false;
  16371. (t[0].match(tagregex)||[]).forEach(function(x) {
  16372. var y = parsexmltag(x);
  16373. switch(strip_ns(y[0])) {
  16374. case '<fills': case '<fills>': case '</fills>': break;
  16375. /* 18.8.20 fill CT_Fill */
  16376. case '<fill>': case '<fill': case '<fill/>':
  16377. fill = {}; styles.Fills.push(fill); break;
  16378. case '</fill>': break;
  16379. /* 18.8.24 gradientFill CT_GradientFill */
  16380. case '<gradientFill>': break;
  16381. case '<gradientFill':
  16382. case '</gradientFill>': styles.Fills.push(fill); fill = {}; break;
  16383. /* 18.8.32 patternFill CT_PatternFill */
  16384. case '<patternFill': case '<patternFill>':
  16385. if(y.patternType) fill.patternType = y.patternType;
  16386. break;
  16387. case '<patternFill/>': case '</patternFill>': break;
  16388. /* 18.8.3 bgColor CT_Color */
  16389. case '<bgColor':
  16390. if(!fill.bgColor) fill.bgColor = {};
  16391. if(y.indexed) fill.bgColor.indexed = parseInt(y.indexed, 10);
  16392. if(y.theme) fill.bgColor.theme = parseInt(y.theme, 10);
  16393. if(y.tint) fill.bgColor.tint = parseFloat(y.tint);
  16394. /* Excel uses ARGB strings */
  16395. if(y.rgb) fill.bgColor.rgb = y.rgb.slice(-6);
  16396. break;
  16397. case '<bgColor/>': case '</bgColor>': break;
  16398. /* 18.8.19 fgColor CT_Color */
  16399. case '<fgColor':
  16400. if(!fill.fgColor) fill.fgColor = {};
  16401. if(y.theme) fill.fgColor.theme = parseInt(y.theme, 10);
  16402. if(y.tint) fill.fgColor.tint = parseFloat(y.tint);
  16403. /* Excel uses ARGB strings */
  16404. if(y.rgb != null) fill.fgColor.rgb = y.rgb.slice(-6);
  16405. break;
  16406. case '<fgColor/>': case '</fgColor>': break;
  16407. /* 18.8.38 stop CT_GradientStop */
  16408. case '<stop': case '<stop/>': break;
  16409. case '</stop>': break;
  16410. /* 18.8.? color CT_Color */
  16411. case '<color': case '<color/>': break;
  16412. case '</color>': break;
  16413. /* 18.2.10 extLst CT_ExtensionList ? */
  16414. case '<extLst': case '<extLst>': case '</extLst>': break;
  16415. case '<ext': pass = true; break;
  16416. case '</ext>': pass = false; break;
  16417. default: if(opts && opts.WTF) {
  16418. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fills');
  16419. }
  16420. }
  16421. });
  16422. }
  16423. /* 18.8.23 fonts CT_Fonts */
  16424. function parse_fonts(t, styles, themes, opts) {
  16425. styles.Fonts = [];
  16426. var font = {};
  16427. var pass = false;
  16428. (t[0].match(tagregex)||[]).forEach(function(x) {
  16429. var y = parsexmltag(x);
  16430. switch(strip_ns(y[0])) {
  16431. case '<fonts': case '<fonts>': case '</fonts>': break;
  16432. /* 18.8.22 font CT_Font */
  16433. case '<font': case '<font>': break;
  16434. case '</font>': case '<font/>':
  16435. styles.Fonts.push(font);
  16436. font = {};
  16437. break;
  16438. /* 18.8.29 name CT_FontName */
  16439. case '<name': if(y.val) font.name = utf8read(y.val); break;
  16440. case '<name/>': case '</name>': break;
  16441. /* 18.8.2 b CT_BooleanProperty */
  16442. case '<b': font.bold = y.val ? parsexmlbool(y.val) : 1; break;
  16443. case '<b/>': font.bold = 1; break;
  16444. /* 18.8.26 i CT_BooleanProperty */
  16445. case '<i': font.italic = y.val ? parsexmlbool(y.val) : 1; break;
  16446. case '<i/>': font.italic = 1; break;
  16447. /* 18.4.13 u CT_UnderlineProperty */
  16448. case '<u':
  16449. switch(y.val) {
  16450. case "none": font.underline = 0x00; break;
  16451. case "single": font.underline = 0x01; break;
  16452. case "double": font.underline = 0x02; break;
  16453. case "singleAccounting": font.underline = 0x21; break;
  16454. case "doubleAccounting": font.underline = 0x22; break;
  16455. } break;
  16456. case '<u/>': font.underline = 1; break;
  16457. /* 18.4.10 strike CT_BooleanProperty */
  16458. case '<strike': font.strike = y.val ? parsexmlbool(y.val) : 1; break;
  16459. case '<strike/>': font.strike = 1; break;
  16460. /* 18.4.2 outline CT_BooleanProperty */
  16461. case '<outline': font.outline = y.val ? parsexmlbool(y.val) : 1; break;
  16462. case '<outline/>': font.outline = 1; break;
  16463. /* 18.8.36 shadow CT_BooleanProperty */
  16464. case '<shadow': font.shadow = y.val ? parsexmlbool(y.val) : 1; break;
  16465. case '<shadow/>': font.shadow = 1; break;
  16466. /* 18.8.12 condense CT_BooleanProperty */
  16467. case '<condense': font.condense = y.val ? parsexmlbool(y.val) : 1; break;
  16468. case '<condense/>': font.condense = 1; break;
  16469. /* 18.8.17 extend CT_BooleanProperty */
  16470. case '<extend': font.extend = y.val ? parsexmlbool(y.val) : 1; break;
  16471. case '<extend/>': font.extend = 1; break;
  16472. /* 18.4.11 sz CT_FontSize */
  16473. case '<sz': if(y.val) font.sz = +y.val; break;
  16474. case '<sz/>': case '</sz>': break;
  16475. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty */
  16476. case '<vertAlign': if(y.val) font.vertAlign = y.val; break;
  16477. case '<vertAlign/>': case '</vertAlign>': break;
  16478. /* 18.8.18 family CT_FontFamily */
  16479. case '<family': if(y.val) font.family = parseInt(y.val,10); break;
  16480. case '<family/>': case '</family>': break;
  16481. /* 18.8.35 scheme CT_FontScheme */
  16482. case '<scheme': if(y.val) font.scheme = y.val; break;
  16483. case '<scheme/>': case '</scheme>': break;
  16484. /* 18.4.1 charset CT_IntProperty */
  16485. case '<charset':
  16486. if(y.val == '1') break;
  16487. y.codepage = CS2CP[parseInt(y.val, 10)];
  16488. break;
  16489. /* 18.?.? color CT_Color */
  16490. case '<color':
  16491. if(!font.color) font.color = {};
  16492. if(y.auto) font.color.auto = parsexmlbool(y.auto);
  16493. if(y.rgb) font.color.rgb = y.rgb.slice(-6);
  16494. else if(y.indexed) {
  16495. font.color.index = parseInt(y.indexed, 10);
  16496. var icv = XLSIcv[font.color.index];
  16497. if(font.color.index == 81) icv = XLSIcv[1];
  16498. if(!icv) throw new Error(x);
  16499. font.color.rgb = icv[0].toString(16) + icv[1].toString(16) + icv[2].toString(16);
  16500. } else if(y.theme) {
  16501. font.color.theme = parseInt(y.theme, 10);
  16502. if(y.tint) font.color.tint = parseFloat(y.tint);
  16503. if(y.theme && themes.themeElements && themes.themeElements.clrScheme) {
  16504. font.color.rgb = rgb_tint(themes.themeElements.clrScheme[font.color.theme].rgb, font.color.tint || 0);
  16505. }
  16506. }
  16507. break;
  16508. case '<color/>': case '</color>': break;
  16509. /* note: sometimes mc:AlternateContent appears bare */
  16510. case '<AlternateContent': pass = true; break;
  16511. case '</AlternateContent>': pass = false; break;
  16512. /* 18.2.10 extLst CT_ExtensionList ? */
  16513. case '<extLst': case '<extLst>': case '</extLst>': break;
  16514. case '<ext': pass = true; break;
  16515. case '</ext>': pass = false; break;
  16516. default: if(opts && opts.WTF) {
  16517. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fonts');
  16518. }
  16519. }
  16520. });
  16521. }
  16522. /* 18.8.31 numFmts CT_NumFmts */
  16523. function parse_numFmts(t, styles, opts) {
  16524. styles.NumberFmt = [];
  16525. var k/*Array<number>*/ = (keys(SSF._table));
  16526. for(var i=0; i < k.length; ++i) styles.NumberFmt[k[i]] = SSF._table[k[i]];
  16527. var m = t[0].match(tagregex);
  16528. if(!m) return;
  16529. for(i=0; i < m.length; ++i) {
  16530. var y = parsexmltag(m[i]);
  16531. switch(strip_ns(y[0])) {
  16532. case '<numFmts': case '</numFmts>': case '<numFmts/>': case '<numFmts>': break;
  16533. case '<numFmt': {
  16534. var f=unescapexml(utf8read(y.formatCode)), j=parseInt(y.numFmtId,10);
  16535. styles.NumberFmt[j] = f;
  16536. if(j>0) {
  16537. if(j > 0x188) {
  16538. for(j = 0x188; j > 0x3c; --j) if(styles.NumberFmt[j] == null) break;
  16539. styles.NumberFmt[j] = f;
  16540. }
  16541. SSF.load(f,j);
  16542. }
  16543. } break;
  16544. case '</numFmt>': break;
  16545. default: if(opts.WTF) throw new Error('unrecognized ' + y[0] + ' in numFmts');
  16546. }
  16547. }
  16548. }
  16549. function write_numFmts(NF) {
  16550. var o = ["<numFmts>"];
  16551. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  16552. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) o[o.length] = (writextag('numFmt',null,{numFmtId:i,formatCode:escapexml(NF[i])}));
  16553. });
  16554. if(o.length === 1) return "";
  16555. o[o.length] = ("</numFmts>");
  16556. o[0] = writextag('numFmts', null, { count:o.length-2 }).replace("/>", ">");
  16557. return o.join("");
  16558. }
  16559. /* 18.8.10 cellXfs CT_CellXfs */
  16560. var cellXF_uint = [ "numFmtId", "fillId", "fontId", "borderId", "xfId" ];
  16561. var cellXF_bool = [ "applyAlignment", "applyBorder", "applyFill", "applyFont", "applyNumberFormat", "applyProtection", "pivotButton", "quotePrefix" ];
  16562. function parse_cellXfs(t, styles, opts) {
  16563. styles.CellXf = [];
  16564. var xf;
  16565. var pass = false;
  16566. (t[0].match(tagregex)||[]).forEach(function(x) {
  16567. var y = parsexmltag(x), i = 0;
  16568. switch(strip_ns(y[0])) {
  16569. case '<cellXfs': case '<cellXfs>': case '<cellXfs/>': case '</cellXfs>': break;
  16570. /* 18.8.45 xf CT_Xf */
  16571. case '<xf': case '<xf/>':
  16572. xf = y;
  16573. delete xf[0];
  16574. for(i = 0; i < cellXF_uint.length; ++i) if(xf[cellXF_uint[i]])
  16575. xf[cellXF_uint[i]] = parseInt(xf[cellXF_uint[i]], 10);
  16576. for(i = 0; i < cellXF_bool.length; ++i) if(xf[cellXF_bool[i]])
  16577. xf[cellXF_bool[i]] = parsexmlbool(xf[cellXF_bool[i]]);
  16578. if(xf.numFmtId > 0x188) {
  16579. for(i = 0x188; i > 0x3c; --i) if(styles.NumberFmt[xf.numFmtId] == styles.NumberFmt[i]) { xf.numFmtId = i; break; }
  16580. }
  16581. styles.CellXf.push(xf); break;
  16582. case '</xf>': break;
  16583. /* 18.8.1 alignment CT_CellAlignment */
  16584. case '<alignment': case '<alignment/>':
  16585. var alignment = {};
  16586. if(y.vertical) alignment.vertical = y.vertical;
  16587. if(y.horizontal) alignment.horizontal = y.horizontal;
  16588. if(y.textRotation != null) alignment.textRotation = y.textRotation;
  16589. if(y.indent) alignment.indent = y.indent;
  16590. if(y.wrapText) alignment.wrapText = parsexmlbool(y.wrapText);
  16591. xf.alignment = alignment;
  16592. break;
  16593. case '</alignment>': break;
  16594. /* 18.8.33 protection CT_CellProtection */
  16595. case '<protection':
  16596. break;
  16597. case '</protection>': case '<protection/>': break;
  16598. /* note: sometimes mc:AlternateContent appears bare */
  16599. case '<AlternateContent': pass = true; break;
  16600. case '</AlternateContent>': pass = false; break;
  16601. /* 18.2.10 extLst CT_ExtensionList ? */
  16602. case '<extLst': case '<extLst>': case '</extLst>': break;
  16603. case '<ext': pass = true; break;
  16604. case '</ext>': pass = false; break;
  16605. default: if(opts && opts.WTF) {
  16606. if(!pass) throw new Error('unrecognized ' + y[0] + ' in cellXfs');
  16607. }
  16608. }
  16609. });
  16610. }
  16611. function write_cellXfs(cellXfs) {
  16612. var o = [];
  16613. o[o.length] = (writextag('cellXfs',null));
  16614. cellXfs.forEach(function(c) {
  16615. o[o.length] = (writextag('xf', null, c));
  16616. });
  16617. o[o.length] = ("</cellXfs>");
  16618. if(o.length === 2) return "";
  16619. o[0] = writextag('cellXfs',null, {count:o.length-2}).replace("/>",">");
  16620. return o.join("");
  16621. }
  16622. /* 18.8 Styles CT_Stylesheet*/
  16623. var parse_sty_xml= (function make_pstyx() {
  16624. var numFmtRegex = /<(?:\w+:)?numFmts([^>]*)>[\S\s]*?<\/(?:\w+:)?numFmts>/;
  16625. var cellXfRegex = /<(?:\w+:)?cellXfs([^>]*)>[\S\s]*?<\/(?:\w+:)?cellXfs>/;
  16626. var fillsRegex = /<(?:\w+:)?fills([^>]*)>[\S\s]*?<\/(?:\w+:)?fills>/;
  16627. var fontsRegex = /<(?:\w+:)?fonts([^>]*)>[\S\s]*?<\/(?:\w+:)?fonts>/;
  16628. var bordersRegex = /<(?:\w+:)?borders([^>]*)>[\S\s]*?<\/(?:\w+:)?borders>/;
  16629. return function parse_sty_xml(data, themes, opts) {
  16630. var styles = {};
  16631. if(!data) return styles;
  16632. data = data.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  16633. /* 18.8.39 styleSheet CT_Stylesheet */
  16634. var t;
  16635. /* 18.8.31 numFmts CT_NumFmts ? */
  16636. if((t=data.match(numFmtRegex))) parse_numFmts(t, styles, opts);
  16637. /* 18.8.23 fonts CT_Fonts ? */
  16638. if((t=data.match(fontsRegex))) parse_fonts(t, styles, themes, opts);
  16639. /* 18.8.21 fills CT_Fills ? */
  16640. if((t=data.match(fillsRegex))) parse_fills(t, styles, themes, opts);
  16641. /* 18.8.5 borders CT_Borders ? */
  16642. if((t=data.match(bordersRegex))) parse_borders(t, styles, themes, opts);
  16643. /* 18.8.9 cellStyleXfs CT_CellStyleXfs ? */
  16644. /* 18.8.8 cellStyles CT_CellStyles ? */
  16645. /* 18.8.10 cellXfs CT_CellXfs ? */
  16646. if((t=data.match(cellXfRegex))) parse_cellXfs(t, styles, opts);
  16647. /* 18.8.15 dxfs CT_Dxfs ? */
  16648. /* 18.8.42 tableStyles CT_TableStyles ? */
  16649. /* 18.8.11 colors CT_Colors ? */
  16650. /* 18.2.10 extLst CT_ExtensionList ? */
  16651. return styles;
  16652. };
  16653. })();
  16654. var STYLES_XML_ROOT = writextag('styleSheet', null, {
  16655. 'xmlns': XMLNS.main[0],
  16656. 'xmlns:vt': XMLNS.vt
  16657. });
  16658. RELS.STY = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
  16659. function write_sty_xml(wb, opts) {
  16660. var o = [XML_HEADER, STYLES_XML_ROOT], w;
  16661. if(wb.SSF && (w = write_numFmts(wb.SSF)) != null) o[o.length] = w;
  16662. o[o.length] = ('<fonts count="1"><font><sz val="12"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts>');
  16663. o[o.length] = ('<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>');
  16664. o[o.length] = ('<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>');
  16665. o[o.length] = ('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>');
  16666. if((w = write_cellXfs(opts.cellXfs))) o[o.length] = (w);
  16667. o[o.length] = ('<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>');
  16668. o[o.length] = ('<dxfs count="0"/>');
  16669. o[o.length] = ('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4"/>');
  16670. if(o.length>2){ o[o.length] = ('</styleSheet>'); o[1]=o[1].replace("/>",">"); }
  16671. return o.join("");
  16672. }
  16673. /* [MS-XLSB] 2.4.657 BrtFmt */
  16674. function parse_BrtFmt(data, length) {
  16675. var numFmtId = data.read_shift(2);
  16676. var stFmtCode = parse_XLWideString(data,length-2);
  16677. return [numFmtId, stFmtCode];
  16678. }
  16679. function write_BrtFmt(i, f, o) {
  16680. if(!o) o = new_buf(6 + 4 * f.length);
  16681. o.write_shift(2, i);
  16682. write_XLWideString(f, o);
  16683. var out = (o.length > o.l) ? o.slice(0, o.l) : o;
  16684. if(o.l == null) o.l = o.length;
  16685. return out;
  16686. }
  16687. /* [MS-XLSB] 2.4.659 BrtFont TODO */
  16688. function parse_BrtFont(data, length, opts) {
  16689. var out = ({});
  16690. out.sz = data.read_shift(2) / 20;
  16691. var grbit = parse_FontFlags(data, 2, opts);
  16692. if(grbit.fItalic) out.italic = 1;
  16693. if(grbit.fCondense) out.condense = 1;
  16694. if(grbit.fExtend) out.extend = 1;
  16695. if(grbit.fShadow) out.shadow = 1;
  16696. if(grbit.fOutline) out.outline = 1;
  16697. if(grbit.fStrikeout) out.strike = 1;
  16698. var bls = data.read_shift(2);
  16699. if(bls === 0x02BC) out.bold = 1;
  16700. switch(data.read_shift(2)) {
  16701. /* case 0: out.vertAlign = "baseline"; break; */
  16702. case 1: out.vertAlign = "superscript"; break;
  16703. case 2: out.vertAlign = "subscript"; break;
  16704. }
  16705. var underline = data.read_shift(1);
  16706. if(underline != 0) out.underline = underline;
  16707. var family = data.read_shift(1);
  16708. if(family > 0) out.family = family;
  16709. var bCharSet = data.read_shift(1);
  16710. if(bCharSet > 0) out.charset = bCharSet;
  16711. data.l++;
  16712. out.color = parse_BrtColor(data, 8);
  16713. switch(data.read_shift(1)) {
  16714. /* case 0: out.scheme = "none": break; */
  16715. case 1: out.scheme = "major"; break;
  16716. case 2: out.scheme = "minor"; break;
  16717. }
  16718. out.name = parse_XLWideString(data, length - 21);
  16719. return out;
  16720. }
  16721. function write_BrtFont(font, o) {
  16722. if(!o) o = new_buf(25+4*32);
  16723. o.write_shift(2, font.sz * 20);
  16724. write_FontFlags(font, o);
  16725. o.write_shift(2, font.bold ? 0x02BC : 0x0190);
  16726. var sss = 0;
  16727. if(font.vertAlign == "superscript") sss = 1;
  16728. else if(font.vertAlign == "subscript") sss = 2;
  16729. o.write_shift(2, sss);
  16730. o.write_shift(1, font.underline || 0);
  16731. o.write_shift(1, font.family || 0);
  16732. o.write_shift(1, font.charset || 0);
  16733. o.write_shift(1, 0);
  16734. write_BrtColor(font.color, o);
  16735. var scheme = 0;
  16736. if(font.scheme == "major") scheme = 1;
  16737. if(font.scheme == "minor") scheme = 2;
  16738. o.write_shift(1, scheme);
  16739. write_XLWideString(font.name, o);
  16740. return o.length > o.l ? o.slice(0, o.l) : o;
  16741. }
  16742. /* [MS-XLSB] 2.4.650 BrtFill */
  16743. var XLSBFillPTNames = [
  16744. "none",
  16745. "solid",
  16746. "mediumGray",
  16747. "darkGray",
  16748. "lightGray",
  16749. "darkHorizontal",
  16750. "darkVertical",
  16751. "darkDown",
  16752. "darkUp",
  16753. "darkGrid",
  16754. "darkTrellis",
  16755. "lightHorizontal",
  16756. "lightVertical",
  16757. "lightDown",
  16758. "lightUp",
  16759. "lightGrid",
  16760. "lightTrellis",
  16761. "gray125",
  16762. "gray0625"
  16763. ];
  16764. var rev_XLSBFillPTNames = (evert(XLSBFillPTNames));
  16765. /* TODO: gradient fill representation */
  16766. var parse_BrtFill = parsenoop;
  16767. function write_BrtFill(fill, o) {
  16768. if(!o) o = new_buf(4*3 + 8*7 + 16*1);
  16769. var fls = rev_XLSBFillPTNames[fill.patternType];
  16770. if(fls == null) fls = 0x28;
  16771. o.write_shift(4, fls);
  16772. var j = 0;
  16773. if(fls != 0x28) {
  16774. /* TODO: custom FG Color */
  16775. write_BrtColor({auto:1}, o);
  16776. /* TODO: custom BG Color */
  16777. write_BrtColor({auto:1}, o);
  16778. for(; j < 12; ++j) o.write_shift(4, 0);
  16779. } else {
  16780. for(; j < 4; ++j) o.write_shift(4, 0);
  16781. for(; j < 12; ++j) o.write_shift(4, 0); /* TODO */
  16782. /* iGradientType */
  16783. /* xnumDegree */
  16784. /* xnumFillToLeft */
  16785. /* xnumFillToRight */
  16786. /* xnumFillToTop */
  16787. /* xnumFillToBottom */
  16788. /* cNumStop */
  16789. /* xfillGradientStop */
  16790. }
  16791. return o.length > o.l ? o.slice(0, o.l) : o;
  16792. }
  16793. /* [MS-XLSB] 2.4.824 BrtXF */
  16794. function parse_BrtXF(data, length) {
  16795. var tgt = data.l + length;
  16796. var ixfeParent = data.read_shift(2);
  16797. var ifmt = data.read_shift(2);
  16798. data.l = tgt;
  16799. return {ixfe:ixfeParent, numFmtId:ifmt };
  16800. }
  16801. function write_BrtXF(data, ixfeP, o) {
  16802. if(!o) o = new_buf(16);
  16803. o.write_shift(2, ixfeP||0);
  16804. o.write_shift(2, data.numFmtId||0);
  16805. o.write_shift(2, 0); /* iFont */
  16806. o.write_shift(2, 0); /* iFill */
  16807. o.write_shift(2, 0); /* ixBorder */
  16808. o.write_shift(1, 0); /* trot */
  16809. o.write_shift(1, 0); /* indent */
  16810. var flow = 0;
  16811. o.write_shift(1, flow); /* flags */
  16812. o.write_shift(1, 0); /* flags */
  16813. o.write_shift(1, 0); /* xfGrbitAtr */
  16814. o.write_shift(1, 0);
  16815. return o;
  16816. }
  16817. /* [MS-XLSB] 2.5.4 Blxf TODO */
  16818. function write_Blxf(data, o) {
  16819. if(!o) o = new_buf(10);
  16820. o.write_shift(1, 0); /* dg */
  16821. o.write_shift(1, 0);
  16822. o.write_shift(4, 0); /* color */
  16823. o.write_shift(4, 0); /* color */
  16824. return o;
  16825. }
  16826. /* [MS-XLSB] 2.4.302 BrtBorder TODO */
  16827. var parse_BrtBorder = parsenoop;
  16828. function write_BrtBorder(border, o) {
  16829. if(!o) o = new_buf(51);
  16830. o.write_shift(1, 0); /* diagonal */
  16831. write_Blxf(null, o); /* top */
  16832. write_Blxf(null, o); /* bottom */
  16833. write_Blxf(null, o); /* left */
  16834. write_Blxf(null, o); /* right */
  16835. write_Blxf(null, o); /* diag */
  16836. return o.length > o.l ? o.slice(0, o.l) : o;
  16837. }
  16838. /* [MS-XLSB] 2.4.763 BrtStyle TODO */
  16839. function write_BrtStyle(style, o) {
  16840. if(!o) o = new_buf(12+4*10);
  16841. o.write_shift(4, style.xfId);
  16842. o.write_shift(2, 1);
  16843. o.write_shift(1, +style.builtinId);
  16844. o.write_shift(1, 0); /* iLevel */
  16845. write_XLNullableWideString(style.name || "", o);
  16846. return o.length > o.l ? o.slice(0, o.l) : o;
  16847. }
  16848. /* [MS-XLSB] 2.4.272 BrtBeginTableStyles */
  16849. function write_BrtBeginTableStyles(cnt, defTableStyle, defPivotStyle) {
  16850. var o = new_buf(4+256*2*4);
  16851. o.write_shift(4, cnt);
  16852. write_XLNullableWideString(defTableStyle, o);
  16853. write_XLNullableWideString(defPivotStyle, o);
  16854. return o.length > o.l ? o.slice(0, o.l) : o;
  16855. }
  16856. /* [MS-XLSB] 2.1.7.50 Styles */
  16857. function parse_sty_bin(data, themes, opts) {
  16858. var styles = {};
  16859. styles.NumberFmt = ([]);
  16860. for(var y in SSF._table) styles.NumberFmt[y] = SSF._table[y];
  16861. styles.CellXf = [];
  16862. styles.Fonts = [];
  16863. var state = [];
  16864. var pass = false;
  16865. recordhopper(data, function hopper_sty(val, R_n, RT) {
  16866. switch(RT) {
  16867. case 0x002C: /* 'BrtFmt' */
  16868. styles.NumberFmt[val[0]] = val[1]; SSF.load(val[1], val[0]);
  16869. break;
  16870. case 0x002B: /* 'BrtFont' */
  16871. styles.Fonts.push(val);
  16872. if(val.color.theme != null && themes && themes.themeElements && themes.themeElements.clrScheme) {
  16873. val.color.rgb = rgb_tint(themes.themeElements.clrScheme[val.color.theme].rgb, val.color.tint || 0);
  16874. }
  16875. break;
  16876. case 0x0401: /* 'BrtKnownFonts' */ break;
  16877. case 0x002D: /* 'BrtFill' */
  16878. break;
  16879. case 0x002E: /* 'BrtBorder' */
  16880. break;
  16881. case 0x002F: /* 'BrtXF' */
  16882. if(state[state.length - 1] == "BrtBeginCellXFs") {
  16883. styles.CellXf.push(val);
  16884. }
  16885. break;
  16886. case 0x0030: /* 'BrtStyle' */
  16887. case 0x01FB: /* 'BrtDXF' */
  16888. case 0x023C: /* 'BrtMRUColor' */
  16889. case 0x01DB: /* 'BrtIndexedColor': */
  16890. break;
  16891. case 0x0493: /* 'BrtDXF14' */
  16892. case 0x0836: /* 'BrtDXF15' */
  16893. case 0x046A: /* 'BrtSlicerStyleElement' */
  16894. case 0x0200: /* 'BrtTableStyleElement' */
  16895. case 0x082F: /* 'BrtTimelineStyleElement' */
  16896. case 0x0C00: /* 'BrtUid' */
  16897. break;
  16898. case 0x0023: /* 'BrtFRTBegin' */
  16899. pass = true; break;
  16900. case 0x0024: /* 'BrtFRTEnd' */
  16901. pass = false; break;
  16902. case 0x0025: /* 'BrtACBegin' */
  16903. state.push(R_n); pass = true; break;
  16904. case 0x0026: /* 'BrtACEnd' */
  16905. state.pop(); pass = false; break;
  16906. default:
  16907. if((R_n||"").indexOf("Begin") > 0) state.push(R_n);
  16908. else if((R_n||"").indexOf("End") > 0) state.pop();
  16909. else if(!pass || (opts.WTF && state[state.length-1] != "BrtACBegin")) throw new Error("Unexpected record " + RT + " " + R_n);
  16910. }
  16911. });
  16912. return styles;
  16913. }
  16914. function write_FMTS_bin(ba, NF) {
  16915. if(!NF) return;
  16916. var cnt = 0;
  16917. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  16918. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) ++cnt;
  16919. });
  16920. if(cnt == 0) return;
  16921. write_record(ba, "BrtBeginFmts", write_UInt32LE(cnt));
  16922. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  16923. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) write_record(ba, "BrtFmt", write_BrtFmt(i, NF[i]));
  16924. });
  16925. write_record(ba, "BrtEndFmts");
  16926. }
  16927. function write_FONTS_bin(ba) {
  16928. var cnt = 1;
  16929. if(cnt == 0) return;
  16930. write_record(ba, "BrtBeginFonts", write_UInt32LE(cnt));
  16931. write_record(ba, "BrtFont", write_BrtFont({
  16932. sz:12,
  16933. color: {theme:1},
  16934. name: "Calibri",
  16935. family: 2,
  16936. scheme: "minor"
  16937. }));
  16938. /* 1*65491BrtFont [ACFONTS] */
  16939. write_record(ba, "BrtEndFonts");
  16940. }
  16941. function write_FILLS_bin(ba) {
  16942. var cnt = 2;
  16943. if(cnt == 0) return;
  16944. write_record(ba, "BrtBeginFills", write_UInt32LE(cnt));
  16945. write_record(ba, "BrtFill", write_BrtFill({patternType:"none"}));
  16946. write_record(ba, "BrtFill", write_BrtFill({patternType:"gray125"}));
  16947. /* 1*65431BrtFill */
  16948. write_record(ba, "BrtEndFills");
  16949. }
  16950. function write_BORDERS_bin(ba) {
  16951. var cnt = 1;
  16952. if(cnt == 0) return;
  16953. write_record(ba, "BrtBeginBorders", write_UInt32LE(cnt));
  16954. write_record(ba, "BrtBorder", write_BrtBorder({}));
  16955. /* 1*65430BrtBorder */
  16956. write_record(ba, "BrtEndBorders");
  16957. }
  16958. function write_CELLSTYLEXFS_bin(ba) {
  16959. var cnt = 1;
  16960. write_record(ba, "BrtBeginCellStyleXFs", write_UInt32LE(cnt));
  16961. write_record(ba, "BrtXF", write_BrtXF({
  16962. numFmtId: 0,
  16963. fontId: 0,
  16964. fillId: 0,
  16965. borderId: 0
  16966. }, 0xFFFF));
  16967. /* 1*65430(BrtXF *FRT) */
  16968. write_record(ba, "BrtEndCellStyleXFs");
  16969. }
  16970. function write_CELLXFS_bin(ba, data) {
  16971. write_record(ba, "BrtBeginCellXFs", write_UInt32LE(data.length));
  16972. data.forEach(function(c) { write_record(ba, "BrtXF", write_BrtXF(c,0)); });
  16973. /* 1*65430(BrtXF *FRT) */
  16974. write_record(ba, "BrtEndCellXFs");
  16975. }
  16976. function write_STYLES_bin(ba) {
  16977. var cnt = 1;
  16978. write_record(ba, "BrtBeginStyles", write_UInt32LE(cnt));
  16979. write_record(ba, "BrtStyle", write_BrtStyle({
  16980. xfId:0,
  16981. builtinId:0,
  16982. name:"Normal"
  16983. }));
  16984. /* 1*65430(BrtStyle *FRT) */
  16985. write_record(ba, "BrtEndStyles");
  16986. }
  16987. function write_DXFS_bin(ba) {
  16988. var cnt = 0;
  16989. write_record(ba, "BrtBeginDXFs", write_UInt32LE(cnt));
  16990. /* *2147483647(BrtDXF *FRT) */
  16991. write_record(ba, "BrtEndDXFs");
  16992. }
  16993. function write_TABLESTYLES_bin(ba) {
  16994. var cnt = 0;
  16995. write_record(ba, "BrtBeginTableStyles", write_BrtBeginTableStyles(cnt, "TableStyleMedium9", "PivotStyleMedium4"));
  16996. /* *TABLESTYLE */
  16997. write_record(ba, "BrtEndTableStyles");
  16998. }
  16999. function write_COLORPALETTE_bin() {
  17000. return;
  17001. /* BrtBeginColorPalette [INDEXEDCOLORS] [MRUCOLORS] BrtEndColorPalette */
  17002. }
  17003. /* [MS-XLSB] 2.1.7.50 Styles */
  17004. function write_sty_bin(wb, opts) {
  17005. var ba = buf_array();
  17006. write_record(ba, "BrtBeginStyleSheet");
  17007. write_FMTS_bin(ba, wb.SSF);
  17008. write_FONTS_bin(ba, wb);
  17009. write_FILLS_bin(ba, wb);
  17010. write_BORDERS_bin(ba, wb);
  17011. write_CELLSTYLEXFS_bin(ba, wb);
  17012. write_CELLXFS_bin(ba, opts.cellXfs);
  17013. write_STYLES_bin(ba, wb);
  17014. write_DXFS_bin(ba, wb);
  17015. write_TABLESTYLES_bin(ba, wb);
  17016. write_COLORPALETTE_bin(ba, wb);
  17017. /* FRTSTYLESHEET*/
  17018. write_record(ba, "BrtEndStyleSheet");
  17019. return ba.end();
  17020. }
  17021. RELS.THEME = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme";
  17022. /* Even though theme layout is dk1 lt1 dk2 lt2, true order is lt1 dk1 lt2 dk2 */
  17023. var XLSXThemeClrScheme = [
  17024. '</a:lt1>', '</a:dk1>', '</a:lt2>', '</a:dk2>',
  17025. '</a:accent1>', '</a:accent2>', '</a:accent3>',
  17026. '</a:accent4>', '</a:accent5>', '</a:accent6>',
  17027. '</a:hlink>', '</a:folHlink>'
  17028. ];
  17029. /* 20.1.6.2 clrScheme CT_ColorScheme */
  17030. function parse_clrScheme(t, themes, opts) {
  17031. themes.themeElements.clrScheme = [];
  17032. var color = {};
  17033. (t[0].match(tagregex)||[]).forEach(function(x) {
  17034. var y = parsexmltag(x);
  17035. switch(y[0]) {
  17036. /* 20.1.6.2 clrScheme (Color Scheme) CT_ColorScheme */
  17037. case '<a:clrScheme': case '</a:clrScheme>': break;
  17038. /* 20.1.2.3.32 srgbClr CT_SRgbColor */
  17039. case '<a:srgbClr':
  17040. color.rgb = y.val; break;
  17041. /* 20.1.2.3.33 sysClr CT_SystemColor */
  17042. case '<a:sysClr':
  17043. color.rgb = y.lastClr; break;
  17044. /* 20.1.4.1.1 accent1 (Accent 1) */
  17045. /* 20.1.4.1.2 accent2 (Accent 2) */
  17046. /* 20.1.4.1.3 accent3 (Accent 3) */
  17047. /* 20.1.4.1.4 accent4 (Accent 4) */
  17048. /* 20.1.4.1.5 accent5 (Accent 5) */
  17049. /* 20.1.4.1.6 accent6 (Accent 6) */
  17050. /* 20.1.4.1.9 dk1 (Dark 1) */
  17051. /* 20.1.4.1.10 dk2 (Dark 2) */
  17052. /* 20.1.4.1.15 folHlink (Followed Hyperlink) */
  17053. /* 20.1.4.1.19 hlink (Hyperlink) */
  17054. /* 20.1.4.1.22 lt1 (Light 1) */
  17055. /* 20.1.4.1.23 lt2 (Light 2) */
  17056. case '<a:dk1>': case '</a:dk1>':
  17057. case '<a:lt1>': case '</a:lt1>':
  17058. case '<a:dk2>': case '</a:dk2>':
  17059. case '<a:lt2>': case '</a:lt2>':
  17060. case '<a:accent1>': case '</a:accent1>':
  17061. case '<a:accent2>': case '</a:accent2>':
  17062. case '<a:accent3>': case '</a:accent3>':
  17063. case '<a:accent4>': case '</a:accent4>':
  17064. case '<a:accent5>': case '</a:accent5>':
  17065. case '<a:accent6>': case '</a:accent6>':
  17066. case '<a:hlink>': case '</a:hlink>':
  17067. case '<a:folHlink>': case '</a:folHlink>':
  17068. if (y[0].charAt(1) === '/') {
  17069. themes.themeElements.clrScheme[XLSXThemeClrScheme.indexOf(y[0])] = color;
  17070. color = {};
  17071. } else {
  17072. color.name = y[0].slice(3, y[0].length - 1);
  17073. }
  17074. break;
  17075. default: if(opts && opts.WTF) throw new Error('Unrecognized ' + y[0] + ' in clrScheme');
  17076. }
  17077. });
  17078. }
  17079. /* 20.1.4.1.18 fontScheme CT_FontScheme */
  17080. function parse_fontScheme() { }
  17081. /* 20.1.4.1.15 fmtScheme CT_StyleMatrix */
  17082. function parse_fmtScheme() { }
  17083. var clrsregex = /<a:clrScheme([^>]*)>[\s\S]*<\/a:clrScheme>/;
  17084. var fntsregex = /<a:fontScheme([^>]*)>[\s\S]*<\/a:fontScheme>/;
  17085. var fmtsregex = /<a:fmtScheme([^>]*)>[\s\S]*<\/a:fmtScheme>/;
  17086. /* 20.1.6.10 themeElements CT_BaseStyles */
  17087. function parse_themeElements(data, themes, opts) {
  17088. themes.themeElements = {};
  17089. var t;
  17090. [
  17091. /* clrScheme CT_ColorScheme */
  17092. ['clrScheme', clrsregex, parse_clrScheme],
  17093. /* fontScheme CT_FontScheme */
  17094. ['fontScheme', fntsregex, parse_fontScheme],
  17095. /* fmtScheme CT_StyleMatrix */
  17096. ['fmtScheme', fmtsregex, parse_fmtScheme]
  17097. ].forEach(function(m) {
  17098. if(!(t=data.match(m[1]))) throw new Error(m[0] + ' not found in themeElements');
  17099. m[2](t, themes, opts);
  17100. });
  17101. }
  17102. var themeltregex = /<a:themeElements([^>]*)>[\s\S]*<\/a:themeElements>/;
  17103. /* 14.2.7 Theme Part */
  17104. function parse_theme_xml(data, opts) {
  17105. /* 20.1.6.9 theme CT_OfficeStyleSheet */
  17106. if(!data || data.length === 0) return parse_theme_xml(write_theme());
  17107. var t;
  17108. var themes = {};
  17109. /* themeElements CT_BaseStyles */
  17110. if(!(t=data.match(themeltregex))) throw new Error('themeElements not found in theme');
  17111. parse_themeElements(t[0], themes, opts);
  17112. themes.raw = data;
  17113. return themes;
  17114. }
  17115. function write_theme(Themes, opts) {
  17116. if(opts && opts.themeXLSX) return opts.themeXLSX;
  17117. if(Themes && typeof Themes.raw == "string") return Themes.raw;
  17118. var o = [XML_HEADER];
  17119. o[o.length] = '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">';
  17120. o[o.length] = '<a:themeElements>';
  17121. o[o.length] = '<a:clrScheme name="Office">';
  17122. o[o.length] = '<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>';
  17123. o[o.length] = '<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>';
  17124. o[o.length] = '<a:dk2><a:srgbClr val="1F497D"/></a:dk2>';
  17125. o[o.length] = '<a:lt2><a:srgbClr val="EEECE1"/></a:lt2>';
  17126. o[o.length] = '<a:accent1><a:srgbClr val="4F81BD"/></a:accent1>';
  17127. o[o.length] = '<a:accent2><a:srgbClr val="C0504D"/></a:accent2>';
  17128. o[o.length] = '<a:accent3><a:srgbClr val="9BBB59"/></a:accent3>';
  17129. o[o.length] = '<a:accent4><a:srgbClr val="8064A2"/></a:accent4>';
  17130. o[o.length] = '<a:accent5><a:srgbClr val="4BACC6"/></a:accent5>';
  17131. o[o.length] = '<a:accent6><a:srgbClr val="F79646"/></a:accent6>';
  17132. o[o.length] = '<a:hlink><a:srgbClr val="0000FF"/></a:hlink>';
  17133. o[o.length] = '<a:folHlink><a:srgbClr val="800080"/></a:folHlink>';
  17134. o[o.length] = '</a:clrScheme>';
  17135. o[o.length] = '<a:fontScheme name="Office">';
  17136. o[o.length] = '<a:majorFont>';
  17137. o[o.length] = '<a:latin typeface="Cambria"/>';
  17138. o[o.length] = '<a:ea typeface=""/>';
  17139. o[o.length] = '<a:cs typeface=""/>';
  17140. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  17141. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  17142. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  17143. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  17144. o[o.length] = '<a:font script="Arab" typeface="Times New Roman"/>';
  17145. o[o.length] = '<a:font script="Hebr" typeface="Times New Roman"/>';
  17146. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  17147. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  17148. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  17149. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  17150. o[o.length] = '<a:font script="Khmr" typeface="MoolBoran"/>';
  17151. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  17152. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  17153. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  17154. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  17155. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  17156. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  17157. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  17158. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  17159. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  17160. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  17161. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  17162. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  17163. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  17164. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  17165. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  17166. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  17167. o[o.length] = '<a:font script="Viet" typeface="Times New Roman"/>';
  17168. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  17169. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  17170. o[o.length] = '</a:majorFont>';
  17171. o[o.length] = '<a:minorFont>';
  17172. o[o.length] = '<a:latin typeface="Calibri"/>';
  17173. o[o.length] = '<a:ea typeface=""/>';
  17174. o[o.length] = '<a:cs typeface=""/>';
  17175. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  17176. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  17177. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  17178. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  17179. o[o.length] = '<a:font script="Arab" typeface="Arial"/>';
  17180. o[o.length] = '<a:font script="Hebr" typeface="Arial"/>';
  17181. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  17182. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  17183. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  17184. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  17185. o[o.length] = '<a:font script="Khmr" typeface="DaunPenh"/>';
  17186. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  17187. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  17188. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  17189. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  17190. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  17191. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  17192. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  17193. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  17194. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  17195. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  17196. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  17197. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  17198. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  17199. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  17200. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  17201. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  17202. o[o.length] = '<a:font script="Viet" typeface="Arial"/>';
  17203. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  17204. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  17205. o[o.length] = '</a:minorFont>';
  17206. o[o.length] = '</a:fontScheme>';
  17207. o[o.length] = '<a:fmtScheme name="Office">';
  17208. o[o.length] = '<a:fillStyleLst>';
  17209. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  17210. o[o.length] = '<a:gradFill rotWithShape="1">';
  17211. o[o.length] = '<a:gsLst>';
  17212. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  17213. o[o.length] = '<a:gs pos="35000"><a:schemeClr val="phClr"><a:tint val="37000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  17214. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="15000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  17215. o[o.length] = '</a:gsLst>';
  17216. o[o.length] = '<a:lin ang="16200000" scaled="1"/>';
  17217. o[o.length] = '</a:gradFill>';
  17218. o[o.length] = '<a:gradFill rotWithShape="1">';
  17219. o[o.length] = '<a:gsLst>';
  17220. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="100000"/><a:shade val="100000"/><a:satMod val="130000"/></a:schemeClr></a:gs>';
  17221. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="50000"/><a:shade val="100000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  17222. o[o.length] = '</a:gsLst>';
  17223. o[o.length] = '<a:lin ang="16200000" scaled="0"/>';
  17224. o[o.length] = '</a:gradFill>';
  17225. o[o.length] = '</a:fillStyleLst>';
  17226. o[o.length] = '<a:lnStyleLst>';
  17227. o[o.length] = '<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>';
  17228. o[o.length] = '<a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>';
  17229. o[o.length] = '<a:ln w="38100" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>';
  17230. o[o.length] = '</a:lnStyleLst>';
  17231. o[o.length] = '<a:effectStyleLst>';
  17232. o[o.length] = '<a:effectStyle>';
  17233. o[o.length] = '<a:effectLst>';
  17234. o[o.length] = '<a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="38000"/></a:srgbClr></a:outerShdw>';
  17235. o[o.length] = '</a:effectLst>';
  17236. o[o.length] = '</a:effectStyle>';
  17237. o[o.length] = '<a:effectStyle>';
  17238. o[o.length] = '<a:effectLst>';
  17239. o[o.length] = '<a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw>';
  17240. o[o.length] = '</a:effectLst>';
  17241. o[o.length] = '</a:effectStyle>';
  17242. o[o.length] = '<a:effectStyle>';
  17243. o[o.length] = '<a:effectLst>';
  17244. o[o.length] = '<a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw>';
  17245. o[o.length] = '</a:effectLst>';
  17246. o[o.length] = '<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>';
  17247. o[o.length] = '<a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d>';
  17248. o[o.length] = '</a:effectStyle>';
  17249. o[o.length] = '</a:effectStyleLst>';
  17250. o[o.length] = '<a:bgFillStyleLst>';
  17251. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  17252. o[o.length] = '<a:gradFill rotWithShape="1">';
  17253. o[o.length] = '<a:gsLst>';
  17254. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="40000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  17255. o[o.length] = '<a:gs pos="40000"><a:schemeClr val="phClr"><a:tint val="45000"/><a:shade val="99000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  17256. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="20000"/><a:satMod val="255000"/></a:schemeClr></a:gs>';
  17257. o[o.length] = '</a:gsLst>';
  17258. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="-80000" r="50000" b="180000"/></a:path>';
  17259. o[o.length] = '</a:gradFill>';
  17260. o[o.length] = '<a:gradFill rotWithShape="1">';
  17261. o[o.length] = '<a:gsLst>';
  17262. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="80000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  17263. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="30000"/><a:satMod val="200000"/></a:schemeClr></a:gs>';
  17264. o[o.length] = '</a:gsLst>';
  17265. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path>';
  17266. o[o.length] = '</a:gradFill>';
  17267. o[o.length] = '</a:bgFillStyleLst>';
  17268. o[o.length] = '</a:fmtScheme>';
  17269. o[o.length] = '</a:themeElements>';
  17270. o[o.length] = '<a:objectDefaults>';
  17271. o[o.length] = '<a:spDef>';
  17272. o[o.length] = '<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>';
  17273. o[o.length] = '</a:spDef>';
  17274. o[o.length] = '<a:lnDef>';
  17275. o[o.length] = '<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>';
  17276. o[o.length] = '</a:lnDef>';
  17277. o[o.length] = '</a:objectDefaults>';
  17278. o[o.length] = '<a:extraClrSchemeLst/>';
  17279. o[o.length] = '</a:theme>';
  17280. return o.join("");
  17281. }
  17282. /* [MS-XLS] 2.4.326 TODO: payload is a zip file */
  17283. function parse_Theme(blob, length, opts) {
  17284. var end = blob.l + length;
  17285. var dwThemeVersion = blob.read_shift(4);
  17286. if(dwThemeVersion === 124226) return;
  17287. if(!opts.cellStyles || !jszip) { blob.l = end; return; }
  17288. var data = blob.slice(blob.l);
  17289. blob.l = end;
  17290. var zip; try { zip = new jszip(data); } catch(e) { return; }
  17291. var themeXML = getzipstr(zip, "theme/theme/theme1.xml", true);
  17292. if(!themeXML) return;
  17293. return parse_theme_xml(themeXML, opts);
  17294. }
  17295. /* 2.5.49 */
  17296. function parse_ColorTheme(blob) { return blob.read_shift(4); }
  17297. /* 2.5.155 */
  17298. function parse_FullColorExt(blob) {
  17299. var o = {};
  17300. o.xclrType = blob.read_shift(2);
  17301. o.nTintShade = blob.read_shift(2);
  17302. switch(o.xclrType) {
  17303. case 0: blob.l += 4; break;
  17304. case 1: o.xclrValue = parse_IcvXF(blob, 4); break;
  17305. case 2: o.xclrValue = parse_LongRGBA(blob, 4); break;
  17306. case 3: o.xclrValue = parse_ColorTheme(blob, 4); break;
  17307. case 4: blob.l += 4; break;
  17308. }
  17309. blob.l += 8;
  17310. return o;
  17311. }
  17312. /* 2.5.164 TODO: read 7 bits*/
  17313. function parse_IcvXF(blob, length) {
  17314. return parsenoop(blob, length);
  17315. }
  17316. /* 2.5.280 */
  17317. function parse_XFExtGradient(blob, length) {
  17318. return parsenoop(blob, length);
  17319. }
  17320. /* [MS-XLS] 2.5.108 */
  17321. function parse_ExtProp(blob) {
  17322. var extType = blob.read_shift(2);
  17323. var cb = blob.read_shift(2) - 4;
  17324. var o = [extType];
  17325. switch(extType) {
  17326. case 0x04: case 0x05: case 0x07: case 0x08:
  17327. case 0x09: case 0x0A: case 0x0B: case 0x0D:
  17328. o[1] = parse_FullColorExt(blob, cb); break;
  17329. case 0x06: o[1] = parse_XFExtGradient(blob, cb); break;
  17330. case 0x0E: case 0x0F: o[1] = blob.read_shift(cb === 1 ? 1 : 2); break;
  17331. default: throw new Error("Unrecognized ExtProp type: " + extType + " " + cb);
  17332. }
  17333. return o;
  17334. }
  17335. /* 2.4.355 */
  17336. function parse_XFExt(blob, length) {
  17337. var end = blob.l + length;
  17338. blob.l += 2;
  17339. var ixfe = blob.read_shift(2);
  17340. blob.l += 2;
  17341. var cexts = blob.read_shift(2);
  17342. var ext = [];
  17343. while(cexts-- > 0) ext.push(parse_ExtProp(blob, end-blob.l));
  17344. return {ixfe:ixfe, ext:ext};
  17345. }
  17346. /* xf is an XF, see parse_XFExt for xfext */
  17347. function update_xfext(xf, xfext) {
  17348. xfext.forEach(function(xfe) {
  17349. switch(xfe[0]) { /* 2.5.108 extPropData */
  17350. case 0x04: break; /* foreground color */
  17351. case 0x05: break; /* background color */
  17352. case 0x06: break; /* gradient fill */
  17353. case 0x07: break; /* top cell border color */
  17354. case 0x08: break; /* bottom cell border color */
  17355. case 0x09: break; /* left cell border color */
  17356. case 0x0a: break; /* right cell border color */
  17357. case 0x0b: break; /* diagonal cell border color */
  17358. case 0x0d: /* text color */
  17359. break;
  17360. case 0x0e: break; /* font scheme */
  17361. case 0x0f: break; /* indentation level */
  17362. }
  17363. });
  17364. }
  17365. /* 18.6 Calculation Chain */
  17366. function parse_cc_xml(data) {
  17367. var d = [];
  17368. if(!data) return d;
  17369. var i = 1;
  17370. (data.match(tagregex)||[]).forEach(function(x) {
  17371. var y = parsexmltag(x);
  17372. switch(y[0]) {
  17373. case '<?xml': break;
  17374. /* 18.6.2 calcChain CT_CalcChain 1 */
  17375. case '<calcChain': case '<calcChain>': case '</calcChain>': break;
  17376. /* 18.6.1 c CT_CalcCell 1 */
  17377. case '<c': delete y[0]; if(y.i) i = y.i; else y.i = i; d.push(y); break;
  17378. }
  17379. });
  17380. return d;
  17381. }
  17382. //function write_cc_xml(data, opts) { }
  17383. /* [MS-XLSB] 2.6.4.1 */
  17384. function parse_BrtCalcChainItem$(data) {
  17385. var out = {};
  17386. out.i = data.read_shift(4);
  17387. var cell = {};
  17388. cell.r = data.read_shift(4);
  17389. cell.c = data.read_shift(4);
  17390. out.r = encode_cell(cell);
  17391. var flags = data.read_shift(1);
  17392. if(flags & 0x2) out.l = '1';
  17393. if(flags & 0x8) out.a = '1';
  17394. return out;
  17395. }
  17396. /* 18.6 Calculation Chain */
  17397. function parse_cc_bin(data, name, opts) {
  17398. var out = [];
  17399. var pass = false;
  17400. recordhopper(data, function hopper_cc(val, R_n, RT) {
  17401. switch(RT) {
  17402. case 0x003F: /* 'BrtCalcChainItem$' */
  17403. out.push(val); break;
  17404. default:
  17405. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  17406. else if((R_n||"").indexOf("End") > 0){/* empty */}
  17407. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  17408. }
  17409. });
  17410. return out;
  17411. }
  17412. //function write_cc_bin(data, opts) { }
  17413. /* 18.14 Supplementary Workbook Data */
  17414. function parse_xlink_xml() {
  17415. //var opts = _opts || {};
  17416. //if(opts.WTF) throw "XLSX External Link";
  17417. }
  17418. /* [MS-XLSB] 2.1.7.25 External Link */
  17419. function parse_xlink_bin(data, rel, name, _opts) {
  17420. if(!data) return data;
  17421. var opts = _opts || {};
  17422. var pass = false, end = false;
  17423. recordhopper(data, function xlink_parse(val, R_n, RT) {
  17424. if(end) return;
  17425. switch(RT) {
  17426. case 0x0167: /* 'BrtSupTabs' */
  17427. case 0x016B: /* 'BrtExternTableStart' */
  17428. case 0x016C: /* 'BrtExternTableEnd' */
  17429. case 0x016E: /* 'BrtExternRowHdr' */
  17430. case 0x016F: /* 'BrtExternCellBlank' */
  17431. case 0x0170: /* 'BrtExternCellReal' */
  17432. case 0x0171: /* 'BrtExternCellBool' */
  17433. case 0x0172: /* 'BrtExternCellError' */
  17434. case 0x0173: /* 'BrtExternCellString' */
  17435. case 0x01D8: /* 'BrtExternValueMeta' */
  17436. case 0x0241: /* 'BrtSupNameStart' */
  17437. case 0x0242: /* 'BrtSupNameValueStart' */
  17438. case 0x0243: /* 'BrtSupNameValueEnd' */
  17439. case 0x0244: /* 'BrtSupNameNum' */
  17440. case 0x0245: /* 'BrtSupNameErr' */
  17441. case 0x0246: /* 'BrtSupNameSt' */
  17442. case 0x0247: /* 'BrtSupNameNil' */
  17443. case 0x0248: /* 'BrtSupNameBool' */
  17444. case 0x0249: /* 'BrtSupNameFmla' */
  17445. case 0x024A: /* 'BrtSupNameBits' */
  17446. case 0x024B: /* 'BrtSupNameEnd' */
  17447. break;
  17448. case 0x0023: /* 'BrtFRTBegin' */
  17449. pass = true; break;
  17450. case 0x0024: /* 'BrtFRTEnd' */
  17451. pass = false; break;
  17452. default:
  17453. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  17454. else if((R_n||"").indexOf("End") > 0){/* empty */}
  17455. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT.toString(16) + " " + R_n);
  17456. }
  17457. }, opts);
  17458. }
  17459. /* 20.5 DrawingML - SpreadsheetML Drawing */
  17460. RELS.IMG = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
  17461. RELS.DRAW = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing";
  17462. /* 20.5.2.35 wsDr CT_Drawing */
  17463. function parse_drawing(data, rels) {
  17464. if(!data) return "??";
  17465. /*
  17466. Chartsheet Drawing:
  17467. - 20.5.2.35 wsDr CT_Drawing
  17468. - 20.5.2.1 absoluteAnchor CT_AbsoluteAnchor
  17469. - 20.5.2.16 graphicFrame CT_GraphicalObjectFrame
  17470. - 20.1.2.2.16 graphic CT_GraphicalObject
  17471. - 20.1.2.2.17 graphicData CT_GraphicalObjectData
  17472. - chart reference
  17473. the actual type is based on the URI of the graphicData
  17474. TODO: handle embedded charts and other types of graphics
  17475. */
  17476. var id = (data.match(/<c:chart [^>]*r:id="([^"]*)"/)||["",""])[1];
  17477. return rels['!id'][id].Target;
  17478. }
  17479. /* L.5.5.2 SpreadsheetML Comments + VML Schema */
  17480. var _shapeid = 1024;
  17481. function write_comments_vml(rId, comments) {
  17482. var csize = [21600, 21600];
  17483. /* L.5.2.1.2 Path Attribute */
  17484. var bbox = ["m0,0l0",csize[1],csize[0],csize[1],csize[0],"0xe"].join(",");
  17485. var o = [
  17486. writextag("xml", null, { 'xmlns:v': XLMLNS.v, 'xmlns:o': XLMLNS.o, 'xmlns:x': XLMLNS.x, 'xmlns:mv': XLMLNS.mv }).replace(/\/>/,">"),
  17487. writextag("o:shapelayout", writextag("o:idmap", null, {'v:ext':"edit", 'data':rId}), {'v:ext':"edit"}),
  17488. writextag("v:shapetype", [
  17489. writextag("v:stroke", null, {joinstyle:"miter"}),
  17490. writextag("v:path", null, {gradientshapeok:"t", 'o:connecttype':"rect"})
  17491. ].join(""), {id:"_x0000_t202", 'o:spt':202, coordsize:csize.join(","),path:bbox})
  17492. ];
  17493. while(_shapeid < rId * 1000) _shapeid += 1000;
  17494. comments.forEach(function(x) {
  17495. var c = decode_cell(x[0]);
  17496. var fillopts = {'color2':"#BEFF82", 'type':"gradient"};
  17497. if(fillopts.type == "gradient") fillopts.angle = "-180";
  17498. var fillparm = fillopts.type == "gradient" ? writextag("o:fill", null, {type:"gradientUnscaled", 'v:ext':"view"}) : null;
  17499. var fillxml = writextag('v:fill', fillparm, fillopts);
  17500. var shadata = ({on:"t", 'obscured':"t"});
  17501. ++_shapeid;
  17502. o = o.concat([
  17503. '<v:shape' + wxt_helper({
  17504. id:'_x0000_s' + _shapeid,
  17505. type:"#_x0000_t202",
  17506. style:"position:absolute; margin-left:80pt;margin-top:5pt;width:104pt;height:64pt;z-index:10" + (x[1].hidden ? ";visibility:hidden" : "") ,
  17507. fillcolor:"#ECFAD4",
  17508. strokecolor:"#edeaa1"
  17509. }) + '>',
  17510. fillxml,
  17511. writextag("v:shadow", null, shadata),
  17512. writextag("v:path", null, {'o:connecttype':"none"}),
  17513. '<v:textbox><div style="text-align:left"></div></v:textbox>',
  17514. '<x:ClientData ObjectType="Note">',
  17515. '<x:MoveWithCells/>',
  17516. '<x:SizeWithCells/>',
  17517. /* Part 4 19.4.2.3 Anchor (Anchor) */
  17518. writetag('x:Anchor', [c.c+1, 0, c.r+1, 0, c.c+3, 20, c.r+5, 20].join(",")),
  17519. writetag('x:AutoFill', "False"),
  17520. writetag('x:Row', String(c.r)),
  17521. writetag('x:Column', String(c.c)),
  17522. x[1].hidden ? '' : '<x:Visible/>',
  17523. '</x:ClientData>',
  17524. '</v:shape>'
  17525. ]); });
  17526. o.push('</xml>');
  17527. return o.join("");
  17528. }
  17529. RELS.CMNT = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
  17530. function sheet_insert_comments(sheet, comments) {
  17531. var dense = Array.isArray(sheet);
  17532. var cell;
  17533. comments.forEach(function(comment) {
  17534. var r = decode_cell(comment.ref);
  17535. if(dense) {
  17536. if(!sheet[r.r]) sheet[r.r] = [];
  17537. cell = sheet[r.r][r.c];
  17538. } else cell = sheet[comment.ref];
  17539. if (!cell) {
  17540. cell = ({t:"z"});
  17541. if(dense) sheet[r.r][r.c] = cell;
  17542. else sheet[comment.ref] = cell;
  17543. var range = safe_decode_range(sheet["!ref"]||"BDWGO1000001:A1");
  17544. if(range.s.r > r.r) range.s.r = r.r;
  17545. if(range.e.r < r.r) range.e.r = r.r;
  17546. if(range.s.c > r.c) range.s.c = r.c;
  17547. if(range.e.c < r.c) range.e.c = r.c;
  17548. var encoded = encode_range(range);
  17549. if (encoded !== sheet["!ref"]) sheet["!ref"] = encoded;
  17550. }
  17551. if (!cell.c) cell.c = [];
  17552. var o = ({a: comment.author, t: comment.t, r: comment.r});
  17553. if(comment.h) o.h = comment.h;
  17554. cell.c.push(o);
  17555. });
  17556. }
  17557. /* 18.7 Comments */
  17558. function parse_comments_xml(data, opts) {
  17559. /* 18.7.6 CT_Comments */
  17560. if(data.match(/<(?:\w+:)?comments *\/>/)) return [];
  17561. var authors = [];
  17562. var commentList = [];
  17563. var authtag = data.match(/<(?:\w+:)?authors>([\s\S]*)<\/(?:\w+:)?authors>/);
  17564. if(authtag && authtag[1]) authtag[1].split(/<\/\w*:?author>/).forEach(function(x) {
  17565. if(x === "" || x.trim() === "") return;
  17566. var a = x.match(/<(?:\w+:)?author[^>]*>(.*)/);
  17567. if(a) authors.push(a[1]);
  17568. });
  17569. var cmnttag = data.match(/<(?:\w+:)?commentList>([\s\S]*)<\/(?:\w+:)?commentList>/);
  17570. if(cmnttag && cmnttag[1]) cmnttag[1].split(/<\/\w*:?comment>/).forEach(function(x) {
  17571. if(x === "" || x.trim() === "") return;
  17572. var cm = x.match(/<(?:\w+:)?comment[^>]*>/);
  17573. if(!cm) return;
  17574. var y = parsexmltag(cm[0]);
  17575. var comment = ({ author: y.authorId && authors[y.authorId] || "sheetjsghost", ref: y.ref, guid: y.guid });
  17576. var cell = decode_cell(y.ref);
  17577. if(opts.sheetRows && opts.sheetRows <= cell.r) return;
  17578. var textMatch = x.match(/<(?:\w+:)?text>([\s\S]*)<\/(?:\w+:)?text>/);
  17579. var rt = !!textMatch && !!textMatch[1] && parse_si(textMatch[1]) || {r:"",t:"",h:""};
  17580. comment.r = rt.r;
  17581. if(rt.r == "<t></t>") rt.t = rt.h = "";
  17582. comment.t = rt.t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");
  17583. if(opts.cellHTML) comment.h = rt.h;
  17584. commentList.push(comment);
  17585. });
  17586. return commentList;
  17587. }
  17588. var CMNT_XML_ROOT = writextag('comments', null, { 'xmlns': XMLNS.main[0] });
  17589. function write_comments_xml(data) {
  17590. var o = [XML_HEADER, CMNT_XML_ROOT];
  17591. var iauthor = [];
  17592. o.push("<authors>");
  17593. data.forEach(function(x) { x[1].forEach(function(w) { var a = escapexml(w.a);
  17594. if(iauthor.indexOf(a) > -1) return;
  17595. iauthor.push(a);
  17596. o.push("<author>" + a + "</author>");
  17597. }); });
  17598. o.push("</authors>");
  17599. o.push("<commentList>");
  17600. data.forEach(function(d) {
  17601. d[1].forEach(function(c) {
  17602. /* 18.7.3 CT_Comment */
  17603. o.push('<comment ref="' + d[0] + '" authorId="' + iauthor.indexOf(escapexml(c.a)) + '"><text>');
  17604. o.push(writetag("t", c.t == null ? "" : escapexml(c.t)));
  17605. o.push('</text></comment>');
  17606. });
  17607. });
  17608. o.push("</commentList>");
  17609. if(o.length>2) { o[o.length] = ('</comments>'); o[1]=o[1].replace("/>",">"); }
  17610. return o.join("");
  17611. }
  17612. /* [MS-XLSB] 2.4.28 BrtBeginComment */
  17613. function parse_BrtBeginComment(data) {
  17614. var out = {};
  17615. out.iauthor = data.read_shift(4);
  17616. var rfx = parse_UncheckedRfX(data, 16);
  17617. out.rfx = rfx.s;
  17618. out.ref = encode_cell(rfx.s);
  17619. data.l += 16; /*var guid = parse_GUID(data); */
  17620. return out;
  17621. }
  17622. function write_BrtBeginComment(data, o) {
  17623. if(o == null) o = new_buf(36);
  17624. o.write_shift(4, data[1].iauthor);
  17625. write_UncheckedRfX((data[0]), o);
  17626. o.write_shift(4, 0);
  17627. o.write_shift(4, 0);
  17628. o.write_shift(4, 0);
  17629. o.write_shift(4, 0);
  17630. return o;
  17631. }
  17632. /* [MS-XLSB] 2.4.327 BrtCommentAuthor */
  17633. var parse_BrtCommentAuthor = parse_XLWideString;
  17634. function write_BrtCommentAuthor(data) { return write_XLWideString(data.slice(0, 54)); }
  17635. /* [MS-XLSB] 2.1.7.8 Comments */
  17636. function parse_comments_bin(data, opts) {
  17637. var out = [];
  17638. var authors = [];
  17639. var c = {};
  17640. var pass = false;
  17641. recordhopper(data, function hopper_cmnt(val, R_n, RT) {
  17642. switch(RT) {
  17643. case 0x0278: /* 'BrtCommentAuthor' */
  17644. authors.push(val); break;
  17645. case 0x027B: /* 'BrtBeginComment' */
  17646. c = val; break;
  17647. case 0x027D: /* 'BrtCommentText' */
  17648. c.t = val.t; c.h = val.h; c.r = val.r; break;
  17649. case 0x027C: /* 'BrtEndComment' */
  17650. c.author = authors[c.iauthor];
  17651. delete (c).iauthor;
  17652. if(opts.sheetRows && c.rfx && opts.sheetRows <= c.rfx.r) break;
  17653. if(!c.t) c.t = "";
  17654. delete c.rfx; out.push(c); break;
  17655. case 0x0C00: /* 'BrtUid' */
  17656. break;
  17657. case 0x0023: /* 'BrtFRTBegin' */
  17658. pass = true; break;
  17659. case 0x0024: /* 'BrtFRTEnd' */
  17660. pass = false; break;
  17661. case 0x0025: /* 'BrtACBegin' */ break;
  17662. case 0x0026: /* 'BrtACEnd' */ break;
  17663. default:
  17664. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  17665. else if((R_n||"").indexOf("End") > 0){/* empty */}
  17666. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  17667. }
  17668. });
  17669. return out;
  17670. }
  17671. function write_comments_bin(data) {
  17672. var ba = buf_array();
  17673. var iauthor = [];
  17674. write_record(ba, "BrtBeginComments");
  17675. write_record(ba, "BrtBeginCommentAuthors");
  17676. data.forEach(function(comment) {
  17677. comment[1].forEach(function(c) {
  17678. if(iauthor.indexOf(c.a) > -1) return;
  17679. iauthor.push(c.a.slice(0,54));
  17680. write_record(ba, "BrtCommentAuthor", write_BrtCommentAuthor(c.a));
  17681. });
  17682. });
  17683. write_record(ba, "BrtEndCommentAuthors");
  17684. write_record(ba, "BrtBeginCommentList");
  17685. data.forEach(function(comment) {
  17686. comment[1].forEach(function(c) {
  17687. c.iauthor = iauthor.indexOf(c.a);
  17688. var range = {s:decode_cell(comment[0]),e:decode_cell(comment[0])};
  17689. write_record(ba, "BrtBeginComment", write_BrtBeginComment([range, c]));
  17690. if(c.t && c.t.length > 0) write_record(ba, "BrtCommentText", write_BrtCommentText(c));
  17691. write_record(ba, "BrtEndComment");
  17692. delete c.iauthor;
  17693. });
  17694. });
  17695. write_record(ba, "BrtEndCommentList");
  17696. write_record(ba, "BrtEndComments");
  17697. return ba.end();
  17698. }
  17699. var CT_VBA = "application/vnd.ms-office.vbaProject";
  17700. function make_vba_xls(cfb) {
  17701. var newcfb = CFB.utils.cfb_new({root:"R"});
  17702. cfb.FullPaths.forEach(function(p, i) {
  17703. if(p.slice(-1) === "/" || !p.match(/_VBA_PROJECT_CUR/)) return;
  17704. var newpath = p.replace(/^[^\/]*/,"R").replace(/\/_VBA_PROJECT_CUR\u0000*/, "");
  17705. CFB.utils.cfb_add(newcfb, newpath, cfb.FileIndex[i].content);
  17706. });
  17707. return CFB.write(newcfb);
  17708. }
  17709. function fill_vba_xls(cfb, vba) {
  17710. vba.FullPaths.forEach(function(p, i) {
  17711. if(i == 0) return;
  17712. var newpath = p.replace(/[^\/]*[\/]/, "/_VBA_PROJECT_CUR/");
  17713. if(newpath.slice(-1) !== "/") CFB.utils.cfb_add(cfb, newpath, vba.FileIndex[i].content);
  17714. });
  17715. }
  17716. var VBAFMTS = [ "xlsb", "xlsm", "xlam", "biff8", "xla" ];
  17717. RELS.DS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet";
  17718. RELS.MS = "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet";
  17719. /* macro and dialog sheet stubs */
  17720. function parse_ds_bin() { return {'!type':'dialog'}; }
  17721. function parse_ds_xml() { return {'!type':'dialog'}; }
  17722. function parse_ms_bin() { return {'!type':'macro'}; }
  17723. function parse_ms_xml() { return {'!type':'macro'}; }
  17724. /* TODO: it will be useful to parse the function str */
  17725. var rc_to_a1 = (function(){
  17726. var rcregex = /(^|[^A-Za-z_])R(\[?-?\d+\]|[1-9]\d*|)C(\[?-?\d+\]|[1-9]\d*|)(?![A-Za-z0-9_])/g;
  17727. var rcbase = ({r:0,c:0});
  17728. function rcfunc($$,$1,$2,$3) {
  17729. var cRel = false, rRel = false;
  17730. if($2.length == 0) rRel = true;
  17731. else if($2.charAt(0) == "[") { rRel = true; $2 = $2.slice(1, -1); }
  17732. if($3.length == 0) cRel = true;
  17733. else if($3.charAt(0) == "[") { cRel = true; $3 = $3.slice(1, -1); }
  17734. var R = $2.length>0?parseInt($2,10)|0:0, C = $3.length>0?parseInt($3,10)|0:0;
  17735. if(cRel) C += rcbase.c; else --C;
  17736. if(rRel) R += rcbase.r; else --R;
  17737. return $1 + (cRel ? "" : "$") + encode_col(C) + (rRel ? "" : "$") + encode_row(R);
  17738. }
  17739. return function rc_to_a1(fstr, base) {
  17740. rcbase = base;
  17741. return fstr.replace(rcregex, rcfunc);
  17742. };
  17743. })();
  17744. var crefregex = /(^|[^._A-Z0-9])([$]?)([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([$]?)(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})(?![_.\(A-Za-z0-9])/g;
  17745. var a1_to_rc =(function(){
  17746. return function a1_to_rc(fstr, base) {
  17747. return fstr.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  17748. var c = decode_col($3) - ($2 ? 0 : base.c);
  17749. var r = decode_row($5) - ($4 ? 0 : base.r);
  17750. var R = (r == 0 ? "" : !$4 ? "[" + r + "]" : (r+1));
  17751. var C = (c == 0 ? "" : !$2 ? "[" + c + "]" : (c+1));
  17752. return $1 + "R" + R + "C" + C;
  17753. });
  17754. };
  17755. })();
  17756. /* no defined name can collide with a valid cell address A1:XFD1048576 ... except LOG10! */
  17757. function shift_formula_str(f, delta) {
  17758. return f.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  17759. return $1+($2=="$" ? $2+$3 : encode_col(decode_col($3)+delta.c))+($4=="$" ? $4+$5 : encode_row(decode_row($5) + delta.r));
  17760. });
  17761. }
  17762. function shift_formula_xlsx(f, range, cell) {
  17763. var r = decode_range(range), s = r.s, c = decode_cell(cell);
  17764. var delta = {r:c.r - s.r, c:c.c - s.c};
  17765. return shift_formula_str(f, delta);
  17766. }
  17767. /* TODO: parse formula */
  17768. function fuzzyfmla(f) {
  17769. if(f.length == 1) return false;
  17770. return true;
  17771. }
  17772. function _xlfn(f) {
  17773. return f.replace(/_xlfn\./g,"");
  17774. }
  17775. function parseread1(blob) { blob.l+=1; return; }
  17776. /* [MS-XLS] 2.5.51 */
  17777. function parse_ColRelU(blob, length) {
  17778. var c = blob.read_shift(length == 1 ? 1 : 2);
  17779. return [c & 0x3FFF, (c >> 14) & 1, (c >> 15) & 1];
  17780. }
  17781. /* [MS-XLS] 2.5.198.105 ; [MS-XLSB] 2.5.97.89 */
  17782. function parse_RgceArea(blob, length, opts) {
  17783. var w = 2;
  17784. if(opts) {
  17785. if(opts.biff >= 2 && opts.biff <= 5) return parse_RgceArea_BIFF2(blob, length, opts);
  17786. else if(opts.biff == 12) w = 4;
  17787. }
  17788. var r=blob.read_shift(w), R=blob.read_shift(w);
  17789. var c=parse_ColRelU(blob, 2);
  17790. var C=parse_ColRelU(blob, 2);
  17791. return { s:{r:r, c:c[0], cRel:c[1], rRel:c[2]}, e:{r:R, c:C[0], cRel:C[1], rRel:C[2]} };
  17792. }
  17793. /* BIFF 2-5 encodes flags in the row field */
  17794. function parse_RgceArea_BIFF2(blob) {
  17795. var r=parse_ColRelU(blob, 2), R=parse_ColRelU(blob, 2);
  17796. var c=blob.read_shift(1);
  17797. var C=blob.read_shift(1);
  17798. return { s:{r:r[0], c:c, cRel:r[1], rRel:r[2]}, e:{r:R[0], c:C, cRel:R[1], rRel:R[2]} };
  17799. }
  17800. /* [MS-XLS] 2.5.198.105 ; [MS-XLSB] 2.5.97.90 */
  17801. function parse_RgceAreaRel(blob, length, opts) {
  17802. if(opts.biff < 8) return parse_RgceArea_BIFF2(blob, length, opts);
  17803. var r=blob.read_shift(opts.biff == 12 ? 4 : 2), R=blob.read_shift(opts.biff == 12 ? 4 : 2);
  17804. var c=parse_ColRelU(blob, 2);
  17805. var C=parse_ColRelU(blob, 2);
  17806. return { s:{r:r, c:c[0], cRel:c[1], rRel:c[2]}, e:{r:R, c:C[0], cRel:C[1], rRel:C[2]} };
  17807. }
  17808. /* [MS-XLS] 2.5.198.109 ; [MS-XLSB] 2.5.97.91 */
  17809. function parse_RgceLoc(blob, length, opts) {
  17810. if(opts && opts.biff >= 2 && opts.biff <= 5) return parse_RgceLoc_BIFF2(blob, length, opts);
  17811. var r = blob.read_shift(opts && opts.biff == 12 ? 4 : 2);
  17812. var c = parse_ColRelU(blob, 2);
  17813. return {r:r, c:c[0], cRel:c[1], rRel:c[2]};
  17814. }
  17815. function parse_RgceLoc_BIFF2(blob) {
  17816. var r = parse_ColRelU(blob, 2);
  17817. var c = blob.read_shift(1);
  17818. return {r:r[0], c:c, cRel:r[1], rRel:r[2]};
  17819. }
  17820. /* [MS-XLS] 2.5.198.107, 2.5.47 */
  17821. function parse_RgceElfLoc(blob) {
  17822. var r = blob.read_shift(2);
  17823. var c = blob.read_shift(2);
  17824. return {r:r, c:c & 0xFF, fQuoted:!!(c & 0x4000), cRel:c>>15, rRel:c>>15 };
  17825. }
  17826. /* [MS-XLS] 2.5.198.111 ; [MS-XLSB] 2.5.97.92 TODO */
  17827. function parse_RgceLocRel(blob, length, opts) {
  17828. var biff = opts && opts.biff ? opts.biff : 8;
  17829. if(biff >= 2 && biff <= 5) return parse_RgceLocRel_BIFF2(blob, length, opts);
  17830. var r = blob.read_shift(biff >= 12 ? 4 : 2);
  17831. var cl = blob.read_shift(2);
  17832. var cRel = (cl & 0x4000) >> 14, rRel = (cl & 0x8000) >> 15;
  17833. cl &= 0x3FFF;
  17834. if(rRel == 1) while(r > 0x7FFFF) r -= 0x100000;
  17835. if(cRel == 1) while(cl > 0x1FFF) cl = cl - 0x4000;
  17836. return {r:r,c:cl,cRel:cRel,rRel:rRel};
  17837. }
  17838. function parse_RgceLocRel_BIFF2(blob) {
  17839. var rl = blob.read_shift(2);
  17840. var c = blob.read_shift(1);
  17841. var rRel = (rl & 0x8000) >> 15, cRel = (rl & 0x4000) >> 14;
  17842. rl &= 0x3FFF;
  17843. if(rRel == 1 && rl >= 0x2000) rl = rl - 0x4000;
  17844. if(cRel == 1 && c >= 0x80) c = c - 0x100;
  17845. return {r:rl,c:c,cRel:cRel,rRel:rRel};
  17846. }
  17847. /* [MS-XLS] 2.5.198.27 ; [MS-XLSB] 2.5.97.18 */
  17848. function parse_PtgArea(blob, length, opts) {
  17849. var type = (blob[blob.l++] & 0x60) >> 5;
  17850. var area = parse_RgceArea(blob, opts.biff >= 2 && opts.biff <= 5 ? 6 : 8, opts);
  17851. return [type, area];
  17852. }
  17853. /* [MS-XLS] 2.5.198.28 ; [MS-XLSB] 2.5.97.19 */
  17854. function parse_PtgArea3d(blob, length, opts) {
  17855. var type = (blob[blob.l++] & 0x60) >> 5;
  17856. var ixti = blob.read_shift(2, 'i');
  17857. var w = 8;
  17858. if(opts) switch(opts.biff) {
  17859. case 5: blob.l += 12; w = 6; break;
  17860. case 12: w = 12; break;
  17861. }
  17862. var area = parse_RgceArea(blob, w, opts);
  17863. return [type, ixti, area];
  17864. }
  17865. /* [MS-XLS] 2.5.198.29 ; [MS-XLSB] 2.5.97.20 */
  17866. function parse_PtgAreaErr(blob, length, opts) {
  17867. var type = (blob[blob.l++] & 0x60) >> 5;
  17868. blob.l += opts && (opts.biff > 8) ? 12 : (opts.biff < 8 ? 6 : 8);
  17869. return [type];
  17870. }
  17871. /* [MS-XLS] 2.5.198.30 ; [MS-XLSB] 2.5.97.21 */
  17872. function parse_PtgAreaErr3d(blob, length, opts) {
  17873. var type = (blob[blob.l++] & 0x60) >> 5;
  17874. var ixti = blob.read_shift(2);
  17875. var w = 8;
  17876. if(opts) switch(opts.biff) {
  17877. case 5: blob.l += 12; w = 6; break;
  17878. case 12: w = 12; break;
  17879. }
  17880. blob.l += w;
  17881. return [type, ixti];
  17882. }
  17883. /* [MS-XLS] 2.5.198.31 ; [MS-XLSB] 2.5.97.22 */
  17884. function parse_PtgAreaN(blob, length, opts) {
  17885. var type = (blob[blob.l++] & 0x60) >> 5;
  17886. var area = parse_RgceAreaRel(blob, length - 1, opts);
  17887. return [type, area];
  17888. }
  17889. /* [MS-XLS] 2.5.198.32 ; [MS-XLSB] 2.5.97.23 */
  17890. function parse_PtgArray(blob, length, opts) {
  17891. var type = (blob[blob.l++] & 0x60) >> 5;
  17892. blob.l += opts.biff == 2 ? 6 : opts.biff == 12 ? 14 : 7;
  17893. return [type];
  17894. }
  17895. /* [MS-XLS] 2.5.198.33 ; [MS-XLSB] 2.5.97.24 */
  17896. function parse_PtgAttrBaxcel(blob) {
  17897. var bitSemi = blob[blob.l+1] & 0x01; /* 1 = volatile */
  17898. var bitBaxcel = 1;
  17899. blob.l += 4;
  17900. return [bitSemi, bitBaxcel];
  17901. }
  17902. /* [MS-XLS] 2.5.198.34 ; [MS-XLSB] 2.5.97.25 */
  17903. function parse_PtgAttrChoose(blob, length, opts) {
  17904. blob.l +=2;
  17905. var offset = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  17906. var o = [];
  17907. /* offset is 1 less than the number of elements */
  17908. for(var i = 0; i <= offset; ++i) o.push(blob.read_shift(opts && opts.biff == 2 ? 1 : 2));
  17909. return o;
  17910. }
  17911. /* [MS-XLS] 2.5.198.35 ; [MS-XLSB] 2.5.97.26 */
  17912. function parse_PtgAttrGoto(blob, length, opts) {
  17913. var bitGoto = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  17914. blob.l += 2;
  17915. return [bitGoto, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
  17916. }
  17917. /* [MS-XLS] 2.5.198.36 ; [MS-XLSB] 2.5.97.27 */
  17918. function parse_PtgAttrIf(blob, length, opts) {
  17919. var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  17920. blob.l += 2;
  17921. return [bitIf, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
  17922. }
  17923. /* [MS-XLSB] 2.5.97.28 */
  17924. function parse_PtgAttrIfError(blob) {
  17925. var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  17926. blob.l += 2;
  17927. return [bitIf, blob.read_shift(2)];
  17928. }
  17929. /* [MS-XLS] 2.5.198.37 ; [MS-XLSB] 2.5.97.29 */
  17930. function parse_PtgAttrSemi(blob, length, opts) {
  17931. var bitSemi = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  17932. blob.l += opts && opts.biff == 2 ? 3 : 4;
  17933. return [bitSemi];
  17934. }
  17935. /* [MS-XLS] 2.5.198.40 ; [MS-XLSB] 2.5.97.32 */
  17936. function parse_PtgAttrSpaceType(blob) {
  17937. var type = blob.read_shift(1), cch = blob.read_shift(1);
  17938. return [type, cch];
  17939. }
  17940. /* [MS-XLS] 2.5.198.38 ; [MS-XLSB] 2.5.97.30 */
  17941. function parse_PtgAttrSpace(blob) {
  17942. blob.read_shift(2);
  17943. return parse_PtgAttrSpaceType(blob, 2);
  17944. }
  17945. /* [MS-XLS] 2.5.198.39 ; [MS-XLSB] 2.5.97.31 */
  17946. function parse_PtgAttrSpaceSemi(blob) {
  17947. blob.read_shift(2);
  17948. return parse_PtgAttrSpaceType(blob, 2);
  17949. }
  17950. /* [MS-XLS] 2.5.198.84 ; [MS-XLSB] 2.5.97.68 TODO */
  17951. function parse_PtgRef(blob, length, opts) {
  17952. //var ptg = blob[blob.l] & 0x1F;
  17953. var type = (blob[blob.l] & 0x60)>>5;
  17954. blob.l += 1;
  17955. var loc = parse_RgceLoc(blob, 0, opts);
  17956. return [type, loc];
  17957. }
  17958. /* [MS-XLS] 2.5.198.88 ; [MS-XLSB] 2.5.97.72 TODO */
  17959. function parse_PtgRefN(blob, length, opts) {
  17960. var type = (blob[blob.l] & 0x60)>>5;
  17961. blob.l += 1;
  17962. var loc = parse_RgceLocRel(blob, 0, opts);
  17963. return [type, loc];
  17964. }
  17965. /* [MS-XLS] 2.5.198.85 ; [MS-XLSB] 2.5.97.69 TODO */
  17966. function parse_PtgRef3d(blob, length, opts) {
  17967. var type = (blob[blob.l] & 0x60)>>5;
  17968. blob.l += 1;
  17969. var ixti = blob.read_shift(2); // XtiIndex
  17970. if(opts && opts.biff == 5) blob.l += 12;
  17971. var loc = parse_RgceLoc(blob, 0, opts); // TODO: or RgceLocRel
  17972. return [type, ixti, loc];
  17973. }
  17974. /* [MS-XLS] 2.5.198.62 ; [MS-XLSB] 2.5.97.45 TODO */
  17975. function parse_PtgFunc(blob, length, opts) {
  17976. //var ptg = blob[blob.l] & 0x1F;
  17977. var type = (blob[blob.l] & 0x60)>>5;
  17978. blob.l += 1;
  17979. var iftab = blob.read_shift(opts && opts.biff <= 3 ? 1 : 2);
  17980. return [FtabArgc[iftab], Ftab[iftab], type];
  17981. }
  17982. /* [MS-XLS] 2.5.198.63 ; [MS-XLSB] 2.5.97.46 TODO */
  17983. function parse_PtgFuncVar(blob, length, opts) {
  17984. var type = blob[blob.l++];
  17985. var cparams = blob.read_shift(1), tab = opts && opts.biff <= 3 ? [(type == 0x58 ? -1 : 0), blob.read_shift(1)]: parsetab(blob);
  17986. return [cparams, (tab[0] === 0 ? Ftab : Cetab)[tab[1]]];
  17987. }
  17988. function parsetab(blob) {
  17989. return [blob[blob.l+1]>>7, blob.read_shift(2) & 0x7FFF];
  17990. }
  17991. /* [MS-XLS] 2.5.198.41 ; [MS-XLSB] 2.5.97.33 */
  17992. function parse_PtgAttrSum(blob, length, opts) {
  17993. blob.l += opts && opts.biff == 2 ? 3 : 4; return;
  17994. }
  17995. /* [MS-XLS] 2.5.198.58 ; [MS-XLSB] 2.5.97.40 */
  17996. function parse_PtgExp(blob, length, opts) {
  17997. blob.l++;
  17998. if(opts && opts.biff == 12) return [blob.read_shift(4, 'i'), 0];
  17999. var row = blob.read_shift(2);
  18000. var col = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  18001. return [row, col];
  18002. }
  18003. /* [MS-XLS] 2.5.198.57 ; [MS-XLSB] 2.5.97.39 */
  18004. function parse_PtgErr(blob) { blob.l++; return BErr[blob.read_shift(1)]; }
  18005. /* [MS-XLS] 2.5.198.66 ; [MS-XLSB] 2.5.97.49 */
  18006. function parse_PtgInt(blob) { blob.l++; return blob.read_shift(2); }
  18007. /* [MS-XLS] 2.5.198.42 ; [MS-XLSB] 2.5.97.34 */
  18008. function parse_PtgBool(blob) { blob.l++; return blob.read_shift(1)!==0;}
  18009. /* [MS-XLS] 2.5.198.79 ; [MS-XLSB] 2.5.97.63 */
  18010. function parse_PtgNum(blob) { blob.l++; return parse_Xnum(blob, 8); }
  18011. /* [MS-XLS] 2.5.198.89 ; [MS-XLSB] 2.5.97.74 */
  18012. function parse_PtgStr(blob, length, opts) { blob.l++; return parse_ShortXLUnicodeString(blob, length-1, opts); }
  18013. /* [MS-XLS] 2.5.192.112 + 2.5.192.11{3,4,5,6,7} */
  18014. /* [MS-XLSB] 2.5.97.93 + 2.5.97.9{4,5,6,7} */
  18015. function parse_SerAr(blob, biff) {
  18016. var val = [blob.read_shift(1)];
  18017. if(biff == 12) switch(val[0]) {
  18018. case 0x02: val[0] = 0x04; break; /* SerBool */
  18019. case 0x04: val[0] = 0x10; break; /* SerErr */
  18020. case 0x00: val[0] = 0x01; break; /* SerNum */
  18021. case 0x01: val[0] = 0x02; break; /* SerStr */
  18022. }
  18023. switch(val[0]) {
  18024. case 0x04: /* SerBool -- boolean */
  18025. val[1] = parsebool(blob, 1) ? 'TRUE' : 'FALSE';
  18026. if(biff != 12) blob.l += 7; break;
  18027. case 0x25: /* appears to be an alias */
  18028. case 0x10: /* SerErr -- error */
  18029. val[1] = BErr[blob[blob.l]];
  18030. blob.l += ((biff == 12) ? 4 : 8); break;
  18031. case 0x00: /* SerNil -- honestly, I'm not sure how to reproduce this */
  18032. blob.l += 8; break;
  18033. case 0x01: /* SerNum -- Xnum */
  18034. val[1] = parse_Xnum(blob, 8); break;
  18035. case 0x02: /* SerStr -- XLUnicodeString (<256 chars) */
  18036. val[1] = parse_XLUnicodeString2(blob, 0, {biff:biff > 0 && biff < 8 ? 2 : biff}); break;
  18037. default: throw new Error("Bad SerAr: " + val[0]); /* Unreachable */
  18038. }
  18039. return val;
  18040. }
  18041. /* [MS-XLS] 2.5.198.61 ; [MS-XLSB] 2.5.97.44 */
  18042. function parse_PtgExtraMem(blob, cce, opts) {
  18043. var count = blob.read_shift((opts.biff == 12) ? 4 : 2);
  18044. var out = [];
  18045. for(var i = 0; i != count; ++i) out.push(((opts.biff == 12) ? parse_UncheckedRfX : parse_Ref8U)(blob, 8));
  18046. return out;
  18047. }
  18048. /* [MS-XLS] 2.5.198.59 ; [MS-XLSB] 2.5.97.41 */
  18049. function parse_PtgExtraArray(blob, length, opts) {
  18050. var rows = 0, cols = 0;
  18051. if(opts.biff == 12) {
  18052. rows = blob.read_shift(4); // DRw
  18053. cols = blob.read_shift(4); // DCol
  18054. } else {
  18055. cols = 1 + blob.read_shift(1); //DColByteU
  18056. rows = 1 + blob.read_shift(2); //DRw
  18057. }
  18058. if(opts.biff >= 2 && opts.biff < 8) { --rows; if(--cols == 0) cols = 0x100; }
  18059. // $FlowIgnore
  18060. for(var i = 0, o = []; i != rows && (o[i] = []); ++i)
  18061. for(var j = 0; j != cols; ++j) o[i][j] = parse_SerAr(blob, opts.biff);
  18062. return o;
  18063. }
  18064. /* [MS-XLS] 2.5.198.76 ; [MS-XLSB] 2.5.97.60 */
  18065. function parse_PtgName(blob, length, opts) {
  18066. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18067. var w = (!opts || (opts.biff >= 8)) ? 4 : 2;
  18068. var nameindex = blob.read_shift(w);
  18069. switch(opts.biff) {
  18070. case 2: blob.l += 5; break;
  18071. case 3: case 4: blob.l += 8; break;
  18072. case 5: blob.l += 12; break;
  18073. }
  18074. return [type, 0, nameindex];
  18075. }
  18076. /* [MS-XLS] 2.5.198.77 ; [MS-XLSB] 2.5.97.61 */
  18077. function parse_PtgNameX(blob, length, opts) {
  18078. if(opts.biff == 5) return parse_PtgNameX_BIFF5(blob, length, opts);
  18079. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18080. var ixti = blob.read_shift(2); // XtiIndex
  18081. var nameindex = blob.read_shift(4);
  18082. return [type, ixti, nameindex];
  18083. }
  18084. function parse_PtgNameX_BIFF5(blob) {
  18085. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18086. var ixti = blob.read_shift(2, 'i'); // XtiIndex
  18087. blob.l += 8;
  18088. var nameindex = blob.read_shift(2);
  18089. blob.l += 12;
  18090. return [type, ixti, nameindex];
  18091. }
  18092. /* [MS-XLS] 2.5.198.70 ; [MS-XLSB] 2.5.97.54 */
  18093. function parse_PtgMemArea(blob, length, opts) {
  18094. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18095. blob.l += (opts && opts.biff == 2 ? 3 : 4);
  18096. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  18097. return [type, cce];
  18098. }
  18099. /* [MS-XLS] 2.5.198.72 ; [MS-XLSB] 2.5.97.56 */
  18100. function parse_PtgMemFunc(blob, length, opts) {
  18101. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18102. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  18103. return [type, cce];
  18104. }
  18105. /* [MS-XLS] 2.5.198.86 ; [MS-XLSB] 2.5.97.69 */
  18106. function parse_PtgRefErr(blob, length, opts) {
  18107. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18108. blob.l += 4;
  18109. if(opts.biff < 8) blob.l--;
  18110. if(opts.biff == 12) blob.l += 2;
  18111. return [type];
  18112. }
  18113. /* [MS-XLS] 2.5.198.87 ; [MS-XLSB] 2.5.97.71 */
  18114. function parse_PtgRefErr3d(blob, length, opts) {
  18115. var type = (blob[blob.l++] & 0x60) >> 5;
  18116. var ixti = blob.read_shift(2);
  18117. var w = 4;
  18118. if(opts) switch(opts.biff) {
  18119. case 5: w = 15; break;
  18120. case 12: w = 6; break;
  18121. }
  18122. blob.l += w;
  18123. return [type, ixti];
  18124. }
  18125. /* [MS-XLS] 2.5.198.71 ; [MS-XLSB] 2.5.97.55 */
  18126. var parse_PtgMemErr = parsenoop;
  18127. /* [MS-XLS] 2.5.198.73 ; [MS-XLSB] 2.5.97.57 */
  18128. var parse_PtgMemNoMem = parsenoop;
  18129. /* [MS-XLS] 2.5.198.92 */
  18130. var parse_PtgTbl = parsenoop;
  18131. function parse_PtgElfLoc(blob, length, opts) {
  18132. blob.l += 2;
  18133. return [parse_RgceElfLoc(blob, 4, opts)];
  18134. }
  18135. function parse_PtgElfNoop(blob) {
  18136. blob.l += 6;
  18137. return [];
  18138. }
  18139. /* [MS-XLS] 2.5.198.46 */
  18140. var parse_PtgElfCol = parse_PtgElfLoc;
  18141. /* [MS-XLS] 2.5.198.47 */
  18142. var parse_PtgElfColS = parse_PtgElfNoop;
  18143. /* [MS-XLS] 2.5.198.48 */
  18144. var parse_PtgElfColSV = parse_PtgElfNoop;
  18145. /* [MS-XLS] 2.5.198.49 */
  18146. var parse_PtgElfColV = parse_PtgElfLoc;
  18147. /* [MS-XLS] 2.5.198.50 */
  18148. function parse_PtgElfLel(blob) {
  18149. blob.l += 2;
  18150. return [parseuint16(blob), blob.read_shift(2) & 0x01];
  18151. }
  18152. /* [MS-XLS] 2.5.198.51 */
  18153. var parse_PtgElfRadical = parse_PtgElfLoc;
  18154. /* [MS-XLS] 2.5.198.52 */
  18155. var parse_PtgElfRadicalLel = parse_PtgElfLel;
  18156. /* [MS-XLS] 2.5.198.53 */
  18157. var parse_PtgElfRadicalS = parse_PtgElfNoop;
  18158. /* [MS-XLS] 2.5.198.54 */
  18159. var parse_PtgElfRw = parse_PtgElfLoc;
  18160. /* [MS-XLS] 2.5.198.55 */
  18161. var parse_PtgElfRwV = parse_PtgElfLoc;
  18162. /* [MS-XLSB] 2.5.97.52 TODO */
  18163. var PtgListRT = [
  18164. "Data",
  18165. "All",
  18166. "Headers",
  18167. "??",
  18168. "?Data2",
  18169. "??",
  18170. "?DataHeaders",
  18171. "??",
  18172. "Totals",
  18173. "??",
  18174. "??",
  18175. "??",
  18176. "?DataTotals",
  18177. "??",
  18178. "??",
  18179. "??",
  18180. "?Current"
  18181. ];
  18182. function parse_PtgList(blob) {
  18183. blob.l += 2;
  18184. var ixti = blob.read_shift(2);
  18185. var flags = blob.read_shift(2);
  18186. var idx = blob.read_shift(4);
  18187. var c = blob.read_shift(2);
  18188. var C = blob.read_shift(2);
  18189. var rt = PtgListRT[(flags >> 2) & 0x1F];
  18190. return {ixti: ixti, coltype:(flags&0x3), rt:rt, idx:idx, c:c, C:C};
  18191. }
  18192. /* [MS-XLS] 2.5.198.91 ; [MS-XLSB] 2.5.97.76 */
  18193. function parse_PtgSxName(blob) {
  18194. blob.l += 2;
  18195. return [blob.read_shift(4)];
  18196. }
  18197. /* [XLS] old spec */
  18198. function parse_PtgSheet(blob, length, opts) {
  18199. blob.l += 5;
  18200. blob.l += 2;
  18201. blob.l += (opts.biff == 2 ? 1 : 4);
  18202. return ["PTGSHEET"];
  18203. }
  18204. function parse_PtgEndSheet(blob, length, opts) {
  18205. blob.l += (opts.biff == 2 ? 4 : 5);
  18206. return ["PTGENDSHEET"];
  18207. }
  18208. function parse_PtgMemAreaN(blob) {
  18209. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18210. var cce = blob.read_shift(2);
  18211. return [type, cce];
  18212. }
  18213. function parse_PtgMemNoMemN(blob) {
  18214. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18215. var cce = blob.read_shift(2);
  18216. return [type, cce];
  18217. }
  18218. function parse_PtgAttrNoop(blob) {
  18219. blob.l += 4;
  18220. return [0, 0];
  18221. }
  18222. /* [MS-XLS] 2.5.198.25 ; [MS-XLSB] 2.5.97.16 */
  18223. var PtgTypes = {
  18224. 0x01: { n:'PtgExp', f:parse_PtgExp },
  18225. 0x02: { n:'PtgTbl', f:parse_PtgTbl },
  18226. 0x03: { n:'PtgAdd', f:parseread1 },
  18227. 0x04: { n:'PtgSub', f:parseread1 },
  18228. 0x05: { n:'PtgMul', f:parseread1 },
  18229. 0x06: { n:'PtgDiv', f:parseread1 },
  18230. 0x07: { n:'PtgPower', f:parseread1 },
  18231. 0x08: { n:'PtgConcat', f:parseread1 },
  18232. 0x09: { n:'PtgLt', f:parseread1 },
  18233. 0x0A: { n:'PtgLe', f:parseread1 },
  18234. 0x0B: { n:'PtgEq', f:parseread1 },
  18235. 0x0C: { n:'PtgGe', f:parseread1 },
  18236. 0x0D: { n:'PtgGt', f:parseread1 },
  18237. 0x0E: { n:'PtgNe', f:parseread1 },
  18238. 0x0F: { n:'PtgIsect', f:parseread1 },
  18239. 0x10: { n:'PtgUnion', f:parseread1 },
  18240. 0x11: { n:'PtgRange', f:parseread1 },
  18241. 0x12: { n:'PtgUplus', f:parseread1 },
  18242. 0x13: { n:'PtgUminus', f:parseread1 },
  18243. 0x14: { n:'PtgPercent', f:parseread1 },
  18244. 0x15: { n:'PtgParen', f:parseread1 },
  18245. 0x16: { n:'PtgMissArg', f:parseread1 },
  18246. 0x17: { n:'PtgStr', f:parse_PtgStr },
  18247. 0x1A: { n:'PtgSheet', f:parse_PtgSheet },
  18248. 0x1B: { n:'PtgEndSheet', f:parse_PtgEndSheet },
  18249. 0x1C: { n:'PtgErr', f:parse_PtgErr },
  18250. 0x1D: { n:'PtgBool', f:parse_PtgBool },
  18251. 0x1E: { n:'PtgInt', f:parse_PtgInt },
  18252. 0x1F: { n:'PtgNum', f:parse_PtgNum },
  18253. 0x20: { n:'PtgArray', f:parse_PtgArray },
  18254. 0x21: { n:'PtgFunc', f:parse_PtgFunc },
  18255. 0x22: { n:'PtgFuncVar', f:parse_PtgFuncVar },
  18256. 0x23: { n:'PtgName', f:parse_PtgName },
  18257. 0x24: { n:'PtgRef', f:parse_PtgRef },
  18258. 0x25: { n:'PtgArea', f:parse_PtgArea },
  18259. 0x26: { n:'PtgMemArea', f:parse_PtgMemArea },
  18260. 0x27: { n:'PtgMemErr', f:parse_PtgMemErr },
  18261. 0x28: { n:'PtgMemNoMem', f:parse_PtgMemNoMem },
  18262. 0x29: { n:'PtgMemFunc', f:parse_PtgMemFunc },
  18263. 0x2A: { n:'PtgRefErr', f:parse_PtgRefErr },
  18264. 0x2B: { n:'PtgAreaErr', f:parse_PtgAreaErr },
  18265. 0x2C: { n:'PtgRefN', f:parse_PtgRefN },
  18266. 0x2D: { n:'PtgAreaN', f:parse_PtgAreaN },
  18267. 0x2E: { n:'PtgMemAreaN', f:parse_PtgMemAreaN },
  18268. 0x2F: { n:'PtgMemNoMemN', f:parse_PtgMemNoMemN },
  18269. 0x39: { n:'PtgNameX', f:parse_PtgNameX },
  18270. 0x3A: { n:'PtgRef3d', f:parse_PtgRef3d },
  18271. 0x3B: { n:'PtgArea3d', f:parse_PtgArea3d },
  18272. 0x3C: { n:'PtgRefErr3d', f:parse_PtgRefErr3d },
  18273. 0x3D: { n:'PtgAreaErr3d', f:parse_PtgAreaErr3d },
  18274. 0xFF: {}
  18275. };
  18276. /* These are duplicated in the PtgTypes table */
  18277. var PtgDupes = {
  18278. 0x40: 0x20, 0x60: 0x20,
  18279. 0x41: 0x21, 0x61: 0x21,
  18280. 0x42: 0x22, 0x62: 0x22,
  18281. 0x43: 0x23, 0x63: 0x23,
  18282. 0x44: 0x24, 0x64: 0x24,
  18283. 0x45: 0x25, 0x65: 0x25,
  18284. 0x46: 0x26, 0x66: 0x26,
  18285. 0x47: 0x27, 0x67: 0x27,
  18286. 0x48: 0x28, 0x68: 0x28,
  18287. 0x49: 0x29, 0x69: 0x29,
  18288. 0x4A: 0x2A, 0x6A: 0x2A,
  18289. 0x4B: 0x2B, 0x6B: 0x2B,
  18290. 0x4C: 0x2C, 0x6C: 0x2C,
  18291. 0x4D: 0x2D, 0x6D: 0x2D,
  18292. 0x4E: 0x2E, 0x6E: 0x2E,
  18293. 0x4F: 0x2F, 0x6F: 0x2F,
  18294. 0x58: 0x22, 0x78: 0x22,
  18295. 0x59: 0x39, 0x79: 0x39,
  18296. 0x5A: 0x3A, 0x7A: 0x3A,
  18297. 0x5B: 0x3B, 0x7B: 0x3B,
  18298. 0x5C: 0x3C, 0x7C: 0x3C,
  18299. 0x5D: 0x3D, 0x7D: 0x3D
  18300. };
  18301. (function(){for(var y in PtgDupes) PtgTypes[y] = PtgTypes[PtgDupes[y]];})();
  18302. var Ptg18 = {
  18303. 0x01: { n:'PtgElfLel', f:parse_PtgElfLel },
  18304. 0x02: { n:'PtgElfRw', f:parse_PtgElfRw },
  18305. 0x03: { n:'PtgElfCol', f:parse_PtgElfCol },
  18306. 0x06: { n:'PtgElfRwV', f:parse_PtgElfRwV },
  18307. 0x07: { n:'PtgElfColV', f:parse_PtgElfColV },
  18308. 0x0A: { n:'PtgElfRadical', f:parse_PtgElfRadical },
  18309. 0x0B: { n:'PtgElfRadicalS', f:parse_PtgElfRadicalS },
  18310. 0x0D: { n:'PtgElfColS', f:parse_PtgElfColS },
  18311. 0x0F: { n:'PtgElfColSV', f:parse_PtgElfColSV },
  18312. 0x10: { n:'PtgElfRadicalLel', f:parse_PtgElfRadicalLel },
  18313. 0x19: { n:'PtgList', f:parse_PtgList },
  18314. 0x1D: { n:'PtgSxName', f:parse_PtgSxName },
  18315. 0xFF: {}
  18316. };
  18317. var Ptg19 = {
  18318. 0x00: { n:'PtgAttrNoop', f:parse_PtgAttrNoop },
  18319. 0x01: { n:'PtgAttrSemi', f:parse_PtgAttrSemi },
  18320. 0x02: { n:'PtgAttrIf', f:parse_PtgAttrIf },
  18321. 0x04: { n:'PtgAttrChoose', f:parse_PtgAttrChoose },
  18322. 0x08: { n:'PtgAttrGoto', f:parse_PtgAttrGoto },
  18323. 0x10: { n:'PtgAttrSum', f:parse_PtgAttrSum },
  18324. 0x20: { n:'PtgAttrBaxcel', f:parse_PtgAttrBaxcel },
  18325. 0x40: { n:'PtgAttrSpace', f:parse_PtgAttrSpace },
  18326. 0x41: { n:'PtgAttrSpaceSemi', f:parse_PtgAttrSpaceSemi },
  18327. 0x80: { n:'PtgAttrIfError', f:parse_PtgAttrIfError },
  18328. 0xFF: {}
  18329. };
  18330. Ptg19[0x21] = Ptg19[0x20];
  18331. /* [MS-XLS] 2.5.198.103 ; [MS-XLSB] 2.5.97.87 */
  18332. function parse_RgbExtra(blob, length, rgce, opts) {
  18333. if(opts.biff < 8) return parsenoop(blob, length);
  18334. var target = blob.l + length;
  18335. var o = [];
  18336. for(var i = 0; i !== rgce.length; ++i) {
  18337. switch(rgce[i][0]) {
  18338. case 'PtgArray': /* PtgArray -> PtgExtraArray */
  18339. rgce[i][1] = parse_PtgExtraArray(blob, 0, opts);
  18340. o.push(rgce[i][1]);
  18341. break;
  18342. case 'PtgMemArea': /* PtgMemArea -> PtgExtraMem */
  18343. rgce[i][2] = parse_PtgExtraMem(blob, rgce[i][1], opts);
  18344. o.push(rgce[i][2]);
  18345. break;
  18346. case 'PtgExp': /* PtgExp -> PtgExtraCol */
  18347. if(opts && opts.biff == 12) {
  18348. rgce[i][1][1] = blob.read_shift(4);
  18349. o.push(rgce[i][1]);
  18350. } break;
  18351. case 'PtgList': /* TODO: PtgList -> PtgExtraList */
  18352. case 'PtgElfRadicalS': /* TODO: PtgElfRadicalS -> PtgExtraElf */
  18353. case 'PtgElfColS': /* TODO: PtgElfColS -> PtgExtraElf */
  18354. case 'PtgElfColSV': /* TODO: PtgElfColSV -> PtgExtraElf */
  18355. throw "Unsupported " + rgce[i][0];
  18356. default: break;
  18357. }
  18358. }
  18359. length = target - blob.l;
  18360. /* note: this is technically an error but Excel disregards */
  18361. //if(target !== blob.l && blob.l !== target - length) throw new Error(target + " != " + blob.l);
  18362. if(length !== 0) o.push(parsenoop(blob, length));
  18363. return o;
  18364. }
  18365. /* [MS-XLS] 2.5.198.104 ; [MS-XLSB] 2.5.97.88 */
  18366. function parse_Rgce(blob, length, opts) {
  18367. var target = blob.l + length;
  18368. var R, id, ptgs = [];
  18369. while(target != blob.l) {
  18370. length = target - blob.l;
  18371. id = blob[blob.l];
  18372. R = PtgTypes[id];
  18373. if(id === 0x18 || id === 0x19) R = (id === 0x18 ? Ptg18 : Ptg19)[blob[blob.l + 1]];
  18374. if(!R || !R.f) { /*ptgs.push*/(parsenoop(blob, length)); }
  18375. else { ptgs.push([R.n, R.f(blob, length, opts)]); }
  18376. }
  18377. return ptgs;
  18378. }
  18379. function stringify_array(f) {
  18380. var o = [];
  18381. for(var i = 0; i < f.length; ++i) {
  18382. var x = f[i], r = [];
  18383. for(var j = 0; j < x.length; ++j) {
  18384. var y = x[j];
  18385. if(y) switch(y[0]) {
  18386. // TODO: handle embedded quotes
  18387. case 0x02:
  18388. r.push('"' + y[1].replace(/"/g,'""') + '"'); break;
  18389. default: r.push(y[1]);
  18390. } else r.push("");
  18391. }
  18392. o.push(r.join(","));
  18393. }
  18394. return o.join(";");
  18395. }
  18396. /* [MS-XLS] 2.2.2 ; [MS-XLSB] 2.2.2 TODO */
  18397. var PtgBinOp = {
  18398. PtgAdd: "+",
  18399. PtgConcat: "&",
  18400. PtgDiv: "/",
  18401. PtgEq: "=",
  18402. PtgGe: ">=",
  18403. PtgGt: ">",
  18404. PtgLe: "<=",
  18405. PtgLt: "<",
  18406. PtgMul: "*",
  18407. PtgNe: "<>",
  18408. PtgPower: "^",
  18409. PtgSub: "-"
  18410. };
  18411. // List of invalid characters needs to be tested further
  18412. var quoteCharacters = new RegExp(/[^\w\u4E00-\u9FFF\u3040-\u30FF]/);
  18413. function formula_quote_sheet_name(sname, opts) {
  18414. if(!sname && !(opts && opts.biff <= 5 && opts.biff >= 2)) throw new Error("empty sheet name");
  18415. if (quoteCharacters.test(sname)) return "'" + sname + "'";
  18416. return sname;
  18417. }
  18418. function get_ixti_raw(supbooks, ixti, opts) {
  18419. if(!supbooks) return "SH33TJSERR0";
  18420. if(opts.biff > 8 && (!supbooks.XTI || !supbooks.XTI[ixti])) return supbooks.SheetNames[ixti];
  18421. if(!supbooks.XTI) return "SH33TJSERR6";
  18422. var XTI = supbooks.XTI[ixti];
  18423. if(opts.biff < 8) {
  18424. if(ixti > 10000) ixti-= 65536;
  18425. if(ixti < 0) ixti = -ixti;
  18426. return ixti == 0 ? "" : supbooks.XTI[ixti - 1];
  18427. }
  18428. if(!XTI) return "SH33TJSERR1";
  18429. var o = "";
  18430. if(opts.biff > 8) switch(supbooks[XTI[0]][0]) {
  18431. case 0x0165: /* 'BrtSupSelf' */
  18432. o = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]];
  18433. return XTI[1] == XTI[2] ? o : o + ":" + supbooks.SheetNames[XTI[2]];
  18434. case 0x0166: /* 'BrtSupSame' */
  18435. if(opts.SID != null) return supbooks.SheetNames[opts.SID];
  18436. return "SH33TJSSAME" + supbooks[XTI[0]][0];
  18437. case 0x0163: /* 'BrtSupBookSrc' */
  18438. /* falls through */
  18439. default: return "SH33TJSSRC" + supbooks[XTI[0]][0];
  18440. }
  18441. switch(supbooks[XTI[0]][0][0]) {
  18442. case 0x0401:
  18443. o = XTI[1] == -1 ? "#REF" : (supbooks.SheetNames[XTI[1]] || "SH33TJSERR3");
  18444. return XTI[1] == XTI[2] ? o : o + ":" + supbooks.SheetNames[XTI[2]];
  18445. case 0x3A01: return supbooks[XTI[0]].slice(1).map(function(name) { return name.Name; }).join(";;"); //return "SH33TJSERR8";
  18446. default:
  18447. if(!supbooks[XTI[0]][0][3]) return "SH33TJSERR2";
  18448. o = XTI[1] == -1 ? "#REF" : (supbooks[XTI[0]][0][3][XTI[1]] || "SH33TJSERR4");
  18449. return XTI[1] == XTI[2] ? o : o + ":" + supbooks[XTI[0]][0][3][XTI[2]];
  18450. }
  18451. }
  18452. function get_ixti(supbooks, ixti, opts) {
  18453. return formula_quote_sheet_name(get_ixti_raw(supbooks, ixti, opts), opts);
  18454. }
  18455. function stringify_formula(formula/*Array<any>*/, range, cell, supbooks, opts) {
  18456. var biff = (opts && opts.biff) || 8;
  18457. var _range = /*range != null ? range :*/ {s:{c:0, r:0},e:{c:0, r:0}};
  18458. var stack = [], e1, e2, c, ixti=0, nameidx=0, r, sname="";
  18459. if(!formula[0] || !formula[0][0]) return "";
  18460. var last_sp = -1, sp = "";
  18461. for(var ff = 0, fflen = formula[0].length; ff < fflen; ++ff) {
  18462. var f = formula[0][ff];
  18463. switch(f[0]) {
  18464. case 'PtgUminus': /* [MS-XLS] 2.5.198.93 */
  18465. stack.push("-" + stack.pop()); break;
  18466. case 'PtgUplus': /* [MS-XLS] 2.5.198.95 */
  18467. stack.push("+" + stack.pop()); break;
  18468. case 'PtgPercent': /* [MS-XLS] 2.5.198.81 */
  18469. stack.push(stack.pop() + "%"); break;
  18470. case 'PtgAdd': /* [MS-XLS] 2.5.198.26 */
  18471. case 'PtgConcat': /* [MS-XLS] 2.5.198.43 */
  18472. case 'PtgDiv': /* [MS-XLS] 2.5.198.45 */
  18473. case 'PtgEq': /* [MS-XLS] 2.5.198.56 */
  18474. case 'PtgGe': /* [MS-XLS] 2.5.198.64 */
  18475. case 'PtgGt': /* [MS-XLS] 2.5.198.65 */
  18476. case 'PtgLe': /* [MS-XLS] 2.5.198.68 */
  18477. case 'PtgLt': /* [MS-XLS] 2.5.198.69 */
  18478. case 'PtgMul': /* [MS-XLS] 2.5.198.75 */
  18479. case 'PtgNe': /* [MS-XLS] 2.5.198.78 */
  18480. case 'PtgPower': /* [MS-XLS] 2.5.198.82 */
  18481. case 'PtgSub': /* [MS-XLS] 2.5.198.90 */
  18482. e1 = stack.pop(); e2 = stack.pop();
  18483. if(last_sp >= 0) {
  18484. switch(formula[0][last_sp][1][0]) {
  18485. case 0:
  18486. // $FlowIgnore
  18487. sp = fill(" ", formula[0][last_sp][1][1]); break;
  18488. case 1:
  18489. // $FlowIgnore
  18490. sp = fill("\r", formula[0][last_sp][1][1]); break;
  18491. default:
  18492. sp = "";
  18493. // $FlowIgnore
  18494. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
  18495. }
  18496. e2 = e2 + sp;
  18497. last_sp = -1;
  18498. }
  18499. stack.push(e2+PtgBinOp[f[0]]+e1);
  18500. break;
  18501. case 'PtgIsect': /* [MS-XLS] 2.5.198.67 */
  18502. e1 = stack.pop(); e2 = stack.pop();
  18503. stack.push(e2+" "+e1);
  18504. break;
  18505. case 'PtgUnion': /* [MS-XLS] 2.5.198.94 */
  18506. e1 = stack.pop(); e2 = stack.pop();
  18507. stack.push(e2+","+e1);
  18508. break;
  18509. case 'PtgRange': /* [MS-XLS] 2.5.198.83 */
  18510. e1 = stack.pop(); e2 = stack.pop();
  18511. stack.push(e2+":"+e1);
  18512. break;
  18513. case 'PtgAttrChoose': /* [MS-XLS] 2.5.198.34 */
  18514. break;
  18515. case 'PtgAttrGoto': /* [MS-XLS] 2.5.198.35 */
  18516. break;
  18517. case 'PtgAttrIf': /* [MS-XLS] 2.5.198.36 */
  18518. break;
  18519. case 'PtgAttrIfError': /* [MS-XLSB] 2.5.97.28 */
  18520. break;
  18521. case 'PtgRef': /* [MS-XLS] 2.5.198.84 */
  18522. c = shift_cell_xls((f[1][1]), _range, opts);
  18523. stack.push(encode_cell_xls(c, biff));
  18524. break;
  18525. case 'PtgRefN': /* [MS-XLS] 2.5.198.88 */
  18526. c = cell ? shift_cell_xls((f[1][1]), cell, opts) : (f[1][1]);
  18527. stack.push(encode_cell_xls(c, biff));
  18528. break;
  18529. case 'PtgRef3d': /* [MS-XLS] 2.5.198.85 */
  18530. ixti = f[1][1]; c = shift_cell_xls((f[1][2]), _range, opts);
  18531. sname = get_ixti(supbooks, ixti, opts);
  18532. var w = sname; /* IE9 fails on defined names */ // eslint-disable-line no-unused-vars
  18533. stack.push(sname + "!" + encode_cell_xls(c, biff));
  18534. break;
  18535. case 'PtgFunc': /* [MS-XLS] 2.5.198.62 */
  18536. case 'PtgFuncVar': /* [MS-XLS] 2.5.198.63 */
  18537. /* f[1] = [argc, func, type] */
  18538. var argc = (f[1][0]), func = (f[1][1]);
  18539. if(!argc) argc = 0;
  18540. argc &= 0x7F;
  18541. var args = argc == 0 ? [] : stack.slice(-argc);
  18542. stack.length -= argc;
  18543. if(func === 'User') func = args.shift();
  18544. stack.push(func + "(" + args.join(",") + ")");
  18545. break;
  18546. case 'PtgBool': /* [MS-XLS] 2.5.198.42 */
  18547. stack.push(f[1] ? "TRUE" : "FALSE"); break;
  18548. case 'PtgInt': /* [MS-XLS] 2.5.198.66 */
  18549. stack.push(f[1]); break;
  18550. case 'PtgNum': /* [MS-XLS] 2.5.198.79 TODO: precision? */
  18551. stack.push(String(f[1])); break;
  18552. case 'PtgStr': /* [MS-XLS] 2.5.198.89 */
  18553. // $FlowIgnore
  18554. stack.push('"' + f[1].replace(/"/g, '""') + '"'); break;
  18555. case 'PtgErr': /* [MS-XLS] 2.5.198.57 */
  18556. stack.push(f[1]); break;
  18557. case 'PtgAreaN': /* [MS-XLS] 2.5.198.31 TODO */
  18558. r = shift_range_xls(f[1][1], cell ? {s:cell} : _range, opts);
  18559. stack.push(encode_range_xls((r), opts));
  18560. break;
  18561. case 'PtgArea': /* [MS-XLS] 2.5.198.27 TODO: fixed points */
  18562. r = shift_range_xls(f[1][1], _range, opts);
  18563. stack.push(encode_range_xls((r), opts));
  18564. break;
  18565. case 'PtgArea3d': /* [MS-XLS] 2.5.198.28 TODO */
  18566. ixti = f[1][1]; r = f[1][2];
  18567. sname = get_ixti(supbooks, ixti, opts);
  18568. stack.push(sname + "!" + encode_range_xls((r), opts));
  18569. break;
  18570. case 'PtgAttrSum': /* [MS-XLS] 2.5.198.41 */
  18571. stack.push("SUM(" + stack.pop() + ")");
  18572. break;
  18573. case 'PtgAttrBaxcel': /* [MS-XLS] 2.5.198.33 */
  18574. case 'PtgAttrSemi': /* [MS-XLS] 2.5.198.37 */
  18575. break;
  18576. case 'PtgName': /* [MS-XLS] 2.5.198.76 ; [MS-XLSB] 2.5.97.60 TODO: revisions */
  18577. /* f[1] = type, 0, nameindex */
  18578. nameidx = (f[1][2]);
  18579. var lbl = (supbooks.names||[])[nameidx-1] || (supbooks[0]||[])[nameidx];
  18580. var name = lbl ? lbl.Name : "SH33TJSNAME" + String(nameidx);
  18581. if(name in XLSXFutureFunctions) name = XLSXFutureFunctions[name];
  18582. stack.push(name);
  18583. break;
  18584. case 'PtgNameX': /* [MS-XLS] 2.5.198.77 ; [MS-XLSB] 2.5.97.61 TODO: revisions */
  18585. /* f[1] = type, ixti, nameindex */
  18586. var bookidx = (f[1][1]); nameidx = (f[1][2]); var externbook;
  18587. /* TODO: Properly handle missing values -- this should be using get_ixti_raw primarily */
  18588. if(opts.biff <= 5) {
  18589. if(bookidx < 0) bookidx = -bookidx;
  18590. if(supbooks[bookidx]) externbook = supbooks[bookidx][nameidx];
  18591. } else {
  18592. var o = "";
  18593. if(((supbooks[bookidx]||[])[0]||[])[0] == 0x3A01){/* empty */}
  18594. else if(((supbooks[bookidx]||[])[0]||[])[0] == 0x0401){
  18595. if(supbooks[bookidx][nameidx] && supbooks[bookidx][nameidx].itab > 0) {
  18596. o = supbooks.SheetNames[supbooks[bookidx][nameidx].itab-1] + "!";
  18597. }
  18598. }
  18599. else o = supbooks.SheetNames[nameidx-1]+ "!";
  18600. if(supbooks[bookidx] && supbooks[bookidx][nameidx]) o += supbooks[bookidx][nameidx].Name;
  18601. else if(supbooks[0] && supbooks[0][nameidx]) o += supbooks[0][nameidx].Name;
  18602. else {
  18603. var ixtidata = get_ixti_raw(supbooks, bookidx, opts).split(";;");
  18604. if(ixtidata[nameidx - 1]) o = ixtidata[nameidx - 1]; // TODO: confirm this is correct
  18605. else o += "SH33TJSERRX";
  18606. }
  18607. stack.push(o);
  18608. break;
  18609. }
  18610. if(!externbook) externbook = {Name: "SH33TJSERRY"};
  18611. stack.push(externbook.Name);
  18612. break;
  18613. case 'PtgParen': /* [MS-XLS] 2.5.198.80 */
  18614. var lp = '(', rp = ')';
  18615. if(last_sp >= 0) {
  18616. sp = "";
  18617. switch(formula[0][last_sp][1][0]) {
  18618. // $FlowIgnore
  18619. case 2: lp = fill(" ", formula[0][last_sp][1][1]) + lp; break;
  18620. // $FlowIgnore
  18621. case 3: lp = fill("\r", formula[0][last_sp][1][1]) + lp; break;
  18622. // $FlowIgnore
  18623. case 4: rp = fill(" ", formula[0][last_sp][1][1]) + rp; break;
  18624. // $FlowIgnore
  18625. case 5: rp = fill("\r", formula[0][last_sp][1][1]) + rp; break;
  18626. default:
  18627. // $FlowIgnore
  18628. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
  18629. }
  18630. last_sp = -1;
  18631. }
  18632. stack.push(lp + stack.pop() + rp); break;
  18633. case 'PtgRefErr': /* [MS-XLS] 2.5.198.86 */
  18634. stack.push('#REF!'); break;
  18635. case 'PtgRefErr3d': /* [MS-XLS] 2.5.198.87 */
  18636. stack.push('#REF!'); break;
  18637. case 'PtgExp': /* [MS-XLS] 2.5.198.58 TODO */
  18638. c = {c:(f[1][1]),r:(f[1][0])};
  18639. var q = ({c: cell.c, r:cell.r});
  18640. if(supbooks.sharedf[encode_cell(c)]) {
  18641. var parsedf = (supbooks.sharedf[encode_cell(c)]);
  18642. stack.push(stringify_formula(parsedf, _range, q, supbooks, opts));
  18643. }
  18644. else {
  18645. var fnd = false;
  18646. for(e1=0;e1!=supbooks.arrayf.length; ++e1) {
  18647. /* TODO: should be something like range_has */
  18648. e2 = supbooks.arrayf[e1];
  18649. if(c.c < e2[0].s.c || c.c > e2[0].e.c) continue;
  18650. if(c.r < e2[0].s.r || c.r > e2[0].e.r) continue;
  18651. stack.push(stringify_formula(e2[1], _range, q, supbooks, opts));
  18652. fnd = true;
  18653. break;
  18654. }
  18655. if(!fnd) stack.push(f[1]);
  18656. }
  18657. break;
  18658. case 'PtgArray': /* [MS-XLS] 2.5.198.32 TODO */
  18659. stack.push("{" + stringify_array(f[1]) + "}");
  18660. break;
  18661. case 'PtgMemArea': /* [MS-XLS] 2.5.198.70 TODO: confirm this is a non-display */
  18662. //stack.push("(" + f[2].map(encode_range).join(",") + ")");
  18663. break;
  18664. case 'PtgAttrSpace': /* [MS-XLS] 2.5.198.38 */
  18665. case 'PtgAttrSpaceSemi': /* [MS-XLS] 2.5.198.39 */
  18666. last_sp = ff;
  18667. break;
  18668. case 'PtgTbl': /* [MS-XLS] 2.5.198.92 TODO */
  18669. break;
  18670. case 'PtgMemErr': /* [MS-XLS] 2.5.198.71 */
  18671. break;
  18672. case 'PtgMissArg': /* [MS-XLS] 2.5.198.74 */
  18673. stack.push("");
  18674. break;
  18675. case 'PtgAreaErr': /* [MS-XLS] 2.5.198.29 */
  18676. stack.push("#REF!"); break;
  18677. case 'PtgAreaErr3d': /* [MS-XLS] 2.5.198.30 */
  18678. stack.push("#REF!"); break;
  18679. case 'PtgList': /* [MS-XLSB] 2.5.97.52 */
  18680. // $FlowIgnore
  18681. stack.push("Table" + f[1].idx + "[#" + f[1].rt + "]");
  18682. break;
  18683. case 'PtgMemAreaN':
  18684. case 'PtgMemNoMemN':
  18685. case 'PtgAttrNoop':
  18686. case 'PtgSheet':
  18687. case 'PtgEndSheet':
  18688. break;
  18689. case 'PtgMemFunc': /* [MS-XLS] 2.5.198.72 TODO */
  18690. break;
  18691. case 'PtgMemNoMem': /* [MS-XLS] 2.5.198.73 TODO */
  18692. break;
  18693. case 'PtgElfCol': /* [MS-XLS] 2.5.198.46 */
  18694. case 'PtgElfColS': /* [MS-XLS] 2.5.198.47 */
  18695. case 'PtgElfColSV': /* [MS-XLS] 2.5.198.48 */
  18696. case 'PtgElfColV': /* [MS-XLS] 2.5.198.49 */
  18697. case 'PtgElfLel': /* [MS-XLS] 2.5.198.50 */
  18698. case 'PtgElfRadical': /* [MS-XLS] 2.5.198.51 */
  18699. case 'PtgElfRadicalLel': /* [MS-XLS] 2.5.198.52 */
  18700. case 'PtgElfRadicalS': /* [MS-XLS] 2.5.198.53 */
  18701. case 'PtgElfRw': /* [MS-XLS] 2.5.198.54 */
  18702. case 'PtgElfRwV': /* [MS-XLS] 2.5.198.55 */
  18703. throw new Error("Unsupported ELFs");
  18704. case 'PtgSxName': /* [MS-XLS] 2.5.198.91 TODO -- find a test case */
  18705. throw new Error('Unrecognized Formula Token: ' + String(f));
  18706. default: throw new Error('Unrecognized Formula Token: ' + String(f));
  18707. }
  18708. var PtgNonDisp = ['PtgAttrSpace', 'PtgAttrSpaceSemi', 'PtgAttrGoto'];
  18709. if(opts.biff != 3) if(last_sp >= 0 && PtgNonDisp.indexOf(formula[0][ff][0]) == -1) {
  18710. f = formula[0][last_sp];
  18711. var _left = true;
  18712. switch(f[1][0]) {
  18713. /* note: some bad XLSB files omit the PtgParen */
  18714. case 4: _left = false;
  18715. /* falls through */
  18716. case 0:
  18717. // $FlowIgnore
  18718. sp = fill(" ", f[1][1]); break;
  18719. case 5: _left = false;
  18720. /* falls through */
  18721. case 1:
  18722. // $FlowIgnore
  18723. sp = fill("\r", f[1][1]); break;
  18724. default:
  18725. sp = "";
  18726. // $FlowIgnore
  18727. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + f[1][0]);
  18728. }
  18729. stack.push((_left ? sp : "") + stack.pop() + (_left ? "" : sp));
  18730. last_sp = -1;
  18731. }
  18732. }
  18733. if(stack.length > 1 && opts.WTF) throw new Error("bad formula stack");
  18734. return stack[0];
  18735. }
  18736. /* [MS-XLS] 2.5.198.1 TODO */
  18737. function parse_ArrayParsedFormula(blob, length, opts) {
  18738. var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
  18739. var rgcb, cce = blob.read_shift(len); // length of rgce
  18740. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  18741. var rgce = parse_Rgce(blob, cce, opts);
  18742. if(length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
  18743. blob.l = target;
  18744. return [rgce, rgcb];
  18745. }
  18746. /* [MS-XLS] 2.5.198.3 TODO */
  18747. function parse_XLSCellParsedFormula(blob, length, opts) {
  18748. var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
  18749. var rgcb, cce = blob.read_shift(len); // length of rgce
  18750. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  18751. var rgce = parse_Rgce(blob, cce, opts);
  18752. if(length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
  18753. blob.l = target;
  18754. return [rgce, rgcb];
  18755. }
  18756. /* [MS-XLS] 2.5.198.21 */
  18757. function parse_NameParsedFormula(blob, length, opts, cce) {
  18758. var target = blob.l + length;
  18759. var rgce = parse_Rgce(blob, cce, opts);
  18760. var rgcb;
  18761. if(target !== blob.l) rgcb = parse_RgbExtra(blob, target - blob.l, rgce, opts);
  18762. return [rgce, rgcb];
  18763. }
  18764. /* [MS-XLS] 2.5.198.118 TODO */
  18765. function parse_SharedParsedFormula(blob, length, opts) {
  18766. var target = blob.l + length;
  18767. var rgcb, cce = blob.read_shift(2); // length of rgce
  18768. var rgce = parse_Rgce(blob, cce, opts);
  18769. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  18770. if(length !== cce + 2) rgcb = parse_RgbExtra(blob, target - cce - 2, rgce, opts);
  18771. return [rgce, rgcb];
  18772. }
  18773. /* [MS-XLS] 2.5.133 TODO: how to emit empty strings? */
  18774. function parse_FormulaValue(blob) {
  18775. var b;
  18776. if(__readUInt16LE(blob,blob.l + 6) !== 0xFFFF) return [parse_Xnum(blob),'n'];
  18777. switch(blob[blob.l]) {
  18778. case 0x00: blob.l += 8; return ["String", 's'];
  18779. case 0x01: b = blob[blob.l+2] === 0x1; blob.l += 8; return [b,'b'];
  18780. case 0x02: b = blob[blob.l+2]; blob.l += 8; return [b,'e'];
  18781. case 0x03: blob.l += 8; return ["",'s'];
  18782. }
  18783. return [];
  18784. }
  18785. function write_FormulaValue(value) {
  18786. if(value == null) {
  18787. // Blank String Value
  18788. var o = new_buf(8);
  18789. o.write_shift(1, 0x03);
  18790. o.write_shift(1, 0);
  18791. o.write_shift(2, 0);
  18792. o.write_shift(2, 0);
  18793. o.write_shift(2, 0xFFFF);
  18794. return o;
  18795. } else if(typeof value == "number") return write_Xnum(value);
  18796. return write_Xnum(0);
  18797. }
  18798. /* [MS-XLS] 2.4.127 TODO */
  18799. function parse_Formula(blob, length, opts) {
  18800. var end = blob.l + length;
  18801. var cell = parse_XLSCell(blob, 6);
  18802. if(opts.biff == 2) ++blob.l;
  18803. var val = parse_FormulaValue(blob,8);
  18804. var flags = blob.read_shift(1);
  18805. if(opts.biff != 2) {
  18806. blob.read_shift(1);
  18807. if(opts.biff >= 5) {
  18808. /*var chn = */blob.read_shift(4);
  18809. }
  18810. }
  18811. var cbf = parse_XLSCellParsedFormula(blob, end - blob.l, opts);
  18812. return {cell:cell, val:val[0], formula:cbf, shared: (flags >> 3) & 1, tt:val[1]};
  18813. }
  18814. function write_Formula(cell, R, C, opts, os) {
  18815. // Cell
  18816. var o1 = write_XLSCell(R, C, os);
  18817. // FormulaValue
  18818. var o2 = write_FormulaValue(cell.v);
  18819. // flags + cache
  18820. var o3 = new_buf(6);
  18821. var flags = 0x01 | 0x20;
  18822. o3.write_shift(2, flags);
  18823. o3.write_shift(4, 0);
  18824. // CellParsedFormula
  18825. var bf = new_buf(cell.bf.length);
  18826. for(var i = 0; i < cell.bf.length; ++i) bf[i] = cell.bf[i];
  18827. var out = bconcat([o1, o2, o3, bf]);
  18828. return out;
  18829. }
  18830. /* XLSB Parsed Formula records have the same shape */
  18831. function parse_XLSBParsedFormula(data, length, opts) {
  18832. var cce = data.read_shift(4);
  18833. var rgce = parse_Rgce(data, cce, opts);
  18834. var cb = data.read_shift(4);
  18835. var rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;
  18836. return [rgce, rgcb];
  18837. }
  18838. /* [MS-XLSB] 2.5.97.1 ArrayParsedFormula */
  18839. var parse_XLSBArrayParsedFormula = parse_XLSBParsedFormula;
  18840. /* [MS-XLSB] 2.5.97.4 CellParsedFormula */
  18841. var parse_XLSBCellParsedFormula = parse_XLSBParsedFormula;
  18842. /* [MS-XLSB] 2.5.97.8 DVParsedFormula */
  18843. //var parse_XLSBDVParsedFormula = parse_XLSBParsedFormula;
  18844. /* [MS-XLSB] 2.5.97.9 FRTParsedFormula */
  18845. //var parse_XLSBFRTParsedFormula = parse_XLSBParsedFormula2;
  18846. /* [MS-XLSB] 2.5.97.12 NameParsedFormula */
  18847. var parse_XLSBNameParsedFormula = parse_XLSBParsedFormula;
  18848. /* [MS-XLSB] 2.5.97.98 SharedParsedFormula */
  18849. var parse_XLSBSharedParsedFormula = parse_XLSBParsedFormula;
  18850. /* [MS-XLS] 2.5.198.4 */
  18851. var Cetab = {
  18852. 0x0000: 'BEEP',
  18853. 0x0001: 'OPEN',
  18854. 0x0002: 'OPEN.LINKS',
  18855. 0x0003: 'CLOSE.ALL',
  18856. 0x0004: 'SAVE',
  18857. 0x0005: 'SAVE.AS',
  18858. 0x0006: 'FILE.DELETE',
  18859. 0x0007: 'PAGE.SETUP',
  18860. 0x0008: 'PRINT',
  18861. 0x0009: 'PRINTER.SETUP',
  18862. 0x000A: 'QUIT',
  18863. 0x000B: 'NEW.WINDOW',
  18864. 0x000C: 'ARRANGE.ALL',
  18865. 0x000D: 'WINDOW.SIZE',
  18866. 0x000E: 'WINDOW.MOVE',
  18867. 0x000F: 'FULL',
  18868. 0x0010: 'CLOSE',
  18869. 0x0011: 'RUN',
  18870. 0x0016: 'SET.PRINT.AREA',
  18871. 0x0017: 'SET.PRINT.TITLES',
  18872. 0x0018: 'SET.PAGE.BREAK',
  18873. 0x0019: 'REMOVE.PAGE.BREAK',
  18874. 0x001A: 'FONT',
  18875. 0x001B: 'DISPLAY',
  18876. 0x001C: 'PROTECT.DOCUMENT',
  18877. 0x001D: 'PRECISION',
  18878. 0x001E: 'A1.R1C1',
  18879. 0x001F: 'CALCULATE.NOW',
  18880. 0x0020: 'CALCULATION',
  18881. 0x0022: 'DATA.FIND',
  18882. 0x0023: 'EXTRACT',
  18883. 0x0024: 'DATA.DELETE',
  18884. 0x0025: 'SET.DATABASE',
  18885. 0x0026: 'SET.CRITERIA',
  18886. 0x0027: 'SORT',
  18887. 0x0028: 'DATA.SERIES',
  18888. 0x0029: 'TABLE',
  18889. 0x002A: 'FORMAT.NUMBER',
  18890. 0x002B: 'ALIGNMENT',
  18891. 0x002C: 'STYLE',
  18892. 0x002D: 'BORDER',
  18893. 0x002E: 'CELL.PROTECTION',
  18894. 0x002F: 'COLUMN.WIDTH',
  18895. 0x0030: 'UNDO',
  18896. 0x0031: 'CUT',
  18897. 0x0032: 'COPY',
  18898. 0x0033: 'PASTE',
  18899. 0x0034: 'CLEAR',
  18900. 0x0035: 'PASTE.SPECIAL',
  18901. 0x0036: 'EDIT.DELETE',
  18902. 0x0037: 'INSERT',
  18903. 0x0038: 'FILL.RIGHT',
  18904. 0x0039: 'FILL.DOWN',
  18905. 0x003D: 'DEFINE.NAME',
  18906. 0x003E: 'CREATE.NAMES',
  18907. 0x003F: 'FORMULA.GOTO',
  18908. 0x0040: 'FORMULA.FIND',
  18909. 0x0041: 'SELECT.LAST.CELL',
  18910. 0x0042: 'SHOW.ACTIVE.CELL',
  18911. 0x0043: 'GALLERY.AREA',
  18912. 0x0044: 'GALLERY.BAR',
  18913. 0x0045: 'GALLERY.COLUMN',
  18914. 0x0046: 'GALLERY.LINE',
  18915. 0x0047: 'GALLERY.PIE',
  18916. 0x0048: 'GALLERY.SCATTER',
  18917. 0x0049: 'COMBINATION',
  18918. 0x004A: 'PREFERRED',
  18919. 0x004B: 'ADD.OVERLAY',
  18920. 0x004C: 'GRIDLINES',
  18921. 0x004D: 'SET.PREFERRED',
  18922. 0x004E: 'AXES',
  18923. 0x004F: 'LEGEND',
  18924. 0x0050: 'ATTACH.TEXT',
  18925. 0x0051: 'ADD.ARROW',
  18926. 0x0052: 'SELECT.CHART',
  18927. 0x0053: 'SELECT.PLOT.AREA',
  18928. 0x0054: 'PATTERNS',
  18929. 0x0055: 'MAIN.CHART',
  18930. 0x0056: 'OVERLAY',
  18931. 0x0057: 'SCALE',
  18932. 0x0058: 'FORMAT.LEGEND',
  18933. 0x0059: 'FORMAT.TEXT',
  18934. 0x005A: 'EDIT.REPEAT',
  18935. 0x005B: 'PARSE',
  18936. 0x005C: 'JUSTIFY',
  18937. 0x005D: 'HIDE',
  18938. 0x005E: 'UNHIDE',
  18939. 0x005F: 'WORKSPACE',
  18940. 0x0060: 'FORMULA',
  18941. 0x0061: 'FORMULA.FILL',
  18942. 0x0062: 'FORMULA.ARRAY',
  18943. 0x0063: 'DATA.FIND.NEXT',
  18944. 0x0064: 'DATA.FIND.PREV',
  18945. 0x0065: 'FORMULA.FIND.NEXT',
  18946. 0x0066: 'FORMULA.FIND.PREV',
  18947. 0x0067: 'ACTIVATE',
  18948. 0x0068: 'ACTIVATE.NEXT',
  18949. 0x0069: 'ACTIVATE.PREV',
  18950. 0x006A: 'UNLOCKED.NEXT',
  18951. 0x006B: 'UNLOCKED.PREV',
  18952. 0x006C: 'COPY.PICTURE',
  18953. 0x006D: 'SELECT',
  18954. 0x006E: 'DELETE.NAME',
  18955. 0x006F: 'DELETE.FORMAT',
  18956. 0x0070: 'VLINE',
  18957. 0x0071: 'HLINE',
  18958. 0x0072: 'VPAGE',
  18959. 0x0073: 'HPAGE',
  18960. 0x0074: 'VSCROLL',
  18961. 0x0075: 'HSCROLL',
  18962. 0x0076: 'ALERT',
  18963. 0x0077: 'NEW',
  18964. 0x0078: 'CANCEL.COPY',
  18965. 0x0079: 'SHOW.CLIPBOARD',
  18966. 0x007A: 'MESSAGE',
  18967. 0x007C: 'PASTE.LINK',
  18968. 0x007D: 'APP.ACTIVATE',
  18969. 0x007E: 'DELETE.ARROW',
  18970. 0x007F: 'ROW.HEIGHT',
  18971. 0x0080: 'FORMAT.MOVE',
  18972. 0x0081: 'FORMAT.SIZE',
  18973. 0x0082: 'FORMULA.REPLACE',
  18974. 0x0083: 'SEND.KEYS',
  18975. 0x0084: 'SELECT.SPECIAL',
  18976. 0x0085: 'APPLY.NAMES',
  18977. 0x0086: 'REPLACE.FONT',
  18978. 0x0087: 'FREEZE.PANES',
  18979. 0x0088: 'SHOW.INFO',
  18980. 0x0089: 'SPLIT',
  18981. 0x008A: 'ON.WINDOW',
  18982. 0x008B: 'ON.DATA',
  18983. 0x008C: 'DISABLE.INPUT',
  18984. 0x008E: 'OUTLINE',
  18985. 0x008F: 'LIST.NAMES',
  18986. 0x0090: 'FILE.CLOSE',
  18987. 0x0091: 'SAVE.WORKBOOK',
  18988. 0x0092: 'DATA.FORM',
  18989. 0x0093: 'COPY.CHART',
  18990. 0x0094: 'ON.TIME',
  18991. 0x0095: 'WAIT',
  18992. 0x0096: 'FORMAT.FONT',
  18993. 0x0097: 'FILL.UP',
  18994. 0x0098: 'FILL.LEFT',
  18995. 0x0099: 'DELETE.OVERLAY',
  18996. 0x009B: 'SHORT.MENUS',
  18997. 0x009F: 'SET.UPDATE.STATUS',
  18998. 0x00A1: 'COLOR.PALETTE',
  18999. 0x00A2: 'DELETE.STYLE',
  19000. 0x00A3: 'WINDOW.RESTORE',
  19001. 0x00A4: 'WINDOW.MAXIMIZE',
  19002. 0x00A6: 'CHANGE.LINK',
  19003. 0x00A7: 'CALCULATE.DOCUMENT',
  19004. 0x00A8: 'ON.KEY',
  19005. 0x00A9: 'APP.RESTORE',
  19006. 0x00AA: 'APP.MOVE',
  19007. 0x00AB: 'APP.SIZE',
  19008. 0x00AC: 'APP.MINIMIZE',
  19009. 0x00AD: 'APP.MAXIMIZE',
  19010. 0x00AE: 'BRING.TO.FRONT',
  19011. 0x00AF: 'SEND.TO.BACK',
  19012. 0x00B9: 'MAIN.CHART.TYPE',
  19013. 0x00BA: 'OVERLAY.CHART.TYPE',
  19014. 0x00BB: 'SELECT.END',
  19015. 0x00BC: 'OPEN.MAIL',
  19016. 0x00BD: 'SEND.MAIL',
  19017. 0x00BE: 'STANDARD.FONT',
  19018. 0x00BF: 'CONSOLIDATE',
  19019. 0x00C0: 'SORT.SPECIAL',
  19020. 0x00C1: 'GALLERY.3D.AREA',
  19021. 0x00C2: 'GALLERY.3D.COLUMN',
  19022. 0x00C3: 'GALLERY.3D.LINE',
  19023. 0x00C4: 'GALLERY.3D.PIE',
  19024. 0x00C5: 'VIEW.3D',
  19025. 0x00C6: 'GOAL.SEEK',
  19026. 0x00C7: 'WORKGROUP',
  19027. 0x00C8: 'FILL.GROUP',
  19028. 0x00C9: 'UPDATE.LINK',
  19029. 0x00CA: 'PROMOTE',
  19030. 0x00CB: 'DEMOTE',
  19031. 0x00CC: 'SHOW.DETAIL',
  19032. 0x00CE: 'UNGROUP',
  19033. 0x00CF: 'OBJECT.PROPERTIES',
  19034. 0x00D0: 'SAVE.NEW.OBJECT',
  19035. 0x00D1: 'SHARE',
  19036. 0x00D2: 'SHARE.NAME',
  19037. 0x00D3: 'DUPLICATE',
  19038. 0x00D4: 'APPLY.STYLE',
  19039. 0x00D5: 'ASSIGN.TO.OBJECT',
  19040. 0x00D6: 'OBJECT.PROTECTION',
  19041. 0x00D7: 'HIDE.OBJECT',
  19042. 0x00D8: 'SET.EXTRACT',
  19043. 0x00D9: 'CREATE.PUBLISHER',
  19044. 0x00DA: 'SUBSCRIBE.TO',
  19045. 0x00DB: 'ATTRIBUTES',
  19046. 0x00DC: 'SHOW.TOOLBAR',
  19047. 0x00DE: 'PRINT.PREVIEW',
  19048. 0x00DF: 'EDIT.COLOR',
  19049. 0x00E0: 'SHOW.LEVELS',
  19050. 0x00E1: 'FORMAT.MAIN',
  19051. 0x00E2: 'FORMAT.OVERLAY',
  19052. 0x00E3: 'ON.RECALC',
  19053. 0x00E4: 'EDIT.SERIES',
  19054. 0x00E5: 'DEFINE.STYLE',
  19055. 0x00F0: 'LINE.PRINT',
  19056. 0x00F3: 'ENTER.DATA',
  19057. 0x00F9: 'GALLERY.RADAR',
  19058. 0x00FA: 'MERGE.STYLES',
  19059. 0x00FB: 'EDITION.OPTIONS',
  19060. 0x00FC: 'PASTE.PICTURE',
  19061. 0x00FD: 'PASTE.PICTURE.LINK',
  19062. 0x00FE: 'SPELLING',
  19063. 0x0100: 'ZOOM',
  19064. 0x0103: 'INSERT.OBJECT',
  19065. 0x0104: 'WINDOW.MINIMIZE',
  19066. 0x0109: 'SOUND.NOTE',
  19067. 0x010A: 'SOUND.PLAY',
  19068. 0x010B: 'FORMAT.SHAPE',
  19069. 0x010C: 'EXTEND.POLYGON',
  19070. 0x010D: 'FORMAT.AUTO',
  19071. 0x0110: 'GALLERY.3D.BAR',
  19072. 0x0111: 'GALLERY.3D.SURFACE',
  19073. 0x0112: 'FILL.AUTO',
  19074. 0x0114: 'CUSTOMIZE.TOOLBAR',
  19075. 0x0115: 'ADD.TOOL',
  19076. 0x0116: 'EDIT.OBJECT',
  19077. 0x0117: 'ON.DOUBLECLICK',
  19078. 0x0118: 'ON.ENTRY',
  19079. 0x0119: 'WORKBOOK.ADD',
  19080. 0x011A: 'WORKBOOK.MOVE',
  19081. 0x011B: 'WORKBOOK.COPY',
  19082. 0x011C: 'WORKBOOK.OPTIONS',
  19083. 0x011D: 'SAVE.WORKSPACE',
  19084. 0x0120: 'CHART.WIZARD',
  19085. 0x0121: 'DELETE.TOOL',
  19086. 0x0122: 'MOVE.TOOL',
  19087. 0x0123: 'WORKBOOK.SELECT',
  19088. 0x0124: 'WORKBOOK.ACTIVATE',
  19089. 0x0125: 'ASSIGN.TO.TOOL',
  19090. 0x0127: 'COPY.TOOL',
  19091. 0x0128: 'RESET.TOOL',
  19092. 0x0129: 'CONSTRAIN.NUMERIC',
  19093. 0x012A: 'PASTE.TOOL',
  19094. 0x012E: 'WORKBOOK.NEW',
  19095. 0x0131: 'SCENARIO.CELLS',
  19096. 0x0132: 'SCENARIO.DELETE',
  19097. 0x0133: 'SCENARIO.ADD',
  19098. 0x0134: 'SCENARIO.EDIT',
  19099. 0x0135: 'SCENARIO.SHOW',
  19100. 0x0136: 'SCENARIO.SHOW.NEXT',
  19101. 0x0137: 'SCENARIO.SUMMARY',
  19102. 0x0138: 'PIVOT.TABLE.WIZARD',
  19103. 0x0139: 'PIVOT.FIELD.PROPERTIES',
  19104. 0x013A: 'PIVOT.FIELD',
  19105. 0x013B: 'PIVOT.ITEM',
  19106. 0x013C: 'PIVOT.ADD.FIELDS',
  19107. 0x013E: 'OPTIONS.CALCULATION',
  19108. 0x013F: 'OPTIONS.EDIT',
  19109. 0x0140: 'OPTIONS.VIEW',
  19110. 0x0141: 'ADDIN.MANAGER',
  19111. 0x0142: 'MENU.EDITOR',
  19112. 0x0143: 'ATTACH.TOOLBARS',
  19113. 0x0144: 'VBAActivate',
  19114. 0x0145: 'OPTIONS.CHART',
  19115. 0x0148: 'VBA.INSERT.FILE',
  19116. 0x014A: 'VBA.PROCEDURE.DEFINITION',
  19117. 0x0150: 'ROUTING.SLIP',
  19118. 0x0152: 'ROUTE.DOCUMENT',
  19119. 0x0153: 'MAIL.LOGON',
  19120. 0x0156: 'INSERT.PICTURE',
  19121. 0x0157: 'EDIT.TOOL',
  19122. 0x0158: 'GALLERY.DOUGHNUT',
  19123. 0x015E: 'CHART.TREND',
  19124. 0x0160: 'PIVOT.ITEM.PROPERTIES',
  19125. 0x0162: 'WORKBOOK.INSERT',
  19126. 0x0163: 'OPTIONS.TRANSITION',
  19127. 0x0164: 'OPTIONS.GENERAL',
  19128. 0x0172: 'FILTER.ADVANCED',
  19129. 0x0175: 'MAIL.ADD.MAILER',
  19130. 0x0176: 'MAIL.DELETE.MAILER',
  19131. 0x0177: 'MAIL.REPLY',
  19132. 0x0178: 'MAIL.REPLY.ALL',
  19133. 0x0179: 'MAIL.FORWARD',
  19134. 0x017A: 'MAIL.NEXT.LETTER',
  19135. 0x017B: 'DATA.LABEL',
  19136. 0x017C: 'INSERT.TITLE',
  19137. 0x017D: 'FONT.PROPERTIES',
  19138. 0x017E: 'MACRO.OPTIONS',
  19139. 0x017F: 'WORKBOOK.HIDE',
  19140. 0x0180: 'WORKBOOK.UNHIDE',
  19141. 0x0181: 'WORKBOOK.DELETE',
  19142. 0x0182: 'WORKBOOK.NAME',
  19143. 0x0184: 'GALLERY.CUSTOM',
  19144. 0x0186: 'ADD.CHART.AUTOFORMAT',
  19145. 0x0187: 'DELETE.CHART.AUTOFORMAT',
  19146. 0x0188: 'CHART.ADD.DATA',
  19147. 0x0189: 'AUTO.OUTLINE',
  19148. 0x018A: 'TAB.ORDER',
  19149. 0x018B: 'SHOW.DIALOG',
  19150. 0x018C: 'SELECT.ALL',
  19151. 0x018D: 'UNGROUP.SHEETS',
  19152. 0x018E: 'SUBTOTAL.CREATE',
  19153. 0x018F: 'SUBTOTAL.REMOVE',
  19154. 0x0190: 'RENAME.OBJECT',
  19155. 0x019C: 'WORKBOOK.SCROLL',
  19156. 0x019D: 'WORKBOOK.NEXT',
  19157. 0x019E: 'WORKBOOK.PREV',
  19158. 0x019F: 'WORKBOOK.TAB.SPLIT',
  19159. 0x01A0: 'FULL.SCREEN',
  19160. 0x01A1: 'WORKBOOK.PROTECT',
  19161. 0x01A4: 'SCROLLBAR.PROPERTIES',
  19162. 0x01A5: 'PIVOT.SHOW.PAGES',
  19163. 0x01A6: 'TEXT.TO.COLUMNS',
  19164. 0x01A7: 'FORMAT.CHARTTYPE',
  19165. 0x01A8: 'LINK.FORMAT',
  19166. 0x01A9: 'TRACER.DISPLAY',
  19167. 0x01AE: 'TRACER.NAVIGATE',
  19168. 0x01AF: 'TRACER.CLEAR',
  19169. 0x01B0: 'TRACER.ERROR',
  19170. 0x01B1: 'PIVOT.FIELD.GROUP',
  19171. 0x01B2: 'PIVOT.FIELD.UNGROUP',
  19172. 0x01B3: 'CHECKBOX.PROPERTIES',
  19173. 0x01B4: 'LABEL.PROPERTIES',
  19174. 0x01B5: 'LISTBOX.PROPERTIES',
  19175. 0x01B6: 'EDITBOX.PROPERTIES',
  19176. 0x01B7: 'PIVOT.REFRESH',
  19177. 0x01B8: 'LINK.COMBO',
  19178. 0x01B9: 'OPEN.TEXT',
  19179. 0x01BA: 'HIDE.DIALOG',
  19180. 0x01BB: 'SET.DIALOG.FOCUS',
  19181. 0x01BC: 'ENABLE.OBJECT',
  19182. 0x01BD: 'PUSHBUTTON.PROPERTIES',
  19183. 0x01BE: 'SET.DIALOG.DEFAULT',
  19184. 0x01BF: 'FILTER',
  19185. 0x01C0: 'FILTER.SHOW.ALL',
  19186. 0x01C1: 'CLEAR.OUTLINE',
  19187. 0x01C2: 'FUNCTION.WIZARD',
  19188. 0x01C3: 'ADD.LIST.ITEM',
  19189. 0x01C4: 'SET.LIST.ITEM',
  19190. 0x01C5: 'REMOVE.LIST.ITEM',
  19191. 0x01C6: 'SELECT.LIST.ITEM',
  19192. 0x01C7: 'SET.CONTROL.VALUE',
  19193. 0x01C8: 'SAVE.COPY.AS',
  19194. 0x01CA: 'OPTIONS.LISTS.ADD',
  19195. 0x01CB: 'OPTIONS.LISTS.DELETE',
  19196. 0x01CC: 'SERIES.AXES',
  19197. 0x01CD: 'SERIES.X',
  19198. 0x01CE: 'SERIES.Y',
  19199. 0x01CF: 'ERRORBAR.X',
  19200. 0x01D0: 'ERRORBAR.Y',
  19201. 0x01D1: 'FORMAT.CHART',
  19202. 0x01D2: 'SERIES.ORDER',
  19203. 0x01D3: 'MAIL.LOGOFF',
  19204. 0x01D4: 'CLEAR.ROUTING.SLIP',
  19205. 0x01D5: 'APP.ACTIVATE.MICROSOFT',
  19206. 0x01D6: 'MAIL.EDIT.MAILER',
  19207. 0x01D7: 'ON.SHEET',
  19208. 0x01D8: 'STANDARD.WIDTH',
  19209. 0x01D9: 'SCENARIO.MERGE',
  19210. 0x01DA: 'SUMMARY.INFO',
  19211. 0x01DB: 'FIND.FILE',
  19212. 0x01DC: 'ACTIVE.CELL.FONT',
  19213. 0x01DD: 'ENABLE.TIPWIZARD',
  19214. 0x01DE: 'VBA.MAKE.ADDIN',
  19215. 0x01E0: 'INSERTDATATABLE',
  19216. 0x01E1: 'WORKGROUP.OPTIONS',
  19217. 0x01E2: 'MAIL.SEND.MAILER',
  19218. 0x01E5: 'AUTOCORRECT',
  19219. 0x01E9: 'POST.DOCUMENT',
  19220. 0x01EB: 'PICKLIST',
  19221. 0x01ED: 'VIEW.SHOW',
  19222. 0x01EE: 'VIEW.DEFINE',
  19223. 0x01EF: 'VIEW.DELETE',
  19224. 0x01FD: 'SHEET.BACKGROUND',
  19225. 0x01FE: 'INSERT.MAP.OBJECT',
  19226. 0x01FF: 'OPTIONS.MENONO',
  19227. 0x0205: 'MSOCHECKS',
  19228. 0x0206: 'NORMAL',
  19229. 0x0207: 'LAYOUT',
  19230. 0x0208: 'RM.PRINT.AREA',
  19231. 0x0209: 'CLEAR.PRINT.AREA',
  19232. 0x020A: 'ADD.PRINT.AREA',
  19233. 0x020B: 'MOVE.BRK',
  19234. 0x0221: 'HIDECURR.NOTE',
  19235. 0x0222: 'HIDEALL.NOTES',
  19236. 0x0223: 'DELETE.NOTE',
  19237. 0x0224: 'TRAVERSE.NOTES',
  19238. 0x0225: 'ACTIVATE.NOTES',
  19239. 0x026C: 'PROTECT.REVISIONS',
  19240. 0x026D: 'UNPROTECT.REVISIONS',
  19241. 0x0287: 'OPTIONS.ME',
  19242. 0x028D: 'WEB.PUBLISH',
  19243. 0x029B: 'NEWWEBQUERY',
  19244. 0x02A1: 'PIVOT.TABLE.CHART',
  19245. 0x02F1: 'OPTIONS.SAVE',
  19246. 0x02F3: 'OPTIONS.SPELL',
  19247. 0x0328: 'HIDEALL.INKANNOTS'
  19248. };
  19249. /* [MS-XLS] 2.5.198.17 */
  19250. /* [MS-XLSB] 2.5.97.10 */
  19251. var Ftab = {
  19252. 0x0000: 'COUNT',
  19253. 0x0001: 'IF',
  19254. 0x0002: 'ISNA',
  19255. 0x0003: 'ISERROR',
  19256. 0x0004: 'SUM',
  19257. 0x0005: 'AVERAGE',
  19258. 0x0006: 'MIN',
  19259. 0x0007: 'MAX',
  19260. 0x0008: 'ROW',
  19261. 0x0009: 'COLUMN',
  19262. 0x000A: 'NA',
  19263. 0x000B: 'NPV',
  19264. 0x000C: 'STDEV',
  19265. 0x000D: 'DOLLAR',
  19266. 0x000E: 'FIXED',
  19267. 0x000F: 'SIN',
  19268. 0x0010: 'COS',
  19269. 0x0011: 'TAN',
  19270. 0x0012: 'ATAN',
  19271. 0x0013: 'PI',
  19272. 0x0014: 'SQRT',
  19273. 0x0015: 'EXP',
  19274. 0x0016: 'LN',
  19275. 0x0017: 'LOG10',
  19276. 0x0018: 'ABS',
  19277. 0x0019: 'INT',
  19278. 0x001A: 'SIGN',
  19279. 0x001B: 'ROUND',
  19280. 0x001C: 'LOOKUP',
  19281. 0x001D: 'INDEX',
  19282. 0x001E: 'REPT',
  19283. 0x001F: 'MID',
  19284. 0x0020: 'LEN',
  19285. 0x0021: 'VALUE',
  19286. 0x0022: 'TRUE',
  19287. 0x0023: 'FALSE',
  19288. 0x0024: 'AND',
  19289. 0x0025: 'OR',
  19290. 0x0026: 'NOT',
  19291. 0x0027: 'MOD',
  19292. 0x0028: 'DCOUNT',
  19293. 0x0029: 'DSUM',
  19294. 0x002A: 'DAVERAGE',
  19295. 0x002B: 'DMIN',
  19296. 0x002C: 'DMAX',
  19297. 0x002D: 'DSTDEV',
  19298. 0x002E: 'VAR',
  19299. 0x002F: 'DVAR',
  19300. 0x0030: 'TEXT',
  19301. 0x0031: 'LINEST',
  19302. 0x0032: 'TREND',
  19303. 0x0033: 'LOGEST',
  19304. 0x0034: 'GROWTH',
  19305. 0x0035: 'GOTO',
  19306. 0x0036: 'HALT',
  19307. 0x0037: 'RETURN',
  19308. 0x0038: 'PV',
  19309. 0x0039: 'FV',
  19310. 0x003A: 'NPER',
  19311. 0x003B: 'PMT',
  19312. 0x003C: 'RATE',
  19313. 0x003D: 'MIRR',
  19314. 0x003E: 'IRR',
  19315. 0x003F: 'RAND',
  19316. 0x0040: 'MATCH',
  19317. 0x0041: 'DATE',
  19318. 0x0042: 'TIME',
  19319. 0x0043: 'DAY',
  19320. 0x0044: 'MONTH',
  19321. 0x0045: 'YEAR',
  19322. 0x0046: 'WEEKDAY',
  19323. 0x0047: 'HOUR',
  19324. 0x0048: 'MINUTE',
  19325. 0x0049: 'SECOND',
  19326. 0x004A: 'NOW',
  19327. 0x004B: 'AREAS',
  19328. 0x004C: 'ROWS',
  19329. 0x004D: 'COLUMNS',
  19330. 0x004E: 'OFFSET',
  19331. 0x004F: 'ABSREF',
  19332. 0x0050: 'RELREF',
  19333. 0x0051: 'ARGUMENT',
  19334. 0x0052: 'SEARCH',
  19335. 0x0053: 'TRANSPOSE',
  19336. 0x0054: 'ERROR',
  19337. 0x0055: 'STEP',
  19338. 0x0056: 'TYPE',
  19339. 0x0057: 'ECHO',
  19340. 0x0058: 'SET.NAME',
  19341. 0x0059: 'CALLER',
  19342. 0x005A: 'DEREF',
  19343. 0x005B: 'WINDOWS',
  19344. 0x005C: 'SERIES',
  19345. 0x005D: 'DOCUMENTS',
  19346. 0x005E: 'ACTIVE.CELL',
  19347. 0x005F: 'SELECTION',
  19348. 0x0060: 'RESULT',
  19349. 0x0061: 'ATAN2',
  19350. 0x0062: 'ASIN',
  19351. 0x0063: 'ACOS',
  19352. 0x0064: 'CHOOSE',
  19353. 0x0065: 'HLOOKUP',
  19354. 0x0066: 'VLOOKUP',
  19355. 0x0067: 'LINKS',
  19356. 0x0068: 'INPUT',
  19357. 0x0069: 'ISREF',
  19358. 0x006A: 'GET.FORMULA',
  19359. 0x006B: 'GET.NAME',
  19360. 0x006C: 'SET.VALUE',
  19361. 0x006D: 'LOG',
  19362. 0x006E: 'EXEC',
  19363. 0x006F: 'CHAR',
  19364. 0x0070: 'LOWER',
  19365. 0x0071: 'UPPER',
  19366. 0x0072: 'PROPER',
  19367. 0x0073: 'LEFT',
  19368. 0x0074: 'RIGHT',
  19369. 0x0075: 'EXACT',
  19370. 0x0076: 'TRIM',
  19371. 0x0077: 'REPLACE',
  19372. 0x0078: 'SUBSTITUTE',
  19373. 0x0079: 'CODE',
  19374. 0x007A: 'NAMES',
  19375. 0x007B: 'DIRECTORY',
  19376. 0x007C: 'FIND',
  19377. 0x007D: 'CELL',
  19378. 0x007E: 'ISERR',
  19379. 0x007F: 'ISTEXT',
  19380. 0x0080: 'ISNUMBER',
  19381. 0x0081: 'ISBLANK',
  19382. 0x0082: 'T',
  19383. 0x0083: 'N',
  19384. 0x0084: 'FOPEN',
  19385. 0x0085: 'FCLOSE',
  19386. 0x0086: 'FSIZE',
  19387. 0x0087: 'FREADLN',
  19388. 0x0088: 'FREAD',
  19389. 0x0089: 'FWRITELN',
  19390. 0x008A: 'FWRITE',
  19391. 0x008B: 'FPOS',
  19392. 0x008C: 'DATEVALUE',
  19393. 0x008D: 'TIMEVALUE',
  19394. 0x008E: 'SLN',
  19395. 0x008F: 'SYD',
  19396. 0x0090: 'DDB',
  19397. 0x0091: 'GET.DEF',
  19398. 0x0092: 'REFTEXT',
  19399. 0x0093: 'TEXTREF',
  19400. 0x0094: 'INDIRECT',
  19401. 0x0095: 'REGISTER',
  19402. 0x0096: 'CALL',
  19403. 0x0097: 'ADD.BAR',
  19404. 0x0098: 'ADD.MENU',
  19405. 0x0099: 'ADD.COMMAND',
  19406. 0x009A: 'ENABLE.COMMAND',
  19407. 0x009B: 'CHECK.COMMAND',
  19408. 0x009C: 'RENAME.COMMAND',
  19409. 0x009D: 'SHOW.BAR',
  19410. 0x009E: 'DELETE.MENU',
  19411. 0x009F: 'DELETE.COMMAND',
  19412. 0x00A0: 'GET.CHART.ITEM',
  19413. 0x00A1: 'DIALOG.BOX',
  19414. 0x00A2: 'CLEAN',
  19415. 0x00A3: 'MDETERM',
  19416. 0x00A4: 'MINVERSE',
  19417. 0x00A5: 'MMULT',
  19418. 0x00A6: 'FILES',
  19419. 0x00A7: 'IPMT',
  19420. 0x00A8: 'PPMT',
  19421. 0x00A9: 'COUNTA',
  19422. 0x00AA: 'CANCEL.KEY',
  19423. 0x00AB: 'FOR',
  19424. 0x00AC: 'WHILE',
  19425. 0x00AD: 'BREAK',
  19426. 0x00AE: 'NEXT',
  19427. 0x00AF: 'INITIATE',
  19428. 0x00B0: 'REQUEST',
  19429. 0x00B1: 'POKE',
  19430. 0x00B2: 'EXECUTE',
  19431. 0x00B3: 'TERMINATE',
  19432. 0x00B4: 'RESTART',
  19433. 0x00B5: 'HELP',
  19434. 0x00B6: 'GET.BAR',
  19435. 0x00B7: 'PRODUCT',
  19436. 0x00B8: 'FACT',
  19437. 0x00B9: 'GET.CELL',
  19438. 0x00BA: 'GET.WORKSPACE',
  19439. 0x00BB: 'GET.WINDOW',
  19440. 0x00BC: 'GET.DOCUMENT',
  19441. 0x00BD: 'DPRODUCT',
  19442. 0x00BE: 'ISNONTEXT',
  19443. 0x00BF: 'GET.NOTE',
  19444. 0x00C0: 'NOTE',
  19445. 0x00C1: 'STDEVP',
  19446. 0x00C2: 'VARP',
  19447. 0x00C3: 'DSTDEVP',
  19448. 0x00C4: 'DVARP',
  19449. 0x00C5: 'TRUNC',
  19450. 0x00C6: 'ISLOGICAL',
  19451. 0x00C7: 'DCOUNTA',
  19452. 0x00C8: 'DELETE.BAR',
  19453. 0x00C9: 'UNREGISTER',
  19454. 0x00CC: 'USDOLLAR',
  19455. 0x00CD: 'FINDB',
  19456. 0x00CE: 'SEARCHB',
  19457. 0x00CF: 'REPLACEB',
  19458. 0x00D0: 'LEFTB',
  19459. 0x00D1: 'RIGHTB',
  19460. 0x00D2: 'MIDB',
  19461. 0x00D3: 'LENB',
  19462. 0x00D4: 'ROUNDUP',
  19463. 0x00D5: 'ROUNDDOWN',
  19464. 0x00D6: 'ASC',
  19465. 0x00D7: 'DBCS',
  19466. 0x00D8: 'RANK',
  19467. 0x00DB: 'ADDRESS',
  19468. 0x00DC: 'DAYS360',
  19469. 0x00DD: 'TODAY',
  19470. 0x00DE: 'VDB',
  19471. 0x00DF: 'ELSE',
  19472. 0x00E0: 'ELSE.IF',
  19473. 0x00E1: 'END.IF',
  19474. 0x00E2: 'FOR.CELL',
  19475. 0x00E3: 'MEDIAN',
  19476. 0x00E4: 'SUMPRODUCT',
  19477. 0x00E5: 'SINH',
  19478. 0x00E6: 'COSH',
  19479. 0x00E7: 'TANH',
  19480. 0x00E8: 'ASINH',
  19481. 0x00E9: 'ACOSH',
  19482. 0x00EA: 'ATANH',
  19483. 0x00EB: 'DGET',
  19484. 0x00EC: 'CREATE.OBJECT',
  19485. 0x00ED: 'VOLATILE',
  19486. 0x00EE: 'LAST.ERROR',
  19487. 0x00EF: 'CUSTOM.UNDO',
  19488. 0x00F0: 'CUSTOM.REPEAT',
  19489. 0x00F1: 'FORMULA.CONVERT',
  19490. 0x00F2: 'GET.LINK.INFO',
  19491. 0x00F3: 'TEXT.BOX',
  19492. 0x00F4: 'INFO',
  19493. 0x00F5: 'GROUP',
  19494. 0x00F6: 'GET.OBJECT',
  19495. 0x00F7: 'DB',
  19496. 0x00F8: 'PAUSE',
  19497. 0x00FB: 'RESUME',
  19498. 0x00FC: 'FREQUENCY',
  19499. 0x00FD: 'ADD.TOOLBAR',
  19500. 0x00FE: 'DELETE.TOOLBAR',
  19501. 0x00FF: 'User',
  19502. 0x0100: 'RESET.TOOLBAR',
  19503. 0x0101: 'EVALUATE',
  19504. 0x0102: 'GET.TOOLBAR',
  19505. 0x0103: 'GET.TOOL',
  19506. 0x0104: 'SPELLING.CHECK',
  19507. 0x0105: 'ERROR.TYPE',
  19508. 0x0106: 'APP.TITLE',
  19509. 0x0107: 'WINDOW.TITLE',
  19510. 0x0108: 'SAVE.TOOLBAR',
  19511. 0x0109: 'ENABLE.TOOL',
  19512. 0x010A: 'PRESS.TOOL',
  19513. 0x010B: 'REGISTER.ID',
  19514. 0x010C: 'GET.WORKBOOK',
  19515. 0x010D: 'AVEDEV',
  19516. 0x010E: 'BETADIST',
  19517. 0x010F: 'GAMMALN',
  19518. 0x0110: 'BETAINV',
  19519. 0x0111: 'BINOMDIST',
  19520. 0x0112: 'CHIDIST',
  19521. 0x0113: 'CHIINV',
  19522. 0x0114: 'COMBIN',
  19523. 0x0115: 'CONFIDENCE',
  19524. 0x0116: 'CRITBINOM',
  19525. 0x0117: 'EVEN',
  19526. 0x0118: 'EXPONDIST',
  19527. 0x0119: 'FDIST',
  19528. 0x011A: 'FINV',
  19529. 0x011B: 'FISHER',
  19530. 0x011C: 'FISHERINV',
  19531. 0x011D: 'FLOOR',
  19532. 0x011E: 'GAMMADIST',
  19533. 0x011F: 'GAMMAINV',
  19534. 0x0120: 'CEILING',
  19535. 0x0121: 'HYPGEOMDIST',
  19536. 0x0122: 'LOGNORMDIST',
  19537. 0x0123: 'LOGINV',
  19538. 0x0124: 'NEGBINOMDIST',
  19539. 0x0125: 'NORMDIST',
  19540. 0x0126: 'NORMSDIST',
  19541. 0x0127: 'NORMINV',
  19542. 0x0128: 'NORMSINV',
  19543. 0x0129: 'STANDARDIZE',
  19544. 0x012A: 'ODD',
  19545. 0x012B: 'PERMUT',
  19546. 0x012C: 'POISSON',
  19547. 0x012D: 'TDIST',
  19548. 0x012E: 'WEIBULL',
  19549. 0x012F: 'SUMXMY2',
  19550. 0x0130: 'SUMX2MY2',
  19551. 0x0131: 'SUMX2PY2',
  19552. 0x0132: 'CHITEST',
  19553. 0x0133: 'CORREL',
  19554. 0x0134: 'COVAR',
  19555. 0x0135: 'FORECAST',
  19556. 0x0136: 'FTEST',
  19557. 0x0137: 'INTERCEPT',
  19558. 0x0138: 'PEARSON',
  19559. 0x0139: 'RSQ',
  19560. 0x013A: 'STEYX',
  19561. 0x013B: 'SLOPE',
  19562. 0x013C: 'TTEST',
  19563. 0x013D: 'PROB',
  19564. 0x013E: 'DEVSQ',
  19565. 0x013F: 'GEOMEAN',
  19566. 0x0140: 'HARMEAN',
  19567. 0x0141: 'SUMSQ',
  19568. 0x0142: 'KURT',
  19569. 0x0143: 'SKEW',
  19570. 0x0144: 'ZTEST',
  19571. 0x0145: 'LARGE',
  19572. 0x0146: 'SMALL',
  19573. 0x0147: 'QUARTILE',
  19574. 0x0148: 'PERCENTILE',
  19575. 0x0149: 'PERCENTRANK',
  19576. 0x014A: 'MODE',
  19577. 0x014B: 'TRIMMEAN',
  19578. 0x014C: 'TINV',
  19579. 0x014E: 'MOVIE.COMMAND',
  19580. 0x014F: 'GET.MOVIE',
  19581. 0x0150: 'CONCATENATE',
  19582. 0x0151: 'POWER',
  19583. 0x0152: 'PIVOT.ADD.DATA',
  19584. 0x0153: 'GET.PIVOT.TABLE',
  19585. 0x0154: 'GET.PIVOT.FIELD',
  19586. 0x0155: 'GET.PIVOT.ITEM',
  19587. 0x0156: 'RADIANS',
  19588. 0x0157: 'DEGREES',
  19589. 0x0158: 'SUBTOTAL',
  19590. 0x0159: 'SUMIF',
  19591. 0x015A: 'COUNTIF',
  19592. 0x015B: 'COUNTBLANK',
  19593. 0x015C: 'SCENARIO.GET',
  19594. 0x015D: 'OPTIONS.LISTS.GET',
  19595. 0x015E: 'ISPMT',
  19596. 0x015F: 'DATEDIF',
  19597. 0x0160: 'DATESTRING',
  19598. 0x0161: 'NUMBERSTRING',
  19599. 0x0162: 'ROMAN',
  19600. 0x0163: 'OPEN.DIALOG',
  19601. 0x0164: 'SAVE.DIALOG',
  19602. 0x0165: 'VIEW.GET',
  19603. 0x0166: 'GETPIVOTDATA',
  19604. 0x0167: 'HYPERLINK',
  19605. 0x0168: 'PHONETIC',
  19606. 0x0169: 'AVERAGEA',
  19607. 0x016A: 'MAXA',
  19608. 0x016B: 'MINA',
  19609. 0x016C: 'STDEVPA',
  19610. 0x016D: 'VARPA',
  19611. 0x016E: 'STDEVA',
  19612. 0x016F: 'VARA',
  19613. 0x0170: 'BAHTTEXT',
  19614. 0x0171: 'THAIDAYOFWEEK',
  19615. 0x0172: 'THAIDIGIT',
  19616. 0x0173: 'THAIMONTHOFYEAR',
  19617. 0x0174: 'THAINUMSOUND',
  19618. 0x0175: 'THAINUMSTRING',
  19619. 0x0176: 'THAISTRINGLENGTH',
  19620. 0x0177: 'ISTHAIDIGIT',
  19621. 0x0178: 'ROUNDBAHTDOWN',
  19622. 0x0179: 'ROUNDBAHTUP',
  19623. 0x017A: 'THAIYEAR',
  19624. 0x017B: 'RTD',
  19625. 0x017C: 'CUBEVALUE',
  19626. 0x017D: 'CUBEMEMBER',
  19627. 0x017E: 'CUBEMEMBERPROPERTY',
  19628. 0x017F: 'CUBERANKEDMEMBER',
  19629. 0x0180: 'HEX2BIN',
  19630. 0x0181: 'HEX2DEC',
  19631. 0x0182: 'HEX2OCT',
  19632. 0x0183: 'DEC2BIN',
  19633. 0x0184: 'DEC2HEX',
  19634. 0x0185: 'DEC2OCT',
  19635. 0x0186: 'OCT2BIN',
  19636. 0x0187: 'OCT2HEX',
  19637. 0x0188: 'OCT2DEC',
  19638. 0x0189: 'BIN2DEC',
  19639. 0x018A: 'BIN2OCT',
  19640. 0x018B: 'BIN2HEX',
  19641. 0x018C: 'IMSUB',
  19642. 0x018D: 'IMDIV',
  19643. 0x018E: 'IMPOWER',
  19644. 0x018F: 'IMABS',
  19645. 0x0190: 'IMSQRT',
  19646. 0x0191: 'IMLN',
  19647. 0x0192: 'IMLOG2',
  19648. 0x0193: 'IMLOG10',
  19649. 0x0194: 'IMSIN',
  19650. 0x0195: 'IMCOS',
  19651. 0x0196: 'IMEXP',
  19652. 0x0197: 'IMARGUMENT',
  19653. 0x0198: 'IMCONJUGATE',
  19654. 0x0199: 'IMAGINARY',
  19655. 0x019A: 'IMREAL',
  19656. 0x019B: 'COMPLEX',
  19657. 0x019C: 'IMSUM',
  19658. 0x019D: 'IMPRODUCT',
  19659. 0x019E: 'SERIESSUM',
  19660. 0x019F: 'FACTDOUBLE',
  19661. 0x01A0: 'SQRTPI',
  19662. 0x01A1: 'QUOTIENT',
  19663. 0x01A2: 'DELTA',
  19664. 0x01A3: 'GESTEP',
  19665. 0x01A4: 'ISEVEN',
  19666. 0x01A5: 'ISODD',
  19667. 0x01A6: 'MROUND',
  19668. 0x01A7: 'ERF',
  19669. 0x01A8: 'ERFC',
  19670. 0x01A9: 'BESSELJ',
  19671. 0x01AA: 'BESSELK',
  19672. 0x01AB: 'BESSELY',
  19673. 0x01AC: 'BESSELI',
  19674. 0x01AD: 'XIRR',
  19675. 0x01AE: 'XNPV',
  19676. 0x01AF: 'PRICEMAT',
  19677. 0x01B0: 'YIELDMAT',
  19678. 0x01B1: 'INTRATE',
  19679. 0x01B2: 'RECEIVED',
  19680. 0x01B3: 'DISC',
  19681. 0x01B4: 'PRICEDISC',
  19682. 0x01B5: 'YIELDDISC',
  19683. 0x01B6: 'TBILLEQ',
  19684. 0x01B7: 'TBILLPRICE',
  19685. 0x01B8: 'TBILLYIELD',
  19686. 0x01B9: 'PRICE',
  19687. 0x01BA: 'YIELD',
  19688. 0x01BB: 'DOLLARDE',
  19689. 0x01BC: 'DOLLARFR',
  19690. 0x01BD: 'NOMINAL',
  19691. 0x01BE: 'EFFECT',
  19692. 0x01BF: 'CUMPRINC',
  19693. 0x01C0: 'CUMIPMT',
  19694. 0x01C1: 'EDATE',
  19695. 0x01C2: 'EOMONTH',
  19696. 0x01C3: 'YEARFRAC',
  19697. 0x01C4: 'COUPDAYBS',
  19698. 0x01C5: 'COUPDAYS',
  19699. 0x01C6: 'COUPDAYSNC',
  19700. 0x01C7: 'COUPNCD',
  19701. 0x01C8: 'COUPNUM',
  19702. 0x01C9: 'COUPPCD',
  19703. 0x01CA: 'DURATION',
  19704. 0x01CB: 'MDURATION',
  19705. 0x01CC: 'ODDLPRICE',
  19706. 0x01CD: 'ODDLYIELD',
  19707. 0x01CE: 'ODDFPRICE',
  19708. 0x01CF: 'ODDFYIELD',
  19709. 0x01D0: 'RANDBETWEEN',
  19710. 0x01D1: 'WEEKNUM',
  19711. 0x01D2: 'AMORDEGRC',
  19712. 0x01D3: 'AMORLINC',
  19713. 0x01D4: 'CONVERT',
  19714. 0x02D4: 'SHEETJS',
  19715. 0x01D5: 'ACCRINT',
  19716. 0x01D6: 'ACCRINTM',
  19717. 0x01D7: 'WORKDAY',
  19718. 0x01D8: 'NETWORKDAYS',
  19719. 0x01D9: 'GCD',
  19720. 0x01DA: 'MULTINOMIAL',
  19721. 0x01DB: 'LCM',
  19722. 0x01DC: 'FVSCHEDULE',
  19723. 0x01DD: 'CUBEKPIMEMBER',
  19724. 0x01DE: 'CUBESET',
  19725. 0x01DF: 'CUBESETCOUNT',
  19726. 0x01E0: 'IFERROR',
  19727. 0x01E1: 'COUNTIFS',
  19728. 0x01E2: 'SUMIFS',
  19729. 0x01E3: 'AVERAGEIF',
  19730. 0x01E4: 'AVERAGEIFS'
  19731. };
  19732. var FtabArgc = {
  19733. 0x0002: 1, /* ISNA */
  19734. 0x0003: 1, /* ISERROR */
  19735. 0x000A: 0, /* NA */
  19736. 0x000F: 1, /* SIN */
  19737. 0x0010: 1, /* COS */
  19738. 0x0011: 1, /* TAN */
  19739. 0x0012: 1, /* ATAN */
  19740. 0x0013: 0, /* PI */
  19741. 0x0014: 1, /* SQRT */
  19742. 0x0015: 1, /* EXP */
  19743. 0x0016: 1, /* LN */
  19744. 0x0017: 1, /* LOG10 */
  19745. 0x0018: 1, /* ABS */
  19746. 0x0019: 1, /* INT */
  19747. 0x001A: 1, /* SIGN */
  19748. 0x001B: 2, /* ROUND */
  19749. 0x001E: 2, /* REPT */
  19750. 0x001F: 3, /* MID */
  19751. 0x0020: 1, /* LEN */
  19752. 0x0021: 1, /* VALUE */
  19753. 0x0022: 0, /* TRUE */
  19754. 0x0023: 0, /* FALSE */
  19755. 0x0026: 1, /* NOT */
  19756. 0x0027: 2, /* MOD */
  19757. 0x0028: 3, /* DCOUNT */
  19758. 0x0029: 3, /* DSUM */
  19759. 0x002A: 3, /* DAVERAGE */
  19760. 0x002B: 3, /* DMIN */
  19761. 0x002C: 3, /* DMAX */
  19762. 0x002D: 3, /* DSTDEV */
  19763. 0x002F: 3, /* DVAR */
  19764. 0x0030: 2, /* TEXT */
  19765. 0x0035: 1, /* GOTO */
  19766. 0x003D: 3, /* MIRR */
  19767. 0x003F: 0, /* RAND */
  19768. 0x0041: 3, /* DATE */
  19769. 0x0042: 3, /* TIME */
  19770. 0x0043: 1, /* DAY */
  19771. 0x0044: 1, /* MONTH */
  19772. 0x0045: 1, /* YEAR */
  19773. 0x0046: 1, /* WEEKDAY */
  19774. 0x0047: 1, /* HOUR */
  19775. 0x0048: 1, /* MINUTE */
  19776. 0x0049: 1, /* SECOND */
  19777. 0x004A: 0, /* NOW */
  19778. 0x004B: 1, /* AREAS */
  19779. 0x004C: 1, /* ROWS */
  19780. 0x004D: 1, /* COLUMNS */
  19781. 0x004F: 2, /* ABSREF */
  19782. 0x0050: 2, /* RELREF */
  19783. 0x0053: 1, /* TRANSPOSE */
  19784. 0x0055: 0, /* STEP */
  19785. 0x0056: 1, /* TYPE */
  19786. 0x0059: 0, /* CALLER */
  19787. 0x005A: 1, /* DEREF */
  19788. 0x005E: 0, /* ACTIVE.CELL */
  19789. 0x005F: 0, /* SELECTION */
  19790. 0x0061: 2, /* ATAN2 */
  19791. 0x0062: 1, /* ASIN */
  19792. 0x0063: 1, /* ACOS */
  19793. 0x0065: 3, /* HLOOKUP */
  19794. 0x0066: 3, /* VLOOKUP */
  19795. 0x0069: 1, /* ISREF */
  19796. 0x006A: 1, /* GET.FORMULA */
  19797. 0x006C: 2, /* SET.VALUE */
  19798. 0x006F: 1, /* CHAR */
  19799. 0x0070: 1, /* LOWER */
  19800. 0x0071: 1, /* UPPER */
  19801. 0x0072: 1, /* PROPER */
  19802. 0x0075: 2, /* EXACT */
  19803. 0x0076: 1, /* TRIM */
  19804. 0x0077: 4, /* REPLACE */
  19805. 0x0079: 1, /* CODE */
  19806. 0x007E: 1, /* ISERR */
  19807. 0x007F: 1, /* ISTEXT */
  19808. 0x0080: 1, /* ISNUMBER */
  19809. 0x0081: 1, /* ISBLANK */
  19810. 0x0082: 1, /* T */
  19811. 0x0083: 1, /* N */
  19812. 0x0085: 1, /* FCLOSE */
  19813. 0x0086: 1, /* FSIZE */
  19814. 0x0087: 1, /* FREADLN */
  19815. 0x0088: 2, /* FREAD */
  19816. 0x0089: 2, /* FWRITELN */
  19817. 0x008A: 2, /* FWRITE */
  19818. 0x008C: 1, /* DATEVALUE */
  19819. 0x008D: 1, /* TIMEVALUE */
  19820. 0x008E: 3, /* SLN */
  19821. 0x008F: 4, /* SYD */
  19822. 0x0090: 4, /* DDB */
  19823. 0x00A1: 1, /* DIALOG.BOX */
  19824. 0x00A2: 1, /* CLEAN */
  19825. 0x00A3: 1, /* MDETERM */
  19826. 0x00A4: 1, /* MINVERSE */
  19827. 0x00A5: 2, /* MMULT */
  19828. 0x00AC: 1, /* WHILE */
  19829. 0x00AF: 2, /* INITIATE */
  19830. 0x00B0: 2, /* REQUEST */
  19831. 0x00B1: 3, /* POKE */
  19832. 0x00B2: 2, /* EXECUTE */
  19833. 0x00B3: 1, /* TERMINATE */
  19834. 0x00B8: 1, /* FACT */
  19835. 0x00BA: 1, /* GET.WORKSPACE */
  19836. 0x00BD: 3, /* DPRODUCT */
  19837. 0x00BE: 1, /* ISNONTEXT */
  19838. 0x00C3: 3, /* DSTDEVP */
  19839. 0x00C4: 3, /* DVARP */
  19840. 0x00C5: 1, /* TRUNC */
  19841. 0x00C6: 1, /* ISLOGICAL */
  19842. 0x00C7: 3, /* DCOUNTA */
  19843. 0x00C9: 1, /* UNREGISTER */
  19844. 0x00CF: 4, /* REPLACEB */
  19845. 0x00D2: 3, /* MIDB */
  19846. 0x00D3: 1, /* LENB */
  19847. 0x00D4: 2, /* ROUNDUP */
  19848. 0x00D5: 2, /* ROUNDDOWN */
  19849. 0x00D6: 1, /* ASC */
  19850. 0x00D7: 1, /* DBCS */
  19851. 0x00E1: 0, /* END.IF */
  19852. 0x00E5: 1, /* SINH */
  19853. 0x00E6: 1, /* COSH */
  19854. 0x00E7: 1, /* TANH */
  19855. 0x00E8: 1, /* ASINH */
  19856. 0x00E9: 1, /* ACOSH */
  19857. 0x00EA: 1, /* ATANH */
  19858. 0x00EB: 3, /* DGET */
  19859. 0x00F4: 1, /* INFO */
  19860. 0x00F7: 4, /* DB */
  19861. 0x00FC: 2, /* FREQUENCY */
  19862. 0x0101: 1, /* EVALUATE */
  19863. 0x0105: 1, /* ERROR.TYPE */
  19864. 0x010F: 1, /* GAMMALN */
  19865. 0x0111: 4, /* BINOMDIST */
  19866. 0x0112: 2, /* CHIDIST */
  19867. 0x0113: 2, /* CHIINV */
  19868. 0x0114: 2, /* COMBIN */
  19869. 0x0115: 3, /* CONFIDENCE */
  19870. 0x0116: 3, /* CRITBINOM */
  19871. 0x0117: 1, /* EVEN */
  19872. 0x0118: 3, /* EXPONDIST */
  19873. 0x0119: 3, /* FDIST */
  19874. 0x011A: 3, /* FINV */
  19875. 0x011B: 1, /* FISHER */
  19876. 0x011C: 1, /* FISHERINV */
  19877. 0x011D: 2, /* FLOOR */
  19878. 0x011E: 4, /* GAMMADIST */
  19879. 0x011F: 3, /* GAMMAINV */
  19880. 0x0120: 2, /* CEILING */
  19881. 0x0121: 4, /* HYPGEOMDIST */
  19882. 0x0122: 3, /* LOGNORMDIST */
  19883. 0x0123: 3, /* LOGINV */
  19884. 0x0124: 3, /* NEGBINOMDIST */
  19885. 0x0125: 4, /* NORMDIST */
  19886. 0x0126: 1, /* NORMSDIST */
  19887. 0x0127: 3, /* NORMINV */
  19888. 0x0128: 1, /* NORMSINV */
  19889. 0x0129: 3, /* STANDARDIZE */
  19890. 0x012A: 1, /* ODD */
  19891. 0x012B: 2, /* PERMUT */
  19892. 0x012C: 3, /* POISSON */
  19893. 0x012D: 3, /* TDIST */
  19894. 0x012E: 4, /* WEIBULL */
  19895. 0x012F: 2, /* SUMXMY2 */
  19896. 0x0130: 2, /* SUMX2MY2 */
  19897. 0x0131: 2, /* SUMX2PY2 */
  19898. 0x0132: 2, /* CHITEST */
  19899. 0x0133: 2, /* CORREL */
  19900. 0x0134: 2, /* COVAR */
  19901. 0x0135: 3, /* FORECAST */
  19902. 0x0136: 2, /* FTEST */
  19903. 0x0137: 2, /* INTERCEPT */
  19904. 0x0138: 2, /* PEARSON */
  19905. 0x0139: 2, /* RSQ */
  19906. 0x013A: 2, /* STEYX */
  19907. 0x013B: 2, /* SLOPE */
  19908. 0x013C: 4, /* TTEST */
  19909. 0x0145: 2, /* LARGE */
  19910. 0x0146: 2, /* SMALL */
  19911. 0x0147: 2, /* QUARTILE */
  19912. 0x0148: 2, /* PERCENTILE */
  19913. 0x014B: 2, /* TRIMMEAN */
  19914. 0x014C: 2, /* TINV */
  19915. 0x0151: 2, /* POWER */
  19916. 0x0156: 1, /* RADIANS */
  19917. 0x0157: 1, /* DEGREES */
  19918. 0x015A: 2, /* COUNTIF */
  19919. 0x015B: 1, /* COUNTBLANK */
  19920. 0x015E: 4, /* ISPMT */
  19921. 0x015F: 3, /* DATEDIF */
  19922. 0x0160: 1, /* DATESTRING */
  19923. 0x0161: 2, /* NUMBERSTRING */
  19924. 0x0168: 1, /* PHONETIC */
  19925. 0x0170: 1, /* BAHTTEXT */
  19926. 0x0171: 1, /* THAIDAYOFWEEK */
  19927. 0x0172: 1, /* THAIDIGIT */
  19928. 0x0173: 1, /* THAIMONTHOFYEAR */
  19929. 0x0174: 1, /* THAINUMSOUND */
  19930. 0x0175: 1, /* THAINUMSTRING */
  19931. 0x0176: 1, /* THAISTRINGLENGTH */
  19932. 0x0177: 1, /* ISTHAIDIGIT */
  19933. 0x0178: 1, /* ROUNDBAHTDOWN */
  19934. 0x0179: 1, /* ROUNDBAHTUP */
  19935. 0x017A: 1, /* THAIYEAR */
  19936. 0x017E: 3, /* CUBEMEMBERPROPERTY */
  19937. 0x0181: 1, /* HEX2DEC */
  19938. 0x0188: 1, /* OCT2DEC */
  19939. 0x0189: 1, /* BIN2DEC */
  19940. 0x018C: 2, /* IMSUB */
  19941. 0x018D: 2, /* IMDIV */
  19942. 0x018E: 2, /* IMPOWER */
  19943. 0x018F: 1, /* IMABS */
  19944. 0x0190: 1, /* IMSQRT */
  19945. 0x0191: 1, /* IMLN */
  19946. 0x0192: 1, /* IMLOG2 */
  19947. 0x0193: 1, /* IMLOG10 */
  19948. 0x0194: 1, /* IMSIN */
  19949. 0x0195: 1, /* IMCOS */
  19950. 0x0196: 1, /* IMEXP */
  19951. 0x0197: 1, /* IMARGUMENT */
  19952. 0x0198: 1, /* IMCONJUGATE */
  19953. 0x0199: 1, /* IMAGINARY */
  19954. 0x019A: 1, /* IMREAL */
  19955. 0x019E: 4, /* SERIESSUM */
  19956. 0x019F: 1, /* FACTDOUBLE */
  19957. 0x01A0: 1, /* SQRTPI */
  19958. 0x01A1: 2, /* QUOTIENT */
  19959. 0x01A4: 1, /* ISEVEN */
  19960. 0x01A5: 1, /* ISODD */
  19961. 0x01A6: 2, /* MROUND */
  19962. 0x01A8: 1, /* ERFC */
  19963. 0x01A9: 2, /* BESSELJ */
  19964. 0x01AA: 2, /* BESSELK */
  19965. 0x01AB: 2, /* BESSELY */
  19966. 0x01AC: 2, /* BESSELI */
  19967. 0x01AE: 3, /* XNPV */
  19968. 0x01B6: 3, /* TBILLEQ */
  19969. 0x01B7: 3, /* TBILLPRICE */
  19970. 0x01B8: 3, /* TBILLYIELD */
  19971. 0x01BB: 2, /* DOLLARDE */
  19972. 0x01BC: 2, /* DOLLARFR */
  19973. 0x01BD: 2, /* NOMINAL */
  19974. 0x01BE: 2, /* EFFECT */
  19975. 0x01BF: 6, /* CUMPRINC */
  19976. 0x01C0: 6, /* CUMIPMT */
  19977. 0x01C1: 2, /* EDATE */
  19978. 0x01C2: 2, /* EOMONTH */
  19979. 0x01D0: 2, /* RANDBETWEEN */
  19980. 0x01D4: 3, /* CONVERT */
  19981. 0x01DC: 2, /* FVSCHEDULE */
  19982. 0x01DF: 1, /* CUBESETCOUNT */
  19983. 0x01E0: 2, /* IFERROR */
  19984. 0xFFFF: 0
  19985. };
  19986. /* [MS-XLSX] 2.2.3 Functions */
  19987. /* [MS-XLSB] 2.5.97.10 Ftab */
  19988. var XLSXFutureFunctions = {
  19989. "_xlfn.ACOT": "ACOT",
  19990. "_xlfn.ACOTH": "ACOTH",
  19991. "_xlfn.AGGREGATE": "AGGREGATE",
  19992. "_xlfn.ARABIC": "ARABIC",
  19993. "_xlfn.AVERAGEIF": "AVERAGEIF",
  19994. "_xlfn.AVERAGEIFS": "AVERAGEIFS",
  19995. "_xlfn.BASE": "BASE",
  19996. "_xlfn.BETA.DIST": "BETA.DIST",
  19997. "_xlfn.BETA.INV": "BETA.INV",
  19998. "_xlfn.BINOM.DIST": "BINOM.DIST",
  19999. "_xlfn.BINOM.DIST.RANGE": "BINOM.DIST.RANGE",
  20000. "_xlfn.BINOM.INV": "BINOM.INV",
  20001. "_xlfn.BITAND": "BITAND",
  20002. "_xlfn.BITLSHIFT": "BITLSHIFT",
  20003. "_xlfn.BITOR": "BITOR",
  20004. "_xlfn.BITRSHIFT": "BITRSHIFT",
  20005. "_xlfn.BITXOR": "BITXOR",
  20006. "_xlfn.CEILING.MATH": "CEILING.MATH",
  20007. "_xlfn.CEILING.PRECISE": "CEILING.PRECISE",
  20008. "_xlfn.CHISQ.DIST": "CHISQ.DIST",
  20009. "_xlfn.CHISQ.DIST.RT": "CHISQ.DIST.RT",
  20010. "_xlfn.CHISQ.INV": "CHISQ.INV",
  20011. "_xlfn.CHISQ.INV.RT": "CHISQ.INV.RT",
  20012. "_xlfn.CHISQ.TEST": "CHISQ.TEST",
  20013. "_xlfn.COMBINA": "COMBINA",
  20014. "_xlfn.CONCAT": "CONCAT",
  20015. "_xlfn.CONFIDENCE.NORM": "CONFIDENCE.NORM",
  20016. "_xlfn.CONFIDENCE.T": "CONFIDENCE.T",
  20017. "_xlfn.COT": "COT",
  20018. "_xlfn.COTH": "COTH",
  20019. "_xlfn.COUNTIFS": "COUNTIFS",
  20020. "_xlfn.COVARIANCE.P": "COVARIANCE.P",
  20021. "_xlfn.COVARIANCE.S": "COVARIANCE.S",
  20022. "_xlfn.CSC": "CSC",
  20023. "_xlfn.CSCH": "CSCH",
  20024. "_xlfn.DAYS": "DAYS",
  20025. "_xlfn.DECIMAL": "DECIMAL",
  20026. "_xlfn.ECMA.CEILING": "ECMA.CEILING",
  20027. "_xlfn.ERF.PRECISE": "ERF.PRECISE",
  20028. "_xlfn.ERFC.PRECISE": "ERFC.PRECISE",
  20029. "_xlfn.EXPON.DIST": "EXPON.DIST",
  20030. "_xlfn.F.DIST": "F.DIST",
  20031. "_xlfn.F.DIST.RT": "F.DIST.RT",
  20032. "_xlfn.F.INV": "F.INV",
  20033. "_xlfn.F.INV.RT": "F.INV.RT",
  20034. "_xlfn.F.TEST": "F.TEST",
  20035. "_xlfn.FILTERXML": "FILTERXML",
  20036. "_xlfn.FLOOR.MATH": "FLOOR.MATH",
  20037. "_xlfn.FLOOR.PRECISE": "FLOOR.PRECISE",
  20038. "_xlfn.FORECAST.ETS": "FORECAST.ETS",
  20039. "_xlfn.FORECAST.ETS.CONFINT": "FORECAST.ETS.CONFINT",
  20040. "_xlfn.FORECAST.ETS.SEASONALITY": "FORECAST.ETS.SEASONALITY",
  20041. "_xlfn.FORECAST.ETS.STAT": "FORECAST.ETS.STAT",
  20042. "_xlfn.FORECAST.LINEAR": "FORECAST.LINEAR",
  20043. "_xlfn.FORMULATEXT": "FORMULATEXT",
  20044. "_xlfn.GAMMA": "GAMMA",
  20045. "_xlfn.GAMMA.DIST": "GAMMA.DIST",
  20046. "_xlfn.GAMMA.INV": "GAMMA.INV",
  20047. "_xlfn.GAMMALN.PRECISE": "GAMMALN.PRECISE",
  20048. "_xlfn.GAUSS": "GAUSS",
  20049. "_xlfn.HYPGEOM.DIST": "HYPGEOM.DIST",
  20050. "_xlfn.IFERROR": "IFERROR",
  20051. "_xlfn.IFNA": "IFNA",
  20052. "_xlfn.IFS": "IFS",
  20053. "_xlfn.IMCOSH": "IMCOSH",
  20054. "_xlfn.IMCOT": "IMCOT",
  20055. "_xlfn.IMCSC": "IMCSC",
  20056. "_xlfn.IMCSCH": "IMCSCH",
  20057. "_xlfn.IMSEC": "IMSEC",
  20058. "_xlfn.IMSECH": "IMSECH",
  20059. "_xlfn.IMSINH": "IMSINH",
  20060. "_xlfn.IMTAN": "IMTAN",
  20061. "_xlfn.ISFORMULA": "ISFORMULA",
  20062. "_xlfn.ISO.CEILING": "ISO.CEILING",
  20063. "_xlfn.ISOWEEKNUM": "ISOWEEKNUM",
  20064. "_xlfn.LOGNORM.DIST": "LOGNORM.DIST",
  20065. "_xlfn.LOGNORM.INV": "LOGNORM.INV",
  20066. "_xlfn.MAXIFS": "MAXIFS",
  20067. "_xlfn.MINIFS": "MINIFS",
  20068. "_xlfn.MODE.MULT": "MODE.MULT",
  20069. "_xlfn.MODE.SNGL": "MODE.SNGL",
  20070. "_xlfn.MUNIT": "MUNIT",
  20071. "_xlfn.NEGBINOM.DIST": "NEGBINOM.DIST",
  20072. "_xlfn.NETWORKDAYS.INTL": "NETWORKDAYS.INTL",
  20073. "_xlfn.NIGBINOM": "NIGBINOM",
  20074. "_xlfn.NORM.DIST": "NORM.DIST",
  20075. "_xlfn.NORM.INV": "NORM.INV",
  20076. "_xlfn.NORM.S.DIST": "NORM.S.DIST",
  20077. "_xlfn.NORM.S.INV": "NORM.S.INV",
  20078. "_xlfn.NUMBERVALUE": "NUMBERVALUE",
  20079. "_xlfn.PDURATION": "PDURATION",
  20080. "_xlfn.PERCENTILE.EXC": "PERCENTILE.EXC",
  20081. "_xlfn.PERCENTILE.INC": "PERCENTILE.INC",
  20082. "_xlfn.PERCENTRANK.EXC": "PERCENTRANK.EXC",
  20083. "_xlfn.PERCENTRANK.INC": "PERCENTRANK.INC",
  20084. "_xlfn.PERMUTATIONA": "PERMUTATIONA",
  20085. "_xlfn.PHI": "PHI",
  20086. "_xlfn.POISSON.DIST": "POISSON.DIST",
  20087. "_xlfn.QUARTILE.EXC": "QUARTILE.EXC",
  20088. "_xlfn.QUARTILE.INC": "QUARTILE.INC",
  20089. "_xlfn.QUERYSTRING": "QUERYSTRING",
  20090. "_xlfn.RANK.AVG": "RANK.AVG",
  20091. "_xlfn.RANK.EQ": "RANK.EQ",
  20092. "_xlfn.RRI": "RRI",
  20093. "_xlfn.SEC": "SEC",
  20094. "_xlfn.SECH": "SECH",
  20095. "_xlfn.SHEET": "SHEET",
  20096. "_xlfn.SHEETS": "SHEETS",
  20097. "_xlfn.SKEW.P": "SKEW.P",
  20098. "_xlfn.STDEV.P": "STDEV.P",
  20099. "_xlfn.STDEV.S": "STDEV.S",
  20100. "_xlfn.SUMIFS": "SUMIFS",
  20101. "_xlfn.SWITCH": "SWITCH",
  20102. "_xlfn.T.DIST": "T.DIST",
  20103. "_xlfn.T.DIST.2T": "T.DIST.2T",
  20104. "_xlfn.T.DIST.RT": "T.DIST.RT",
  20105. "_xlfn.T.INV": "T.INV",
  20106. "_xlfn.T.INV.2T": "T.INV.2T",
  20107. "_xlfn.T.TEST": "T.TEST",
  20108. "_xlfn.TEXTJOIN": "TEXTJOIN",
  20109. "_xlfn.UNICHAR": "UNICHAR",
  20110. "_xlfn.UNICODE": "UNICODE",
  20111. "_xlfn.VAR.P": "VAR.P",
  20112. "_xlfn.VAR.S": "VAR.S",
  20113. "_xlfn.WEBSERVICE": "WEBSERVICE",
  20114. "_xlfn.WEIBULL.DIST": "WEIBULL.DIST",
  20115. "_xlfn.WORKDAY.INTL": "WORKDAY.INTL",
  20116. "_xlfn.XOR": "XOR",
  20117. "_xlfn.Z.TEST": "Z.TEST"
  20118. };
  20119. /* Part 3 TODO: actually parse formulae */
  20120. function ods_to_csf_formula(f) {
  20121. if(f.slice(0,3) == "of:") f = f.slice(3);
  20122. /* 5.2 Basic Expressions */
  20123. if(f.charCodeAt(0) == 61) {
  20124. f = f.slice(1);
  20125. if(f.charCodeAt(0) == 61) f = f.slice(1);
  20126. }
  20127. f = f.replace(/COM\.MICROSOFT\./g, "");
  20128. /* Part 3 Section 5.8 References */
  20129. f = f.replace(/\[((?:\.[A-Z]+[0-9]+)(?::\.[A-Z]+[0-9]+)?)\]/g, function($$, $1) { return $1.replace(/\./g,""); });
  20130. /* TODO: something other than this */
  20131. f = f.replace(/\[.(#[A-Z]*[?!])\]/g, "$1");
  20132. return f.replace(/[;~]/g,",").replace(/\|/g,";");
  20133. }
  20134. function csf_to_ods_formula(f) {
  20135. var o = "of:=" + f.replace(crefregex, "$1[.$2$3$4$5]").replace(/\]:\[/g,":");
  20136. /* TODO: something other than this */
  20137. return o.replace(/;/g, "|").replace(/,/g,";");
  20138. }
  20139. function ods_to_csf_3D(r) {
  20140. var a = r.split(":");
  20141. var s = a[0].split(".")[0];
  20142. return [s, a[0].split(".")[1] + (a.length > 1 ? (":" + (a[1].split(".")[1] || a[1].split(".")[0])) : "")];
  20143. }
  20144. function csf_to_ods_3D(r) {
  20145. return r.replace(/\./,"!");
  20146. }
  20147. var strs = {}; // shared strings
  20148. var _ssfopts = {}; // spreadsheet formatting options
  20149. RELS.WS = [
  20150. "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
  20151. "http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet"
  20152. ];
  20153. /*global Map */
  20154. var browser_has_Map = typeof Map !== 'undefined';
  20155. function get_sst_id(sst, str, rev) {
  20156. var i = 0, len = sst.length;
  20157. if(rev) {
  20158. if(browser_has_Map ? rev.has(str) : Object.prototype.hasOwnProperty.call(rev, str)) {
  20159. var revarr = browser_has_Map ? rev.get(str) : rev[str];
  20160. for(; i < revarr.length; ++i) {
  20161. if(sst[revarr[i]].t === str) { sst.Count ++; return revarr[i]; }
  20162. }
  20163. }
  20164. } else for(; i < len; ++i) {
  20165. if(sst[i].t === str) { sst.Count ++; return i; }
  20166. }
  20167. sst[len] = ({t:str}); sst.Count ++; sst.Unique ++;
  20168. if(rev) {
  20169. if(browser_has_Map) {
  20170. if(!rev.has(str)) rev.set(str, []);
  20171. rev.get(str).push(len);
  20172. } else {
  20173. if(!Object.prototype.hasOwnProperty.call(rev, str)) rev[str] = [];
  20174. rev[str].push(len);
  20175. }
  20176. }
  20177. return len;
  20178. }
  20179. function col_obj_w(C, col) {
  20180. var p = ({min:C+1,max:C+1});
  20181. /* wch (chars), wpx (pixels) */
  20182. var wch = -1;
  20183. if(col.MDW) MDW = col.MDW;
  20184. if(col.width != null) p.customWidth = 1;
  20185. else if(col.wpx != null) wch = px2char(col.wpx);
  20186. else if(col.wch != null) wch = col.wch;
  20187. if(wch > -1) { p.width = char2width(wch); p.customWidth = 1; }
  20188. else if(col.width != null) p.width = col.width;
  20189. if(col.hidden) p.hidden = true;
  20190. return p;
  20191. }
  20192. function default_margins(margins, mode) {
  20193. if(!margins) return;
  20194. var defs = [0.7, 0.7, 0.75, 0.75, 0.3, 0.3];
  20195. if(mode == 'xlml') defs = [1, 1, 1, 1, 0.5, 0.5];
  20196. if(margins.left == null) margins.left = defs[0];
  20197. if(margins.right == null) margins.right = defs[1];
  20198. if(margins.top == null) margins.top = defs[2];
  20199. if(margins.bottom == null) margins.bottom = defs[3];
  20200. if(margins.header == null) margins.header = defs[4];
  20201. if(margins.footer == null) margins.footer = defs[5];
  20202. }
  20203. function get_cell_style(styles, cell, opts) {
  20204. var z = opts.revssf[cell.z != null ? cell.z : "General"];
  20205. var i = 0x3c, len = styles.length;
  20206. if(z == null && opts.ssf) {
  20207. for(; i < 0x188; ++i) if(opts.ssf[i] == null) {
  20208. SSF.load(cell.z, i);
  20209. // $FlowIgnore
  20210. opts.ssf[i] = cell.z;
  20211. opts.revssf[cell.z] = z = i;
  20212. break;
  20213. }
  20214. }
  20215. for(i = 0; i != len; ++i) if(styles[i].numFmtId === z) return i;
  20216. styles[len] = {
  20217. numFmtId:z,
  20218. fontId:0,
  20219. fillId:0,
  20220. borderId:0,
  20221. xfId:0,
  20222. applyNumberFormat:1
  20223. };
  20224. return len;
  20225. }
  20226. function safe_format(p, fmtid, fillid, opts, themes, styles) {
  20227. try {
  20228. if(opts.cellNF) p.z = SSF._table[fmtid];
  20229. } catch(e) { if(opts.WTF) throw e; }
  20230. if(p.t === 'z') return;
  20231. if(p.t === 'd' && typeof p.v === 'string') p.v = parseDate(p.v);
  20232. if(!opts || opts.cellText !== false) try {
  20233. if(SSF._table[fmtid] == null) SSF.load(SSFImplicit[fmtid] || "General", fmtid);
  20234. if(p.t === 'e') p.w = p.w || BErr[p.v];
  20235. else if(fmtid === 0) {
  20236. if(p.t === 'n') {
  20237. if((p.v|0) === p.v) p.w = SSF._general_int(p.v);
  20238. else p.w = SSF._general_num(p.v);
  20239. }
  20240. else if(p.t === 'd') {
  20241. var dd = datenum(p.v);
  20242. if((dd|0) === dd) p.w = SSF._general_int(dd);
  20243. else p.w = SSF._general_num(dd);
  20244. }
  20245. else if(p.v === undefined) return "";
  20246. else p.w = SSF._general(p.v,_ssfopts);
  20247. }
  20248. else if(p.t === 'd') p.w = SSF.format(fmtid,datenum(p.v),_ssfopts);
  20249. else p.w = SSF.format(fmtid,p.v,_ssfopts);
  20250. } catch(e) { if(opts.WTF) throw e; }
  20251. if(!opts.cellStyles) return;
  20252. if(fillid != null) try {
  20253. p.s = styles.Fills[fillid];
  20254. if (p.s.fgColor && p.s.fgColor.theme && !p.s.fgColor.rgb) {
  20255. p.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.fgColor.theme].rgb, p.s.fgColor.tint || 0);
  20256. if(opts.WTF) p.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p.s.fgColor.theme].rgb;
  20257. }
  20258. if (p.s.bgColor && p.s.bgColor.theme) {
  20259. p.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.bgColor.theme].rgb, p.s.bgColor.tint || 0);
  20260. if(opts.WTF) p.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p.s.bgColor.theme].rgb;
  20261. }
  20262. } catch(e) { if(opts.WTF && styles.Fills) throw e; }
  20263. }
  20264. function check_ws(ws, sname, i) {
  20265. if(ws && ws['!ref']) {
  20266. var range = safe_decode_range(ws['!ref']);
  20267. if(range.e.c < range.s.c || range.e.r < range.s.r) throw new Error("Bad range (" + i + "): " + ws['!ref']);
  20268. }
  20269. }
  20270. function parse_ws_xml_dim(ws, s) {
  20271. var d = safe_decode_range(s);
  20272. if(d.s.r<=d.e.r && d.s.c<=d.e.c && d.s.r>=0 && d.s.c>=0) ws["!ref"] = encode_range(d);
  20273. }
  20274. var mergecregex = /<(?:\w:)?mergeCell ref="[A-Z0-9:]+"\s*[\/]?>/g;
  20275. var sheetdataregex = /<(?:\w+:)?sheetData[^>]*>([\s\S]*)<\/(?:\w+:)?sheetData>/;
  20276. var hlinkregex = /<(?:\w:)?hyperlink [^>]*>/mg;
  20277. var dimregex = /"(\w*:\w*)"/;
  20278. var colregex = /<(?:\w:)?col\b[^>]*[\/]?>/g;
  20279. var afregex = /<(?:\w:)?autoFilter[^>]*([\/]|>([\s\S]*)<\/(?:\w:)?autoFilter)>/g;
  20280. var marginregex= /<(?:\w:)?pageMargins[^>]*\/>/g;
  20281. var sheetprregex = /<(?:\w:)?sheetPr\b(?:[^>a-z][^>]*)?\/>/;
  20282. var svsregex = /<(?:\w:)?sheetViews[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetViews)>/;
  20283. /* 18.3 Worksheets */
  20284. function parse_ws_xml(data, opts, idx, rels, wb, themes, styles) {
  20285. if(!data) return data;
  20286. if(!rels) rels = {'!id':{}};
  20287. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  20288. /* 18.3.1.99 worksheet CT_Worksheet */
  20289. var s = opts.dense ? ([]) : ({});
  20290. var refguess = ({s: {r:2000000, c:2000000}, e: {r:0, c:0} });
  20291. var data1 = "", data2 = "";
  20292. var mtch = data.match(sheetdataregex);
  20293. if(mtch) {
  20294. data1 = data.slice(0, mtch.index);
  20295. data2 = data.slice(mtch.index + mtch[0].length);
  20296. } else data1 = data2 = data;
  20297. /* 18.3.1.82 sheetPr CT_SheetPr */
  20298. var sheetPr = data1.match(sheetprregex);
  20299. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  20300. /* 18.3.1.35 dimension CT_SheetDimension */
  20301. var ridx = (data1.match(/<(?:\w*:)?dimension/)||{index:-1}).index;
  20302. if(ridx > 0) {
  20303. var ref = data1.slice(ridx,ridx+50).match(dimregex);
  20304. if(ref) parse_ws_xml_dim(s, ref[1]);
  20305. }
  20306. /* 18.3.1.88 sheetViews CT_SheetViews */
  20307. var svs = data1.match(svsregex);
  20308. if(svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb);
  20309. /* 18.3.1.17 cols CT_Cols */
  20310. var columns = [];
  20311. if(opts.cellStyles) {
  20312. /* 18.3.1.13 col CT_Col */
  20313. var cols = data1.match(colregex);
  20314. if(cols) parse_ws_xml_cols(columns, cols);
  20315. }
  20316. /* 18.3.1.80 sheetData CT_SheetData ? */
  20317. if(mtch) parse_ws_xml_data(mtch[1], s, opts, refguess, themes, styles);
  20318. /* 18.3.1.2 autoFilter CT_AutoFilter */
  20319. var afilter = data2.match(afregex);
  20320. if(afilter) s['!autofilter'] = parse_ws_xml_autofilter(afilter[0]);
  20321. /* 18.3.1.55 mergeCells CT_MergeCells */
  20322. var merges = [];
  20323. var _merge = data2.match(mergecregex);
  20324. if(_merge) for(ridx = 0; ridx != _merge.length; ++ridx)
  20325. merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("\"")+1));
  20326. /* 18.3.1.48 hyperlinks CT_Hyperlinks */
  20327. var hlink = data2.match(hlinkregex);
  20328. if(hlink) parse_ws_xml_hlinks(s, hlink, rels);
  20329. /* 18.3.1.62 pageMargins CT_PageMargins */
  20330. var margins = data2.match(marginregex);
  20331. if(margins) s['!margins'] = parse_ws_xml_margins(parsexmltag(margins[0]));
  20332. if(!s["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s["!ref"] = encode_range(refguess);
  20333. if(opts.sheetRows > 0 && s["!ref"]) {
  20334. var tmpref = safe_decode_range(s["!ref"]);
  20335. if(opts.sheetRows <= +tmpref.e.r) {
  20336. tmpref.e.r = opts.sheetRows - 1;
  20337. if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
  20338. if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
  20339. if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
  20340. if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
  20341. s["!fullref"] = s["!ref"];
  20342. s["!ref"] = encode_range(tmpref);
  20343. }
  20344. }
  20345. if(columns.length > 0) s["!cols"] = columns;
  20346. if(merges.length > 0) s["!merges"] = merges;
  20347. return s;
  20348. }
  20349. function write_ws_xml_merges(merges) {
  20350. if(merges.length === 0) return "";
  20351. var o = '<mergeCells count="' + merges.length + '">';
  20352. for(var i = 0; i != merges.length; ++i) o += '<mergeCell ref="' + encode_range(merges[i]) + '"/>';
  20353. return o + '</mergeCells>';
  20354. }
  20355. /* 18.3.1.82-3 sheetPr CT_ChartsheetPr / CT_SheetPr */
  20356. function parse_ws_xml_sheetpr(sheetPr, s, wb, idx) {
  20357. var data = parsexmltag(sheetPr);
  20358. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  20359. if(data.codeName) wb.Sheets[idx].CodeName = unescapexml(utf8read(data.codeName));
  20360. }
  20361. function write_ws_xml_sheetpr(ws, wb, idx, opts, o) {
  20362. var needed = false;
  20363. var props = {}, payload = null;
  20364. if(opts.bookType !== 'xlsx' && wb.vbaraw) {
  20365. var cname = wb.SheetNames[idx];
  20366. try { if(wb.Workbook) cname = wb.Workbook.Sheets[idx].CodeName || cname; } catch(e) {}
  20367. needed = true;
  20368. props.codeName = utf8write(escapexml(cname));
  20369. }
  20370. if(ws && ws["!outline"]) {
  20371. var outlineprops = {summaryBelow:1, summaryRight:1};
  20372. if(ws["!outline"].above) outlineprops.summaryBelow = 0;
  20373. if(ws["!outline"].left) outlineprops.summaryRight = 0;
  20374. payload = (payload||"") + writextag('outlinePr', null, outlineprops);
  20375. }
  20376. if(!needed && !payload) return;
  20377. o[o.length] = (writextag('sheetPr', payload, props));
  20378. }
  20379. /* 18.3.1.85 sheetProtection CT_SheetProtection */
  20380. var sheetprot_deffalse = ["objects", "scenarios", "selectLockedCells", "selectUnlockedCells"];
  20381. var sheetprot_deftrue = [
  20382. "formatColumns", "formatRows", "formatCells",
  20383. "insertColumns", "insertRows", "insertHyperlinks",
  20384. "deleteColumns", "deleteRows",
  20385. "sort", "autoFilter", "pivotTables"
  20386. ];
  20387. function write_ws_xml_protection(sp) {
  20388. // algorithmName, hashValue, saltValue, spinCount
  20389. var o = ({sheet:1});
  20390. sheetprot_deffalse.forEach(function(n) { if(sp[n] != null && sp[n]) o[n] = "1"; });
  20391. sheetprot_deftrue.forEach(function(n) { if(sp[n] != null && !sp[n]) o[n] = "0"; });
  20392. /* TODO: algorithm */
  20393. if(sp.password) o.password = crypto_CreatePasswordVerifier_Method1(sp.password).toString(16).toUpperCase();
  20394. return writextag('sheetProtection', null, o);
  20395. }
  20396. function parse_ws_xml_hlinks(s, data, rels) {
  20397. var dense = Array.isArray(s);
  20398. for(var i = 0; i != data.length; ++i) {
  20399. var val = parsexmltag(utf8read(data[i]), true);
  20400. if(!val.ref) return;
  20401. var rel = ((rels || {})['!id']||[])[val.id];
  20402. if(rel) {
  20403. val.Target = rel.Target;
  20404. if(val.location) val.Target += "#"+val.location;
  20405. } else {
  20406. val.Target = "#" + val.location;
  20407. rel = {Target: val.Target, TargetMode: 'Internal'};
  20408. }
  20409. val.Rel = rel;
  20410. if(val.tooltip) { val.Tooltip = val.tooltip; delete val.tooltip; }
  20411. var rng = safe_decode_range(val.ref);
  20412. for(var R=rng.s.r;R<=rng.e.r;++R) for(var C=rng.s.c;C<=rng.e.c;++C) {
  20413. var addr = encode_cell({c:C,r:R});
  20414. if(dense) {
  20415. if(!s[R]) s[R] = [];
  20416. if(!s[R][C]) s[R][C] = {t:"z",v:undefined};
  20417. s[R][C].l = val;
  20418. } else {
  20419. if(!s[addr]) s[addr] = {t:"z",v:undefined};
  20420. s[addr].l = val;
  20421. }
  20422. }
  20423. }
  20424. }
  20425. function parse_ws_xml_margins(margin) {
  20426. var o = {};
  20427. ["left", "right", "top", "bottom", "header", "footer"].forEach(function(k) {
  20428. if(margin[k]) o[k] = parseFloat(margin[k]);
  20429. });
  20430. return o;
  20431. }
  20432. function write_ws_xml_margins(margin) {
  20433. default_margins(margin);
  20434. return writextag('pageMargins', null, margin);
  20435. }
  20436. function parse_ws_xml_cols(columns, cols) {
  20437. var seencol = false;
  20438. for(var coli = 0; coli != cols.length; ++coli) {
  20439. var coll = parsexmltag(cols[coli], true);
  20440. if(coll.hidden) coll.hidden = parsexmlbool(coll.hidden);
  20441. var colm=parseInt(coll.min, 10)-1, colM=parseInt(coll.max,10)-1;
  20442. delete coll.min; delete coll.max; coll.width = +coll.width;
  20443. if(!seencol && coll.width) { seencol = true; find_mdw_colw(coll.width); }
  20444. process_col(coll);
  20445. while(colm <= colM) columns[colm++] = dup(coll);
  20446. }
  20447. }
  20448. function write_ws_xml_cols(ws, cols) {
  20449. var o = ["<cols>"], col;
  20450. for(var i = 0; i != cols.length; ++i) {
  20451. if(!(col = cols[i])) continue;
  20452. o[o.length] = (writextag('col', null, col_obj_w(i, col)));
  20453. }
  20454. o[o.length] = "</cols>";
  20455. return o.join("");
  20456. }
  20457. function parse_ws_xml_autofilter(data) {
  20458. var o = { ref: (data.match(/ref="([^"]*)"/)||[])[1]};
  20459. return o;
  20460. }
  20461. function write_ws_xml_autofilter(data, ws, wb, idx) {
  20462. var ref = typeof data.ref == "string" ? data.ref : encode_range(data.ref);
  20463. if(!wb.Workbook) wb.Workbook = ({Sheets:[]});
  20464. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  20465. var names = wb.Workbook.Names;
  20466. var range = decode_range(ref);
  20467. if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
  20468. for(var i = 0; i < names.length; ++i) {
  20469. var name = names[i];
  20470. if(name.Name != '_xlnm._FilterDatabase') continue;
  20471. if(name.Sheet != idx) continue;
  20472. name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
  20473. }
  20474. if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref });
  20475. return writextag("autoFilter", null, {ref:ref});
  20476. }
  20477. /* 18.3.1.88 sheetViews CT_SheetViews */
  20478. /* 18.3.1.87 sheetView CT_SheetView */
  20479. var sviewregex = /<(?:\w:)?sheetView(?:[^>a-z][^>]*)?\/?>/;
  20480. function parse_ws_xml_sheetviews(data, wb) {
  20481. if(!wb.Views) wb.Views = [{}];
  20482. (data.match(sviewregex)||[]).forEach(function(r, i) {
  20483. var tag = parsexmltag(r);
  20484. // $FlowIgnore
  20485. if(!wb.Views[i]) wb.Views[i] = {};
  20486. // $FlowIgnore
  20487. if(parsexmlbool(tag.rightToLeft)) wb.Views[i].RTL = true;
  20488. });
  20489. }
  20490. function write_ws_xml_sheetviews(ws, opts, idx, wb) {
  20491. var sview = ({workbookViewId:"0"});
  20492. // $FlowIgnore
  20493. if((((wb||{}).Workbook||{}).Views||[])[0]) sview.rightToLeft = wb.Workbook.Views[0].RTL ? "1" : "0";
  20494. return writextag("sheetViews", writextag("sheetView", null, sview), {});
  20495. }
  20496. function write_ws_xml_cell(cell, ref, ws, opts) {
  20497. if(cell.v === undefined && typeof cell.f !== "string" || cell.t === 'z') return "";
  20498. var vv = "";
  20499. var oldt = cell.t, oldv = cell.v;
  20500. if(cell.t !== "z") switch(cell.t) {
  20501. case 'b': vv = cell.v ? "1" : "0"; break;
  20502. case 'n': vv = ''+cell.v; break;
  20503. case 'e': vv = BErr[cell.v]; break;
  20504. case 'd':
  20505. if(opts && opts.cellDates) vv = parseDate(cell.v, -1).toISOString();
  20506. else {
  20507. cell = dup(cell);
  20508. cell.t = 'n';
  20509. vv = ''+(cell.v = datenum(parseDate(cell.v)));
  20510. }
  20511. if(typeof cell.z === 'undefined') cell.z = SSF._table[14];
  20512. break;
  20513. default: vv = cell.v; break;
  20514. }
  20515. var v = writetag('v', escapexml(vv)), o = ({r:ref});
  20516. /* TODO: cell style */
  20517. var os = get_cell_style(opts.cellXfs, cell, opts);
  20518. if(os !== 0) o.s = os;
  20519. switch(cell.t) {
  20520. case 'n': break;
  20521. case 'd': o.t = "d"; break;
  20522. case 'b': o.t = "b"; break;
  20523. case 'e': o.t = "e"; break;
  20524. case 'z': break;
  20525. default: if(cell.v == null) { delete cell.t; break; }
  20526. if(opts && opts.bookSST) {
  20527. v = writetag('v', ''+get_sst_id(opts.Strings, cell.v, opts.revStrings));
  20528. o.t = "s"; break;
  20529. }
  20530. o.t = "str"; break;
  20531. }
  20532. if(cell.t != oldt) { cell.t = oldt; cell.v = oldv; }
  20533. if(typeof cell.f == "string" && cell.f) {
  20534. var ff = cell.F && cell.F.slice(0, ref.length) == ref ? {t:"array", ref:cell.F} : null;
  20535. v = writextag('f', escapexml(cell.f), ff) + (cell.v != null ? v : "");
  20536. }
  20537. if(cell.l) ws['!links'].push([ref, cell.l]);
  20538. if(cell.c) ws['!comments'].push([ref, cell.c]);
  20539. return writextag('c', v, o);
  20540. }
  20541. var parse_ws_xml_data = (function() {
  20542. var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/;
  20543. var rregex = /r=["']([^"']*)["']/, isregex = /<(?:\w+:)?is>([\S\s]*?)<\/(?:\w+:)?is>/;
  20544. var refregex = /ref=["']([^"']*)["']/;
  20545. var match_v = matchtag("v"), match_f = matchtag("f");
  20546. return function parse_ws_xml_data(sdata, s, opts, guess, themes, styles) {
  20547. var ri = 0, x = "", cells = [], cref = [], idx=0, i=0, cc=0, d="", p;
  20548. var tag, tagr = 0, tagc = 0;
  20549. var sstr, ftag;
  20550. var fmtid = 0, fillid = 0;
  20551. var do_format = Array.isArray(styles.CellXf), cf;
  20552. var arrayf = [];
  20553. var sharedf = [];
  20554. var dense = Array.isArray(s);
  20555. var rows = [], rowobj = {}, rowrite = false;
  20556. var sheetStubs = !!opts.sheetStubs;
  20557. for(var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
  20558. x = marr[mt].trim();
  20559. var xlen = x.length;
  20560. if(xlen === 0) continue;
  20561. /* 18.3.1.73 row CT_Row */
  20562. for(ri = 0; ri < xlen; ++ri) if(x.charCodeAt(ri) === 62) break; ++ri;
  20563. tag = parsexmltag(x.slice(0,ri), true);
  20564. tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
  20565. if(opts.sheetRows && opts.sheetRows < tagr) continue;
  20566. if(guess.s.r > tagr - 1) guess.s.r = tagr - 1;
  20567. if(guess.e.r < tagr - 1) guess.e.r = tagr - 1;
  20568. if(opts && opts.cellStyles) {
  20569. rowobj = {}; rowrite = false;
  20570. if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
  20571. if(tag.hidden == "1") { rowrite = true; rowobj.hidden = true; }
  20572. if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
  20573. if(rowrite) rows[tagr-1] = rowobj;
  20574. }
  20575. /* 18.3.1.4 c CT_Cell */
  20576. cells = x.slice(ri).split(cellregex);
  20577. for(var rslice = 0; rslice != cells.length; ++rslice) if(cells[rslice].trim().charAt(0) != "<") break;
  20578. cells = cells.slice(rslice);
  20579. for(ri = 0; ri != cells.length; ++ri) {
  20580. x = cells[ri].trim();
  20581. if(x.length === 0) continue;
  20582. cref = x.match(rregex); idx = ri; i=0; cc=0;
  20583. x = "<c " + (x.slice(0,1)=="<"?">":"") + x;
  20584. if(cref != null && cref.length === 2) {
  20585. idx = 0; d=cref[1];
  20586. for(i=0; i != d.length; ++i) {
  20587. if((cc=d.charCodeAt(i)-64) < 1 || cc > 26) break;
  20588. idx = 26*idx + cc;
  20589. }
  20590. --idx;
  20591. tagc = idx;
  20592. } else ++tagc;
  20593. for(i = 0; i != x.length; ++i) if(x.charCodeAt(i) === 62) break; ++i;
  20594. tag = parsexmltag(x.slice(0,i), true);
  20595. if(!tag.r) tag.r = encode_cell({r:tagr-1, c:tagc});
  20596. d = x.slice(i);
  20597. p = ({t:""});
  20598. if((cref=d.match(match_v))!= null && cref[1] !== '') p.v=unescapexml(cref[1]);
  20599. if(opts.cellFormula) {
  20600. if((cref=d.match(match_f))!= null && cref[1] !== '') {
  20601. /* TODO: match against XLSXFutureFunctions */
  20602. p.f=unescapexml(utf8read(cref[1])).replace(/\r\n/g, "\n");
  20603. if(!opts.xlfn) p.f = _xlfn(p.f);
  20604. if(cref[0].indexOf('t="array"') > -1) {
  20605. p.F = (d.match(refregex)||[])[1];
  20606. if(p.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p.F), p.F]);
  20607. } else if(cref[0].indexOf('t="shared"') > -1) {
  20608. // TODO: parse formula
  20609. ftag = parsexmltag(cref[0]);
  20610. var ___f = unescapexml(utf8read(cref[1]));
  20611. if(!opts.xlfn) ___f = _xlfn(___f);
  20612. sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r];
  20613. }
  20614. } else if((cref=d.match(/<f[^>]*\/>/))) {
  20615. ftag = parsexmltag(cref[0]);
  20616. if(sharedf[ftag.si]) p.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2]/*[0].ref*/, tag.r);
  20617. }
  20618. /* TODO: factor out contains logic */
  20619. var _tag = decode_cell(tag.r);
  20620. for(i = 0; i < arrayf.length; ++i)
  20621. if(_tag.r >= arrayf[i][0].s.r && _tag.r <= arrayf[i][0].e.r)
  20622. if(_tag.c >= arrayf[i][0].s.c && _tag.c <= arrayf[i][0].e.c)
  20623. p.F = arrayf[i][1];
  20624. }
  20625. if(tag.t == null && p.v === undefined) {
  20626. if(p.f || p.F) {
  20627. p.v = 0; p.t = "n";
  20628. } else if(!sheetStubs) continue;
  20629. else p.t = "z";
  20630. }
  20631. else p.t = tag.t || "n";
  20632. if(guess.s.c > tagc) guess.s.c = tagc;
  20633. if(guess.e.c < tagc) guess.e.c = tagc;
  20634. /* 18.18.11 t ST_CellType */
  20635. switch(p.t) {
  20636. case 'n':
  20637. if(p.v == "" || p.v == null) {
  20638. if(!sheetStubs) continue;
  20639. p.t = 'z';
  20640. } else p.v = parseFloat(p.v);
  20641. break;
  20642. case 's':
  20643. if(typeof p.v == 'undefined') {
  20644. if(!sheetStubs) continue;
  20645. p.t = 'z';
  20646. } else {
  20647. sstr = strs[parseInt(p.v, 10)];
  20648. p.v = sstr.t;
  20649. p.r = sstr.r;
  20650. if(opts.cellHTML) p.h = sstr.h;
  20651. }
  20652. break;
  20653. case 'str':
  20654. p.t = "s";
  20655. p.v = (p.v!=null) ? utf8read(p.v) : '';
  20656. if(opts.cellHTML) p.h = escapehtml(p.v);
  20657. break;
  20658. case 'inlineStr':
  20659. cref = d.match(isregex);
  20660. p.t = 's';
  20661. if(cref != null && (sstr = parse_si(cref[1]))) {
  20662. p.v = sstr.t;
  20663. if(opts.cellHTML) p.h = sstr.h;
  20664. } else p.v = "";
  20665. break;
  20666. case 'b': p.v = parsexmlbool(p.v); break;
  20667. case 'd':
  20668. if(opts.cellDates) p.v = parseDate(p.v, 1);
  20669. else { p.v = datenum(parseDate(p.v, 1)); p.t = 'n'; }
  20670. break;
  20671. /* error string in .w, number in .v */
  20672. case 'e':
  20673. if(!opts || opts.cellText !== false) p.w = p.v;
  20674. p.v = RBErr[p.v]; break;
  20675. }
  20676. /* formatting */
  20677. fmtid = fillid = 0;
  20678. cf = null;
  20679. if(do_format && tag.s !== undefined) {
  20680. cf = styles.CellXf[tag.s];
  20681. if(cf != null) {
  20682. if(cf.numFmtId != null) fmtid = cf.numFmtId;
  20683. if(opts.cellStyles) {
  20684. if(cf.fillId != null) fillid = cf.fillId;
  20685. }
  20686. }
  20687. }
  20688. safe_format(p, fmtid, fillid, opts, themes, styles);
  20689. if(opts.cellDates && do_format && p.t == 'n' && SSF.is_date(SSF._table[fmtid])) { p.t = 'd'; p.v = numdate(p.v); }
  20690. if(dense) {
  20691. var _r = decode_cell(tag.r);
  20692. if(!s[_r.r]) s[_r.r] = [];
  20693. s[_r.r][_r.c] = p;
  20694. } else s[tag.r] = p;
  20695. }
  20696. }
  20697. if(rows.length > 0) s['!rows'] = rows;
  20698. }; })();
  20699. function write_ws_xml_data(ws, opts, idx, wb) {
  20700. var o = [], r = [], range = safe_decode_range(ws['!ref']), cell="", ref, rr = "", cols = [], R=0, C=0, rows = ws['!rows'];
  20701. var dense = Array.isArray(ws);
  20702. var params = ({r:rr}), row, height = -1;
  20703. for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
  20704. for(R = range.s.r; R <= range.e.r; ++R) {
  20705. r = [];
  20706. rr = encode_row(R);
  20707. for(C = range.s.c; C <= range.e.c; ++C) {
  20708. ref = cols[C] + rr;
  20709. var _cell = dense ? (ws[R]||[])[C]: ws[ref];
  20710. if(_cell === undefined) continue;
  20711. if((cell = write_ws_xml_cell(_cell, ref, ws, opts, idx, wb)) != null) r.push(cell);
  20712. }
  20713. if(r.length > 0 || (rows && rows[R])) {
  20714. params = ({r:rr});
  20715. if(rows && rows[R]) {
  20716. row = rows[R];
  20717. if(row.hidden) params.hidden = 1;
  20718. height = -1;
  20719. if(row.hpx) height = px2pt(row.hpx);
  20720. else if(row.hpt) height = row.hpt;
  20721. if(height > -1) { params.ht = height; params.customHeight = 1; }
  20722. if(row.level) { params.outlineLevel = row.level; }
  20723. }
  20724. o[o.length] = (writextag('row', r.join(""), params));
  20725. }
  20726. }
  20727. if(rows) for(; R < rows.length; ++R) {
  20728. if(rows && rows[R]) {
  20729. params = ({r:R+1});
  20730. row = rows[R];
  20731. if(row.hidden) params.hidden = 1;
  20732. height = -1;
  20733. if (row.hpx) height = px2pt(row.hpx);
  20734. else if (row.hpt) height = row.hpt;
  20735. if (height > -1) { params.ht = height; params.customHeight = 1; }
  20736. if (row.level) { params.outlineLevel = row.level; }
  20737. o[o.length] = (writextag('row', "", params));
  20738. }
  20739. }
  20740. return o.join("");
  20741. }
  20742. var WS_XML_ROOT = writextag('worksheet', null, {
  20743. 'xmlns': XMLNS.main[0],
  20744. 'xmlns:r': XMLNS.r
  20745. });
  20746. function write_ws_xml(idx, opts, wb, rels) {
  20747. var o = [XML_HEADER, WS_XML_ROOT];
  20748. var s = wb.SheetNames[idx], sidx = 0, rdata = "";
  20749. var ws = wb.Sheets[s];
  20750. if(ws == null) ws = {};
  20751. var ref = ws['!ref'] || 'A1';
  20752. var range = safe_decode_range(ref);
  20753. if(range.e.c > 0x3FFF || range.e.r > 0xFFFFF) {
  20754. if(opts.WTF) throw new Error("Range " + ref + " exceeds format limit A1:XFD1048576");
  20755. range.e.c = Math.min(range.e.c, 0x3FFF);
  20756. range.e.r = Math.min(range.e.c, 0xFFFFF);
  20757. ref = encode_range(range);
  20758. }
  20759. if(!rels) rels = {};
  20760. ws['!comments'] = [];
  20761. var _drawing = [];
  20762. write_ws_xml_sheetpr(ws, wb, idx, opts, o);
  20763. o[o.length] = (writextag('dimension', null, {'ref': ref}));
  20764. o[o.length] = write_ws_xml_sheetviews(ws, opts, idx, wb);
  20765. /* TODO: store in WB, process styles */
  20766. if(opts.sheetFormat) o[o.length] = (writextag('sheetFormatPr', null, {
  20767. defaultRowHeight:opts.sheetFormat.defaultRowHeight||'16',
  20768. baseColWidth:opts.sheetFormat.baseColWidth||'10',
  20769. outlineLevelRow:opts.sheetFormat.outlineLevelRow||'7'
  20770. }));
  20771. if(ws['!cols'] != null && ws['!cols'].length > 0) o[o.length] = (write_ws_xml_cols(ws, ws['!cols']));
  20772. o[sidx = o.length] = '<sheetData/>';
  20773. ws['!links'] = [];
  20774. if(ws['!ref'] != null) {
  20775. rdata = write_ws_xml_data(ws, opts, idx, wb, rels);
  20776. if(rdata.length > 0) o[o.length] = (rdata);
  20777. }
  20778. if(o.length>sidx+1) { o[o.length] = ('</sheetData>'); o[sidx]=o[sidx].replace("/>",">"); }
  20779. /* sheetCalcPr */
  20780. if(ws['!protect'] != null) o[o.length] = write_ws_xml_protection(ws['!protect']);
  20781. /* protectedRanges */
  20782. /* scenarios */
  20783. if(ws['!autofilter'] != null) o[o.length] = write_ws_xml_autofilter(ws['!autofilter'], ws, wb, idx);
  20784. /* sortState */
  20785. /* dataConsolidate */
  20786. /* customSheetViews */
  20787. if(ws['!merges'] != null && ws['!merges'].length > 0) o[o.length] = (write_ws_xml_merges(ws['!merges']));
  20788. /* phoneticPr */
  20789. /* conditionalFormatting */
  20790. /* dataValidations */
  20791. var relc = -1, rel, rId = -1;
  20792. if(ws['!links'].length > 0) {
  20793. o[o.length] = "<hyperlinks>";
  20794. ws['!links'].forEach(function(l) {
  20795. if(!l[1].Target) return;
  20796. rel = ({"ref":l[0]});
  20797. if(l[1].Target.charAt(0) != "#") {
  20798. rId = add_rels(rels, -1, escapexml(l[1].Target).replace(/#.*$/, ""), RELS.HLINK);
  20799. rel["r:id"] = "rId"+rId;
  20800. }
  20801. if((relc = l[1].Target.indexOf("#")) > -1) rel.location = escapexml(l[1].Target.slice(relc+1));
  20802. if(l[1].Tooltip) rel.tooltip = escapexml(l[1].Tooltip);
  20803. o[o.length] = writextag("hyperlink",null,rel);
  20804. });
  20805. o[o.length] = "</hyperlinks>";
  20806. }
  20807. delete ws['!links'];
  20808. /* printOptions */
  20809. if(ws['!margins'] != null) o[o.length] = write_ws_xml_margins(ws['!margins']);
  20810. /* pageSetup */
  20811. /* headerFooter */
  20812. /* rowBreaks */
  20813. /* colBreaks */
  20814. /* customProperties */
  20815. /* cellWatches */
  20816. if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) o[o.length] = writetag("ignoredErrors", writextag("ignoredError", null, {numberStoredAsText:1, sqref:ref}));
  20817. /* smartTags */
  20818. if(_drawing.length > 0) {
  20819. rId = add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  20820. o[o.length] = writextag("drawing", null, {"r:id":"rId" + rId});
  20821. ws['!drawing'] = _drawing;
  20822. }
  20823. if(ws['!comments'].length > 0) {
  20824. rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
  20825. o[o.length] = writextag("legacyDrawing", null, {"r:id":"rId" + rId});
  20826. ws['!legacy'] = rId;
  20827. }
  20828. /* legacyDrawingHF */
  20829. /* picture */
  20830. /* oleObjects */
  20831. /* controls */
  20832. /* webPublishItems */
  20833. /* tableParts */
  20834. /* extLst */
  20835. if(o.length>1) { o[o.length] = ('</worksheet>'); o[1]=o[1].replace("/>",">"); }
  20836. return o.join("");
  20837. }
  20838. /* [MS-XLSB] 2.4.726 BrtRowHdr */
  20839. function parse_BrtRowHdr(data, length) {
  20840. var z = ({});
  20841. var tgt = data.l + length;
  20842. z.r = data.read_shift(4);
  20843. data.l += 4; // TODO: ixfe
  20844. var miyRw = data.read_shift(2);
  20845. data.l += 1; // TODO: top/bot padding
  20846. var flags = data.read_shift(1);
  20847. data.l = tgt;
  20848. if(flags & 0x07) z.level = flags & 0x07;
  20849. if(flags & 0x10) z.hidden = true;
  20850. if(flags & 0x20) z.hpt = miyRw / 20;
  20851. return z;
  20852. }
  20853. function write_BrtRowHdr(R, range, ws) {
  20854. var o = new_buf(17+8*16);
  20855. var row = (ws['!rows']||[])[R]||{};
  20856. o.write_shift(4, R);
  20857. o.write_shift(4, 0); /* TODO: ixfe */
  20858. var miyRw = 0x0140;
  20859. if(row.hpx) miyRw = px2pt(row.hpx) * 20;
  20860. else if(row.hpt) miyRw = row.hpt * 20;
  20861. o.write_shift(2, miyRw);
  20862. o.write_shift(1, 0); /* top/bot padding */
  20863. var flags = 0x0;
  20864. if(row.level) flags |= row.level;
  20865. if(row.hidden) flags |= 0x10;
  20866. if(row.hpx || row.hpt) flags |= 0x20;
  20867. o.write_shift(1, flags);
  20868. o.write_shift(1, 0); /* phonetic guide */
  20869. /* [MS-XLSB] 2.5.8 BrtColSpan explains the mechanism */
  20870. var ncolspan = 0, lcs = o.l;
  20871. o.l += 4;
  20872. var caddr = {r:R, c:0};
  20873. for(var i = 0; i < 16; ++i) {
  20874. if((range.s.c > ((i+1) << 10)) || (range.e.c < (i << 10))) continue;
  20875. var first = -1, last = -1;
  20876. for(var j = (i<<10); j < ((i+1)<<10); ++j) {
  20877. caddr.c = j;
  20878. var cell = Array.isArray(ws) ? (ws[caddr.r]||[])[caddr.c] : ws[encode_cell(caddr)];
  20879. if(cell) { if(first < 0) first = j; last = j; }
  20880. }
  20881. if(first < 0) continue;
  20882. ++ncolspan;
  20883. o.write_shift(4, first);
  20884. o.write_shift(4, last);
  20885. }
  20886. var l = o.l;
  20887. o.l = lcs;
  20888. o.write_shift(4, ncolspan);
  20889. o.l = l;
  20890. return o.length > o.l ? o.slice(0, o.l) : o;
  20891. }
  20892. function write_row_header(ba, ws, range, R) {
  20893. var o = write_BrtRowHdr(R, range, ws);
  20894. if((o.length > 17) || (ws['!rows']||[])[R]) write_record(ba, 'BrtRowHdr', o);
  20895. }
  20896. /* [MS-XLSB] 2.4.820 BrtWsDim */
  20897. var parse_BrtWsDim = parse_UncheckedRfX;
  20898. var write_BrtWsDim = write_UncheckedRfX;
  20899. /* [MS-XLSB] 2.4.821 BrtWsFmtInfo */
  20900. function parse_BrtWsFmtInfo() {
  20901. }
  20902. //function write_BrtWsFmtInfo(ws, o) { }
  20903. /* [MS-XLSB] 2.4.823 BrtWsProp */
  20904. function parse_BrtWsProp(data, length) {
  20905. var z = {};
  20906. /* TODO: pull flags */
  20907. data.l += 19;
  20908. z.name = parse_XLSBCodeName(data, length - 19);
  20909. return z;
  20910. }
  20911. function write_BrtWsProp(str, o) {
  20912. if(o == null) o = new_buf(84+4*str.length);
  20913. for(var i = 0; i < 3; ++i) o.write_shift(1,0);
  20914. write_BrtColor({auto:1}, o);
  20915. o.write_shift(-4,-1);
  20916. o.write_shift(-4,-1);
  20917. write_XLSBCodeName(str, o);
  20918. return o.slice(0, o.l);
  20919. }
  20920. /* [MS-XLSB] 2.4.306 BrtCellBlank */
  20921. function parse_BrtCellBlank(data) {
  20922. var cell = parse_XLSBCell(data);
  20923. return [cell];
  20924. }
  20925. function write_BrtCellBlank(cell, ncell, o) {
  20926. if(o == null) o = new_buf(8);
  20927. return write_XLSBCell(ncell, o);
  20928. }
  20929. /* [MS-XLSB] 2.4.307 BrtCellBool */
  20930. function parse_BrtCellBool(data) {
  20931. var cell = parse_XLSBCell(data);
  20932. var fBool = data.read_shift(1);
  20933. return [cell, fBool, 'b'];
  20934. }
  20935. function write_BrtCellBool(cell, ncell, o) {
  20936. if(o == null) o = new_buf(9);
  20937. write_XLSBCell(ncell, o);
  20938. o.write_shift(1, cell.v ? 1 : 0);
  20939. return o;
  20940. }
  20941. /* [MS-XLSB] 2.4.308 BrtCellError */
  20942. function parse_BrtCellError(data) {
  20943. var cell = parse_XLSBCell(data);
  20944. var bError = data.read_shift(1);
  20945. return [cell, bError, 'e'];
  20946. }
  20947. /* [MS-XLSB] 2.4.311 BrtCellIsst */
  20948. function parse_BrtCellIsst(data) {
  20949. var cell = parse_XLSBCell(data);
  20950. var isst = data.read_shift(4);
  20951. return [cell, isst, 's'];
  20952. }
  20953. function write_BrtCellIsst(cell, ncell, o) {
  20954. if(o == null) o = new_buf(12);
  20955. write_XLSBCell(ncell, o);
  20956. o.write_shift(4, ncell.v);
  20957. return o;
  20958. }
  20959. /* [MS-XLSB] 2.4.313 BrtCellReal */
  20960. function parse_BrtCellReal(data) {
  20961. var cell = parse_XLSBCell(data);
  20962. var value = parse_Xnum(data);
  20963. return [cell, value, 'n'];
  20964. }
  20965. function write_BrtCellReal(cell, ncell, o) {
  20966. if(o == null) o = new_buf(16);
  20967. write_XLSBCell(ncell, o);
  20968. write_Xnum(cell.v, o);
  20969. return o;
  20970. }
  20971. /* [MS-XLSB] 2.4.314 BrtCellRk */
  20972. function parse_BrtCellRk(data) {
  20973. var cell = parse_XLSBCell(data);
  20974. var value = parse_RkNumber(data);
  20975. return [cell, value, 'n'];
  20976. }
  20977. function write_BrtCellRk(cell, ncell, o) {
  20978. if(o == null) o = new_buf(12);
  20979. write_XLSBCell(ncell, o);
  20980. write_RkNumber(cell.v, o);
  20981. return o;
  20982. }
  20983. /* [MS-XLSB] 2.4.317 BrtCellSt */
  20984. function parse_BrtCellSt(data) {
  20985. var cell = parse_XLSBCell(data);
  20986. var value = parse_XLWideString(data);
  20987. return [cell, value, 'str'];
  20988. }
  20989. function write_BrtCellSt(cell, ncell, o) {
  20990. if(o == null) o = new_buf(12 + 4 * cell.v.length);
  20991. write_XLSBCell(ncell, o);
  20992. write_XLWideString(cell.v, o);
  20993. return o.length > o.l ? o.slice(0, o.l) : o;
  20994. }
  20995. /* [MS-XLSB] 2.4.653 BrtFmlaBool */
  20996. function parse_BrtFmlaBool(data, length, opts) {
  20997. var end = data.l + length;
  20998. var cell = parse_XLSBCell(data);
  20999. cell.r = opts['!row'];
  21000. var value = data.read_shift(1);
  21001. var o = [cell, value, 'b'];
  21002. if(opts.cellFormula) {
  21003. data.l += 2;
  21004. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  21005. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  21006. }
  21007. else data.l = end;
  21008. return o;
  21009. }
  21010. /* [MS-XLSB] 2.4.654 BrtFmlaError */
  21011. function parse_BrtFmlaError(data, length, opts) {
  21012. var end = data.l + length;
  21013. var cell = parse_XLSBCell(data);
  21014. cell.r = opts['!row'];
  21015. var value = data.read_shift(1);
  21016. var o = [cell, value, 'e'];
  21017. if(opts.cellFormula) {
  21018. data.l += 2;
  21019. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  21020. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  21021. }
  21022. else data.l = end;
  21023. return o;
  21024. }
  21025. /* [MS-XLSB] 2.4.655 BrtFmlaNum */
  21026. function parse_BrtFmlaNum(data, length, opts) {
  21027. var end = data.l + length;
  21028. var cell = parse_XLSBCell(data);
  21029. cell.r = opts['!row'];
  21030. var value = parse_Xnum(data);
  21031. var o = [cell, value, 'n'];
  21032. if(opts.cellFormula) {
  21033. data.l += 2;
  21034. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  21035. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  21036. }
  21037. else data.l = end;
  21038. return o;
  21039. }
  21040. /* [MS-XLSB] 2.4.656 BrtFmlaString */
  21041. function parse_BrtFmlaString(data, length, opts) {
  21042. var end = data.l + length;
  21043. var cell = parse_XLSBCell(data);
  21044. cell.r = opts['!row'];
  21045. var value = parse_XLWideString(data);
  21046. var o = [cell, value, 'str'];
  21047. if(opts.cellFormula) {
  21048. data.l += 2;
  21049. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  21050. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  21051. }
  21052. else data.l = end;
  21053. return o;
  21054. }
  21055. /* [MS-XLSB] 2.4.682 BrtMergeCell */
  21056. var parse_BrtMergeCell = parse_UncheckedRfX;
  21057. var write_BrtMergeCell = write_UncheckedRfX;
  21058. /* [MS-XLSB] 2.4.107 BrtBeginMergeCells */
  21059. function write_BrtBeginMergeCells(cnt, o) {
  21060. if(o == null) o = new_buf(4);
  21061. o.write_shift(4, cnt);
  21062. return o;
  21063. }
  21064. /* [MS-XLSB] 2.4.662 BrtHLink */
  21065. function parse_BrtHLink(data, length) {
  21066. var end = data.l + length;
  21067. var rfx = parse_UncheckedRfX(data, 16);
  21068. var relId = parse_XLNullableWideString(data);
  21069. var loc = parse_XLWideString(data);
  21070. var tooltip = parse_XLWideString(data);
  21071. var display = parse_XLWideString(data);
  21072. data.l = end;
  21073. var o = ({rfx:rfx, relId:relId, loc:loc, display:display});
  21074. if(tooltip) o.Tooltip = tooltip;
  21075. return o;
  21076. }
  21077. function write_BrtHLink(l, rId) {
  21078. var o = new_buf(50+4*(l[1].Target.length + (l[1].Tooltip || "").length));
  21079. write_UncheckedRfX({s:decode_cell(l[0]), e:decode_cell(l[0])}, o);
  21080. write_RelID("rId" + rId, o);
  21081. var locidx = l[1].Target.indexOf("#");
  21082. var loc = locidx == -1 ? "" : l[1].Target.slice(locidx+1);
  21083. write_XLWideString(loc || "", o);
  21084. write_XLWideString(l[1].Tooltip || "", o);
  21085. write_XLWideString("", o);
  21086. return o.slice(0, o.l);
  21087. }
  21088. /* [MS-XLSB] 2.4.692 BrtPane */
  21089. function parse_BrtPane(/*data, length, opts*/) {
  21090. }
  21091. /* [MS-XLSB] 2.4.6 BrtArrFmla */
  21092. function parse_BrtArrFmla(data, length, opts) {
  21093. var end = data.l + length;
  21094. var rfx = parse_RfX(data, 16);
  21095. var fAlwaysCalc = data.read_shift(1);
  21096. var o = [rfx]; o[2] = fAlwaysCalc;
  21097. if(opts.cellFormula) {
  21098. var formula = parse_XLSBArrayParsedFormula(data, end - data.l, opts);
  21099. o[1] = formula;
  21100. } else data.l = end;
  21101. return o;
  21102. }
  21103. /* [MS-XLSB] 2.4.750 BrtShrFmla */
  21104. function parse_BrtShrFmla(data, length, opts) {
  21105. var end = data.l + length;
  21106. var rfx = parse_UncheckedRfX(data, 16);
  21107. var o = [rfx];
  21108. if(opts.cellFormula) {
  21109. var formula = parse_XLSBSharedParsedFormula(data, end - data.l, opts);
  21110. o[1] = formula;
  21111. data.l = end;
  21112. } else data.l = end;
  21113. return o;
  21114. }
  21115. /* [MS-XLSB] 2.4.323 BrtColInfo */
  21116. /* TODO: once XLS ColInfo is set, combine the functions */
  21117. function write_BrtColInfo(C, col, o) {
  21118. if(o == null) o = new_buf(18);
  21119. var p = col_obj_w(C, col);
  21120. o.write_shift(-4, C);
  21121. o.write_shift(-4, C);
  21122. o.write_shift(4, (p.width || 10) * 256);
  21123. o.write_shift(4, 0/*ixfe*/); // style
  21124. var flags = 0;
  21125. if(col.hidden) flags |= 0x01;
  21126. if(typeof p.width == 'number') flags |= 0x02;
  21127. if(col.level) flags |= (col.level << 8);
  21128. o.write_shift(2, flags); // bit flag
  21129. return o;
  21130. }
  21131. /* [MS-XLSB] 2.4.678 BrtMargins */
  21132. var BrtMarginKeys = ["left","right","top","bottom","header","footer"];
  21133. function parse_BrtMargins(data) {
  21134. var margins = ({});
  21135. BrtMarginKeys.forEach(function(k) { margins[k] = parse_Xnum(data, 8); });
  21136. return margins;
  21137. }
  21138. function write_BrtMargins(margins, o) {
  21139. if(o == null) o = new_buf(6*8);
  21140. default_margins(margins);
  21141. BrtMarginKeys.forEach(function(k) { write_Xnum((margins)[k], o); });
  21142. return o;
  21143. }
  21144. /* [MS-XLSB] 2.4.299 BrtBeginWsView */
  21145. function parse_BrtBeginWsView(data) {
  21146. var f = data.read_shift(2);
  21147. data.l += 28;
  21148. return { RTL: f & 0x20 };
  21149. }
  21150. function write_BrtBeginWsView(ws, Workbook, o) {
  21151. if(o == null) o = new_buf(30);
  21152. var f = 0x39c;
  21153. if((((Workbook||{}).Views||[])[0]||{}).RTL) f |= 0x20;
  21154. o.write_shift(2, f); // bit flag
  21155. o.write_shift(4, 0);
  21156. o.write_shift(4, 0); // view first row
  21157. o.write_shift(4, 0); // view first col
  21158. o.write_shift(1, 0); // gridline color ICV
  21159. o.write_shift(1, 0);
  21160. o.write_shift(2, 0);
  21161. o.write_shift(2, 100); // zoom scale
  21162. o.write_shift(2, 0);
  21163. o.write_shift(2, 0);
  21164. o.write_shift(2, 0);
  21165. o.write_shift(4, 0); // workbook view id
  21166. return o;
  21167. }
  21168. /* [MS-XLSB] 2.4.309 BrtCellIgnoreEC */
  21169. function write_BrtCellIgnoreEC(ref) {
  21170. var o = new_buf(24);
  21171. o.write_shift(4, 4);
  21172. o.write_shift(4, 1);
  21173. write_UncheckedRfX(ref, o);
  21174. return o;
  21175. }
  21176. /* [MS-XLSB] 2.4.748 BrtSheetProtection */
  21177. function write_BrtSheetProtection(sp, o) {
  21178. if(o == null) o = new_buf(16*4+2);
  21179. o.write_shift(2, sp.password ? crypto_CreatePasswordVerifier_Method1(sp.password) : 0);
  21180. o.write_shift(4, 1); // this record should not be written if no protection
  21181. [
  21182. ["objects", false], // fObjects
  21183. ["scenarios", false], // fScenarios
  21184. ["formatCells", true], // fFormatCells
  21185. ["formatColumns", true], // fFormatColumns
  21186. ["formatRows", true], // fFormatRows
  21187. ["insertColumns", true], // fInsertColumns
  21188. ["insertRows", true], // fInsertRows
  21189. ["insertHyperlinks", true], // fInsertHyperlinks
  21190. ["deleteColumns", true], // fDeleteColumns
  21191. ["deleteRows", true], // fDeleteRows
  21192. ["selectLockedCells", false], // fSelLockedCells
  21193. ["sort", true], // fSort
  21194. ["autoFilter", true], // fAutoFilter
  21195. ["pivotTables", true], // fPivotTables
  21196. ["selectUnlockedCells", false] // fSelUnlockedCells
  21197. ].forEach(function(n) {
  21198. if(n[1]) o.write_shift(4, sp[n[0]] != null && !sp[n[0]] ? 1 : 0);
  21199. else o.write_shift(4, sp[n[0]] != null && sp[n[0]] ? 0 : 1);
  21200. });
  21201. return o;
  21202. }
  21203. function parse_BrtDVal(/*data, length, opts*/) {
  21204. }
  21205. function parse_BrtDVal14(/*data, length, opts*/) {
  21206. }
  21207. /* [MS-XLSB] 2.1.7.61 Worksheet */
  21208. function parse_ws_bin(data, _opts, idx, rels, wb, themes, styles) {
  21209. if(!data) return data;
  21210. var opts = _opts || {};
  21211. if(!rels) rels = {'!id':{}};
  21212. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  21213. var s = (opts.dense ? [] : {});
  21214. var ref;
  21215. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  21216. var state = [];
  21217. var pass = false, end = false;
  21218. var row, p, cf, R, C, addr, sstr, rr, cell;
  21219. var merges = [];
  21220. opts.biff = 12;
  21221. opts['!row'] = 0;
  21222. var ai = 0, af = false;
  21223. var arrayf = [];
  21224. var sharedf = {};
  21225. var supbooks = opts.supbooks || wb.supbooks || ([[]]);
  21226. supbooks.sharedf = sharedf;
  21227. supbooks.arrayf = arrayf;
  21228. supbooks.SheetNames = wb.SheetNames || wb.Sheets.map(function(x) { return x.name; });
  21229. if(!opts.supbooks) {
  21230. opts.supbooks = supbooks;
  21231. if(wb.Names) for(var i = 0; i < wb.Names.length; ++i) supbooks[0][i+1] = wb.Names[i];
  21232. }
  21233. var colinfo = [], rowinfo = [];
  21234. var seencol = false;
  21235. recordhopper(data, function ws_parse(val, R_n, RT) {
  21236. if(end) return;
  21237. switch(RT) {
  21238. case 0x0094: /* 'BrtWsDim' */
  21239. ref = val; break;
  21240. case 0x0000: /* 'BrtRowHdr' */
  21241. row = val;
  21242. if(opts.sheetRows && opts.sheetRows <= row.r) end=true;
  21243. rr = encode_row(R = row.r);
  21244. opts['!row'] = row.r;
  21245. if(val.hidden || val.hpt || val.level != null) {
  21246. if(val.hpt) val.hpx = pt2px(val.hpt);
  21247. rowinfo[val.r] = val;
  21248. }
  21249. break;
  21250. case 0x0002: /* 'BrtCellRk' */
  21251. case 0x0003: /* 'BrtCellError' */
  21252. case 0x0004: /* 'BrtCellBool' */
  21253. case 0x0005: /* 'BrtCellReal' */
  21254. case 0x0006: /* 'BrtCellSt' */
  21255. case 0x0007: /* 'BrtCellIsst' */
  21256. case 0x0008: /* 'BrtFmlaString' */
  21257. case 0x0009: /* 'BrtFmlaNum' */
  21258. case 0x000A: /* 'BrtFmlaBool' */
  21259. case 0x000B: /* 'BrtFmlaError' */
  21260. p = ({t:val[2]});
  21261. switch(val[2]) {
  21262. case 'n': p.v = val[1]; break;
  21263. case 's': sstr = strs[val[1]]; p.v = sstr.t; p.r = sstr.r; break;
  21264. case 'b': p.v = val[1] ? true : false; break;
  21265. case 'e': p.v = val[1]; if(opts.cellText !== false) p.w = BErr[p.v]; break;
  21266. case 'str': p.t = 's'; p.v = val[1]; break;
  21267. }
  21268. if((cf = styles.CellXf[val[0].iStyleRef])) safe_format(p,cf.numFmtId,null,opts, themes, styles);
  21269. C = val[0].c;
  21270. if(opts.dense) { if(!s[R]) s[R] = []; s[R][C] = p; }
  21271. else s[encode_col(C) + rr] = p;
  21272. if(opts.cellFormula) {
  21273. af = false;
  21274. for(ai = 0; ai < arrayf.length; ++ai) {
  21275. var aii = arrayf[ai];
  21276. if(row.r >= aii[0].s.r && row.r <= aii[0].e.r)
  21277. if(C >= aii[0].s.c && C <= aii[0].e.c) {
  21278. p.F = encode_range(aii[0]); af = true;
  21279. }
  21280. }
  21281. if(!af && val.length > 3) p.f = val[3];
  21282. }
  21283. if(refguess.s.r > row.r) refguess.s.r = row.r;
  21284. if(refguess.s.c > C) refguess.s.c = C;
  21285. if(refguess.e.r < row.r) refguess.e.r = row.r;
  21286. if(refguess.e.c < C) refguess.e.c = C;
  21287. if(opts.cellDates && cf && p.t == 'n' && SSF.is_date(SSF._table[cf.numFmtId])) {
  21288. var _d = SSF.parse_date_code(p.v); if(_d) { p.t = 'd'; p.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
  21289. }
  21290. break;
  21291. case 0x0001: /* 'BrtCellBlank' */
  21292. if(!opts.sheetStubs || pass) break;
  21293. p = ({t:'z',v:undefined});
  21294. C = val[0].c;
  21295. if(opts.dense) { if(!s[R]) s[R] = []; s[R][C] = p; }
  21296. else s[encode_col(C) + rr] = p;
  21297. if(refguess.s.r > row.r) refguess.s.r = row.r;
  21298. if(refguess.s.c > C) refguess.s.c = C;
  21299. if(refguess.e.r < row.r) refguess.e.r = row.r;
  21300. if(refguess.e.c < C) refguess.e.c = C;
  21301. break;
  21302. case 0x00B0: /* 'BrtMergeCell' */
  21303. merges.push(val); break;
  21304. case 0x01EE: /* 'BrtHLink' */
  21305. var rel = rels['!id'][val.relId];
  21306. if(rel) {
  21307. val.Target = rel.Target;
  21308. if(val.loc) val.Target += "#"+val.loc;
  21309. val.Rel = rel;
  21310. } else if(val.relId == '') {
  21311. val.Target = "#" + val.loc;
  21312. }
  21313. for(R=val.rfx.s.r;R<=val.rfx.e.r;++R) for(C=val.rfx.s.c;C<=val.rfx.e.c;++C) {
  21314. if(opts.dense) {
  21315. if(!s[R]) s[R] = [];
  21316. if(!s[R][C]) s[R][C] = {t:'z',v:undefined};
  21317. s[R][C].l = val;
  21318. } else {
  21319. addr = encode_cell({c:C,r:R});
  21320. if(!s[addr]) s[addr] = {t:'z',v:undefined};
  21321. s[addr].l = val;
  21322. }
  21323. }
  21324. break;
  21325. case 0x01AA: /* 'BrtArrFmla' */
  21326. if(!opts.cellFormula) break;
  21327. arrayf.push(val);
  21328. cell = ((opts.dense ? s[R][C] : s[encode_col(C) + rr]));
  21329. cell.f = stringify_formula(val[1], refguess, {r:row.r, c:C}, supbooks, opts);
  21330. cell.F = encode_range(val[0]);
  21331. break;
  21332. case 0x01AB: /* 'BrtShrFmla' */
  21333. if(!opts.cellFormula) break;
  21334. sharedf[encode_cell(val[0].s)] = val[1];
  21335. cell = (opts.dense ? s[R][C] : s[encode_col(C) + rr]);
  21336. cell.f = stringify_formula(val[1], refguess, {r:row.r, c:C}, supbooks, opts);
  21337. break;
  21338. /* identical to 'ColInfo' in XLS */
  21339. case 0x003C: /* 'BrtColInfo' */
  21340. if(!opts.cellStyles) break;
  21341. while(val.e >= val.s) {
  21342. colinfo[val.e--] = { width: val.w/256, hidden: !!(val.flags & 0x01), level: val.level };
  21343. if(!seencol) { seencol = true; find_mdw_colw(val.w/256); }
  21344. process_col(colinfo[val.e+1]);
  21345. }
  21346. break;
  21347. case 0x00A1: /* 'BrtBeginAFilter' */
  21348. s['!autofilter'] = { ref:encode_range(val) };
  21349. break;
  21350. case 0x01DC: /* 'BrtMargins' */
  21351. s['!margins'] = val;
  21352. break;
  21353. case 0x0093: /* 'BrtWsProp' */
  21354. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  21355. if(val.name) wb.Sheets[idx].CodeName = val.name;
  21356. break;
  21357. case 0x0089: /* 'BrtBeginWsView' */
  21358. if(!wb.Views) wb.Views = [{}];
  21359. if(!wb.Views[0]) wb.Views[0] = {};
  21360. if(val.RTL) wb.Views[0].RTL = true;
  21361. break;
  21362. case 0x01E5: /* 'BrtWsFmtInfo' */
  21363. break;
  21364. case 0x0040: /* 'BrtDVal' */
  21365. case 0x041D: /* 'BrtDVal14' */
  21366. break;
  21367. case 0x0097: /* 'BrtPane' */
  21368. break;
  21369. case 0x00AF: /* 'BrtAFilterDateGroupItem' */
  21370. case 0x0284: /* 'BrtActiveX' */
  21371. case 0x0271: /* 'BrtBigName' */
  21372. case 0x0232: /* 'BrtBkHim' */
  21373. case 0x018C: /* 'BrtBrk' */
  21374. case 0x0458: /* 'BrtCFIcon' */
  21375. case 0x047A: /* 'BrtCFRuleExt' */
  21376. case 0x01D7: /* 'BrtCFVO' */
  21377. case 0x041A: /* 'BrtCFVO14' */
  21378. case 0x0289: /* 'BrtCellIgnoreEC' */
  21379. case 0x0451: /* 'BrtCellIgnoreEC14' */
  21380. case 0x0031: /* 'BrtCellMeta' */
  21381. case 0x024D: /* 'BrtCellSmartTagProperty' */
  21382. case 0x025F: /* 'BrtCellWatch' */
  21383. case 0x0234: /* 'BrtColor' */
  21384. case 0x041F: /* 'BrtColor14' */
  21385. case 0x00A8: /* 'BrtColorFilter' */
  21386. case 0x00AE: /* 'BrtCustomFilter' */
  21387. case 0x049C: /* 'BrtCustomFilter14' */
  21388. case 0x01F3: /* 'BrtDRef' */
  21389. case 0x01FB: /* 'BrtDXF' */
  21390. case 0x0226: /* 'BrtDrawing' */
  21391. case 0x00AB: /* 'BrtDynamicFilter' */
  21392. case 0x00A7: /* 'BrtFilter' */
  21393. case 0x0499: /* 'BrtFilter14' */
  21394. case 0x00A9: /* 'BrtIconFilter' */
  21395. case 0x049D: /* 'BrtIconFilter14' */
  21396. case 0x0227: /* 'BrtLegacyDrawing' */
  21397. case 0x0228: /* 'BrtLegacyDrawingHF' */
  21398. case 0x0295: /* 'BrtListPart' */
  21399. case 0x027F: /* 'BrtOleObject' */
  21400. case 0x01DE: /* 'BrtPageSetup' */
  21401. case 0x0219: /* 'BrtPhoneticInfo' */
  21402. case 0x01DD: /* 'BrtPrintOptions' */
  21403. case 0x0218: /* 'BrtRangeProtection' */
  21404. case 0x044F: /* 'BrtRangeProtection14' */
  21405. case 0x02A8: /* 'BrtRangeProtectionIso' */
  21406. case 0x0450: /* 'BrtRangeProtectionIso14' */
  21407. case 0x0400: /* 'BrtRwDescent' */
  21408. case 0x0098: /* 'BrtSel' */
  21409. case 0x0297: /* 'BrtSheetCalcProp' */
  21410. case 0x0217: /* 'BrtSheetProtection' */
  21411. case 0x02A6: /* 'BrtSheetProtectionIso' */
  21412. case 0x01F8: /* 'BrtSlc' */
  21413. case 0x0413: /* 'BrtSparkline' */
  21414. case 0x01AC: /* 'BrtTable' */
  21415. case 0x00AA: /* 'BrtTop10Filter' */
  21416. case 0x0C00: /* 'BrtUid' */
  21417. case 0x0032: /* 'BrtValueMeta' */
  21418. case 0x0816: /* 'BrtWebExtension' */
  21419. case 0x0415: /* 'BrtWsFmtInfoEx14' */
  21420. break;
  21421. case 0x0023: /* 'BrtFRTBegin' */
  21422. pass = true; break;
  21423. case 0x0024: /* 'BrtFRTEnd' */
  21424. pass = false; break;
  21425. case 0x0025: /* 'BrtACBegin' */
  21426. state.push(R_n); pass = true; break;
  21427. case 0x0026: /* 'BrtACEnd' */
  21428. state.pop(); pass = false; break;
  21429. default:
  21430. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  21431. else if((R_n||"").indexOf("End") > 0){/* empty */}
  21432. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  21433. }
  21434. }, opts);
  21435. delete opts.supbooks;
  21436. delete opts['!row'];
  21437. if(!s["!ref"] && (refguess.s.r < 2000000 || ref && (ref.e.r > 0 || ref.e.c > 0 || ref.s.r > 0 || ref.s.c > 0))) s["!ref"] = encode_range(ref || refguess);
  21438. if(opts.sheetRows && s["!ref"]) {
  21439. var tmpref = safe_decode_range(s["!ref"]);
  21440. if(opts.sheetRows <= +tmpref.e.r) {
  21441. tmpref.e.r = opts.sheetRows - 1;
  21442. if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
  21443. if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
  21444. if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
  21445. if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
  21446. s["!fullref"] = s["!ref"];
  21447. s["!ref"] = encode_range(tmpref);
  21448. }
  21449. }
  21450. if(merges.length > 0) s["!merges"] = merges;
  21451. if(colinfo.length > 0) s["!cols"] = colinfo;
  21452. if(rowinfo.length > 0) s["!rows"] = rowinfo;
  21453. return s;
  21454. }
  21455. /* TODO: something useful -- this is a stub */
  21456. function write_ws_bin_cell(ba, cell, R, C, opts, ws) {
  21457. if(cell.v === undefined) return;
  21458. var vv = "";
  21459. switch(cell.t) {
  21460. case 'b': vv = cell.v ? "1" : "0"; break;
  21461. case 'd': // no BrtCellDate :(
  21462. cell = dup(cell);
  21463. cell.z = cell.z || SSF._table[14];
  21464. cell.v = datenum(parseDate(cell.v)); cell.t = 'n';
  21465. break;
  21466. /* falls through */
  21467. case 'n': case 'e': vv = ''+cell.v; break;
  21468. default: vv = cell.v; break;
  21469. }
  21470. var o = ({r:R, c:C});
  21471. /* TODO: cell style */
  21472. o.s = get_cell_style(opts.cellXfs, cell, opts);
  21473. if(cell.l) ws['!links'].push([encode_cell(o), cell.l]);
  21474. if(cell.c) ws['!comments'].push([encode_cell(o), cell.c]);
  21475. switch(cell.t) {
  21476. case 's': case 'str':
  21477. if(opts.bookSST) {
  21478. vv = get_sst_id(opts.Strings, (cell.v), opts.revStrings);
  21479. o.t = "s"; o.v = vv;
  21480. write_record(ba, "BrtCellIsst", write_BrtCellIsst(cell, o));
  21481. } else {
  21482. o.t = "str";
  21483. write_record(ba, "BrtCellSt", write_BrtCellSt(cell, o));
  21484. }
  21485. return;
  21486. case 'n':
  21487. /* TODO: determine threshold for Real vs RK */
  21488. if(cell.v == (cell.v | 0) && cell.v > -1000 && cell.v < 1000) write_record(ba, "BrtCellRk", write_BrtCellRk(cell, o));
  21489. else write_record(ba, "BrtCellReal", write_BrtCellReal(cell, o));
  21490. return;
  21491. case 'b':
  21492. o.t = "b";
  21493. write_record(ba, "BrtCellBool", write_BrtCellBool(cell, o));
  21494. return;
  21495. case 'e': /* TODO: error */ o.t = "e"; break;
  21496. }
  21497. write_record(ba, "BrtCellBlank", write_BrtCellBlank(cell, o));
  21498. }
  21499. function write_CELLTABLE(ba, ws, idx, opts) {
  21500. var range = safe_decode_range(ws['!ref'] || "A1"), ref, rr = "", cols = [];
  21501. write_record(ba, 'BrtBeginSheetData');
  21502. var dense = Array.isArray(ws);
  21503. var cap = range.e.r;
  21504. if(ws['!rows']) cap = Math.max(range.e.r, ws['!rows'].length - 1);
  21505. for(var R = range.s.r; R <= cap; ++R) {
  21506. rr = encode_row(R);
  21507. /* [ACCELLTABLE] */
  21508. /* BrtRowHdr */
  21509. write_row_header(ba, ws, range, R);
  21510. if(R <= range.e.r) for(var C = range.s.c; C <= range.e.c; ++C) {
  21511. /* *16384CELL */
  21512. if(R === range.s.r) cols[C] = encode_col(C);
  21513. ref = cols[C] + rr;
  21514. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  21515. if(!cell) continue;
  21516. /* write cell */
  21517. write_ws_bin_cell(ba, cell, R, C, opts, ws);
  21518. }
  21519. }
  21520. write_record(ba, 'BrtEndSheetData');
  21521. }
  21522. function write_MERGECELLS(ba, ws) {
  21523. if(!ws || !ws['!merges']) return;
  21524. write_record(ba, 'BrtBeginMergeCells', write_BrtBeginMergeCells(ws['!merges'].length));
  21525. ws['!merges'].forEach(function(m) { write_record(ba, 'BrtMergeCell', write_BrtMergeCell(m)); });
  21526. write_record(ba, 'BrtEndMergeCells');
  21527. }
  21528. function write_COLINFOS(ba, ws) {
  21529. if(!ws || !ws['!cols']) return;
  21530. write_record(ba, 'BrtBeginColInfos');
  21531. ws['!cols'].forEach(function(m, i) { if(m) write_record(ba, 'BrtColInfo', write_BrtColInfo(i, m)); });
  21532. write_record(ba, 'BrtEndColInfos');
  21533. }
  21534. function write_IGNOREECS(ba, ws) {
  21535. if(!ws || !ws['!ref']) return;
  21536. write_record(ba, 'BrtBeginCellIgnoreECs');
  21537. write_record(ba, 'BrtCellIgnoreEC', write_BrtCellIgnoreEC(safe_decode_range(ws['!ref'])));
  21538. write_record(ba, 'BrtEndCellIgnoreECs');
  21539. }
  21540. function write_HLINKS(ba, ws, rels) {
  21541. /* *BrtHLink */
  21542. ws['!links'].forEach(function(l) {
  21543. if(!l[1].Target) return;
  21544. var rId = add_rels(rels, -1, l[1].Target.replace(/#.*$/, ""), RELS.HLINK);
  21545. write_record(ba, "BrtHLink", write_BrtHLink(l, rId));
  21546. });
  21547. delete ws['!links'];
  21548. }
  21549. function write_LEGACYDRAWING(ba, ws, idx, rels) {
  21550. /* [BrtLegacyDrawing] */
  21551. if(ws['!comments'].length > 0) {
  21552. var rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
  21553. write_record(ba, "BrtLegacyDrawing", write_RelID("rId" + rId));
  21554. ws['!legacy'] = rId;
  21555. }
  21556. }
  21557. function write_AUTOFILTER(ba, ws, wb, idx) {
  21558. if(!ws['!autofilter']) return;
  21559. var data = ws['!autofilter'];
  21560. var ref = typeof data.ref === "string" ? data.ref : encode_range(data.ref);
  21561. /* Update FilterDatabase defined name for the worksheet */
  21562. if(!wb.Workbook) wb.Workbook = ({Sheets:[]});
  21563. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  21564. var names = wb.Workbook.Names;
  21565. var range = decode_range(ref);
  21566. if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
  21567. for(var i = 0; i < names.length; ++i) {
  21568. var name = names[i];
  21569. if(name.Name != '_xlnm._FilterDatabase') continue;
  21570. if(name.Sheet != idx) continue;
  21571. name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
  21572. }
  21573. if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref });
  21574. write_record(ba, "BrtBeginAFilter", write_UncheckedRfX(safe_decode_range(ref)));
  21575. /* *FILTERCOLUMN */
  21576. /* [SORTSTATE] */
  21577. /* BrtEndAFilter */
  21578. write_record(ba, "BrtEndAFilter");
  21579. }
  21580. function write_WSVIEWS2(ba, ws, Workbook) {
  21581. write_record(ba, "BrtBeginWsViews");
  21582. { /* 1*WSVIEW2 */
  21583. /* [ACUID] */
  21584. write_record(ba, "BrtBeginWsView", write_BrtBeginWsView(ws, Workbook));
  21585. /* [BrtPane] */
  21586. /* *4BrtSel */
  21587. /* *4SXSELECT */
  21588. /* *FRT */
  21589. write_record(ba, "BrtEndWsView");
  21590. }
  21591. /* *FRT */
  21592. write_record(ba, "BrtEndWsViews");
  21593. }
  21594. function write_WSFMTINFO() {
  21595. /* [ACWSFMTINFO] */
  21596. //write_record(ba, "BrtWsFmtInfo", write_BrtWsFmtInfo(ws));
  21597. }
  21598. function write_SHEETPROTECT(ba, ws) {
  21599. if(!ws['!protect']) return;
  21600. /* [BrtSheetProtectionIso] */
  21601. write_record(ba, "BrtSheetProtection", write_BrtSheetProtection(ws['!protect']));
  21602. }
  21603. function write_ws_bin(idx, opts, wb, rels) {
  21604. var ba = buf_array();
  21605. var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
  21606. var c = s; try { if(wb && wb.Workbook) c = wb.Workbook.Sheets[idx].CodeName || c; } catch(e) {}
  21607. var r = safe_decode_range(ws['!ref'] || "A1");
  21608. if(r.e.c > 0x3FFF || r.e.r > 0xFFFFF) {
  21609. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:XFD1048576");
  21610. r.e.c = Math.min(r.e.c, 0x3FFF);
  21611. r.e.r = Math.min(r.e.c, 0xFFFFF);
  21612. }
  21613. ws['!links'] = [];
  21614. /* passed back to write_zip and removed there */
  21615. ws['!comments'] = [];
  21616. write_record(ba, "BrtBeginSheet");
  21617. if(wb.vbaraw) write_record(ba, "BrtWsProp", write_BrtWsProp(c));
  21618. write_record(ba, "BrtWsDim", write_BrtWsDim(r));
  21619. write_WSVIEWS2(ba, ws, wb.Workbook);
  21620. write_WSFMTINFO(ba, ws);
  21621. write_COLINFOS(ba, ws, idx, opts, wb);
  21622. write_CELLTABLE(ba, ws, idx, opts, wb);
  21623. /* [BrtSheetCalcProp] */
  21624. write_SHEETPROTECT(ba, ws);
  21625. /* *([BrtRangeProtectionIso] BrtRangeProtection) */
  21626. /* [SCENMAN] */
  21627. write_AUTOFILTER(ba, ws, wb, idx);
  21628. /* [SORTSTATE] */
  21629. /* [DCON] */
  21630. /* [USERSHVIEWS] */
  21631. write_MERGECELLS(ba, ws);
  21632. /* [BrtPhoneticInfo] */
  21633. /* *CONDITIONALFORMATTING */
  21634. /* [DVALS] */
  21635. write_HLINKS(ba, ws, rels);
  21636. /* [BrtPrintOptions] */
  21637. if(ws['!margins']) write_record(ba, "BrtMargins", write_BrtMargins(ws['!margins']));
  21638. /* [BrtPageSetup] */
  21639. /* [HEADERFOOTER] */
  21640. /* [RWBRK] */
  21641. /* [COLBRK] */
  21642. /* *BrtBigName */
  21643. /* [CELLWATCHES] */
  21644. if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) write_IGNOREECS(ba, ws);
  21645. /* [SMARTTAGS] */
  21646. /* [BrtDrawing] */
  21647. write_LEGACYDRAWING(ba, ws, idx, rels);
  21648. /* [BrtLegacyDrawingHF] */
  21649. /* [BrtBkHim] */
  21650. /* [OLEOBJECTS] */
  21651. /* [ACTIVEXCONTROLS] */
  21652. /* [WEBPUBITEMS] */
  21653. /* [LISTPARTS] */
  21654. /* FRTWORKSHEET */
  21655. write_record(ba, "BrtEndSheet");
  21656. return ba.end();
  21657. }
  21658. RELS.CHART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart";
  21659. RELS.CHARTEX = "http://schemas.microsoft.com/office/2014/relationships/chartEx";
  21660. function parse_Cache(data) {
  21661. var col = [];
  21662. var num = data.match(/^<c:numCache>/);
  21663. var f;
  21664. /* 21.2.2.150 pt CT_NumVal */
  21665. (data.match(/<c:pt idx="(\d*)">(.*?)<\/c:pt>/mg)||[]).forEach(function(pt) {
  21666. var q = pt.match(/<c:pt idx="(\d*?)"><c:v>(.*)<\/c:v><\/c:pt>/);
  21667. if(!q) return;
  21668. col[+q[1]] = num ? +q[2] : q[2];
  21669. });
  21670. /* 21.2.2.71 formatCode CT_Xstring */
  21671. var nf = unescapexml((data.match(/<c:formatCode>([\s\S]*?)<\/c:formatCode>/) || ["","General"])[1]);
  21672. (data.match(/<c:f>(.*?)<\/c:f>/mg)||[]).forEach(function(F) { f = F.replace(/<.*?>/g,""); });
  21673. return [col, nf, f];
  21674. }
  21675. /* 21.2 DrawingML - Charts */
  21676. function parse_chart(data, name, opts, rels, wb, csheet) {
  21677. var cs = ((csheet || {"!type":"chart"}));
  21678. if(!data) return csheet;
  21679. /* 21.2.2.27 chart CT_Chart */
  21680. var C = 0, R = 0, col = "A";
  21681. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  21682. /* 21.2.2.120 numCache CT_NumData */
  21683. (data.match(/<c:numCache>[\s\S]*?<\/c:numCache>/gm)||[]).forEach(function(nc) {
  21684. var cache = parse_Cache(nc);
  21685. refguess.s.r = refguess.s.c = 0;
  21686. refguess.e.c = C;
  21687. col = encode_col(C);
  21688. cache[0].forEach(function(n,i) {
  21689. cs[col + encode_row(i)] = {t:'n', v:n, z:cache[1] };
  21690. R = i;
  21691. });
  21692. if(refguess.e.r < R) refguess.e.r = R;
  21693. ++C;
  21694. });
  21695. if(C > 0) cs["!ref"] = encode_range(refguess);
  21696. return cs;
  21697. }
  21698. RELS.CS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet";
  21699. var CS_XML_ROOT = writextag('chartsheet', null, {
  21700. 'xmlns': XMLNS.main[0],
  21701. 'xmlns:r': XMLNS.r
  21702. });
  21703. /* 18.3 Worksheets also covers Chartsheets */
  21704. function parse_cs_xml(data, opts, idx, rels, wb) {
  21705. if(!data) return data;
  21706. /* 18.3.1.12 chartsheet CT_ChartSheet */
  21707. if(!rels) rels = {'!id':{}};
  21708. var s = ({'!type':"chart", '!drawel':null, '!rel':""});
  21709. var m;
  21710. /* 18.3.1.83 sheetPr CT_ChartsheetPr */
  21711. var sheetPr = data.match(sheetprregex);
  21712. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  21713. /* 18.3.1.36 drawing CT_Drawing */
  21714. if((m = data.match(/drawing r:id="(.*?)"/))) s['!rel'] = m[1];
  21715. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  21716. return s;
  21717. }
  21718. function write_cs_xml(idx, opts, wb, rels) {
  21719. var o = [XML_HEADER, CS_XML_ROOT];
  21720. o[o.length] = writextag("drawing", null, {"r:id": "rId1"});
  21721. add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  21722. if(o.length>2) { o[o.length] = ('</chartsheet>'); o[1]=o[1].replace("/>",">"); }
  21723. return o.join("");
  21724. }
  21725. /* [MS-XLSB] 2.4.331 BrtCsProp */
  21726. function parse_BrtCsProp(data, length) {
  21727. data.l += 10;
  21728. var name = parse_XLWideString(data, length - 10);
  21729. return { name: name };
  21730. }
  21731. /* [MS-XLSB] 2.1.7.7 Chart Sheet */
  21732. function parse_cs_bin(data, opts, idx, rels, wb) {
  21733. if(!data) return data;
  21734. if(!rels) rels = {'!id':{}};
  21735. var s = {'!type':"chart", '!drawel':null, '!rel':""};
  21736. var state = [];
  21737. var pass = false;
  21738. recordhopper(data, function cs_parse(val, R_n, RT) {
  21739. switch(RT) {
  21740. case 0x0226: /* 'BrtDrawing' */
  21741. s['!rel'] = val; break;
  21742. case 0x028B: /* 'BrtCsProp' */
  21743. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  21744. if(val.name) wb.Sheets[idx].CodeName = val.name;
  21745. break;
  21746. case 0x0232: /* 'BrtBkHim' */
  21747. case 0x028C: /* 'BrtCsPageSetup' */
  21748. case 0x029D: /* 'BrtCsProtection' */
  21749. case 0x02A7: /* 'BrtCsProtectionIso' */
  21750. case 0x0227: /* 'BrtLegacyDrawing' */
  21751. case 0x0228: /* 'BrtLegacyDrawingHF' */
  21752. case 0x01DC: /* 'BrtMargins' */
  21753. case 0x0C00: /* 'BrtUid' */
  21754. break;
  21755. case 0x0023: /* 'BrtFRTBegin' */
  21756. pass = true; break;
  21757. case 0x0024: /* 'BrtFRTEnd' */
  21758. pass = false; break;
  21759. case 0x0025: /* 'BrtACBegin' */
  21760. state.push(R_n); break;
  21761. case 0x0026: /* 'BrtACEnd' */
  21762. state.pop(); break;
  21763. default:
  21764. if((R_n||"").indexOf("Begin") > 0) state.push(R_n);
  21765. else if((R_n||"").indexOf("End") > 0) state.pop();
  21766. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  21767. }
  21768. }, opts);
  21769. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  21770. return s;
  21771. }
  21772. function write_cs_bin() {
  21773. var ba = buf_array();
  21774. write_record(ba, "BrtBeginSheet");
  21775. /* [BrtCsProp] */
  21776. /* CSVIEWS */
  21777. /* [[BrtCsProtectionIso] BrtCsProtection] */
  21778. /* [USERCSVIEWS] */
  21779. /* [BrtMargins] */
  21780. /* [BrtCsPageSetup] */
  21781. /* [HEADERFOOTER] */
  21782. /* BrtDrawing */
  21783. /* [BrtLegacyDrawing] */
  21784. /* [BrtLegacyDrawingHF] */
  21785. /* [BrtBkHim] */
  21786. /* [WEBPUBITEMS] */
  21787. /* FRTCHARTSHEET */
  21788. write_record(ba, "BrtEndSheet");
  21789. return ba.end();
  21790. }
  21791. /* 18.2.28 (CT_WorkbookProtection) Defaults */
  21792. var WBPropsDef = [
  21793. ['allowRefreshQuery', false, "bool"],
  21794. ['autoCompressPictures', true, "bool"],
  21795. ['backupFile', false, "bool"],
  21796. ['checkCompatibility', false, "bool"],
  21797. ['CodeName', ''],
  21798. ['date1904', false, "bool"],
  21799. ['defaultThemeVersion', 0, "int"],
  21800. ['filterPrivacy', false, "bool"],
  21801. ['hidePivotFieldList', false, "bool"],
  21802. ['promptedSolutions', false, "bool"],
  21803. ['publishItems', false, "bool"],
  21804. ['refreshAllConnections', false, "bool"],
  21805. ['saveExternalLinkValues', true, "bool"],
  21806. ['showBorderUnselectedTables', true, "bool"],
  21807. ['showInkAnnotation', true, "bool"],
  21808. ['showObjects', 'all'],
  21809. ['showPivotChartFilter', false, "bool"],
  21810. ['updateLinks', 'userSet']
  21811. ];
  21812. /* 18.2.30 (CT_BookView) Defaults */
  21813. var WBViewDef = [
  21814. ['activeTab', 0, "int"],
  21815. ['autoFilterDateGrouping', true, "bool"],
  21816. ['firstSheet', 0, "int"],
  21817. ['minimized', false, "bool"],
  21818. ['showHorizontalScroll', true, "bool"],
  21819. ['showSheetTabs', true, "bool"],
  21820. ['showVerticalScroll', true, "bool"],
  21821. ['tabRatio', 600, "int"],
  21822. ['visibility', 'visible']
  21823. //window{Height,Width}, {x,y}Window
  21824. ];
  21825. /* 18.2.19 (CT_Sheet) Defaults */
  21826. var SheetDef = [
  21827. //['state', 'visible']
  21828. ];
  21829. /* 18.2.2 (CT_CalcPr) Defaults */
  21830. var CalcPrDef = [
  21831. ['calcCompleted', 'true'],
  21832. ['calcMode', 'auto'],
  21833. ['calcOnSave', 'true'],
  21834. ['concurrentCalc', 'true'],
  21835. ['fullCalcOnLoad', 'false'],
  21836. ['fullPrecision', 'true'],
  21837. ['iterate', 'false'],
  21838. ['iterateCount', '100'],
  21839. ['iterateDelta', '0.001'],
  21840. ['refMode', 'A1']
  21841. ];
  21842. /* 18.2.3 (CT_CustomWorkbookView) Defaults */
  21843. /*var CustomWBViewDef = [
  21844. ['autoUpdate', 'false'],
  21845. ['changesSavedWin', 'false'],
  21846. ['includeHiddenRowCol', 'true'],
  21847. ['includePrintSettings', 'true'],
  21848. ['maximized', 'false'],
  21849. ['minimized', 'false'],
  21850. ['onlySync', 'false'],
  21851. ['personalView', 'false'],
  21852. ['showComments', 'commIndicator'],
  21853. ['showFormulaBar', 'true'],
  21854. ['showHorizontalScroll', 'true'],
  21855. ['showObjects', 'all'],
  21856. ['showSheetTabs', 'true'],
  21857. ['showStatusbar', 'true'],
  21858. ['showVerticalScroll', 'true'],
  21859. ['tabRatio', '600'],
  21860. ['xWindow', '0'],
  21861. ['yWindow', '0']
  21862. ];*/
  21863. function push_defaults_array(target, defaults) {
  21864. for(var j = 0; j != target.length; ++j) { var w = target[j];
  21865. for(var i=0; i != defaults.length; ++i) { var z = defaults[i];
  21866. if(w[z[0]] == null) w[z[0]] = z[1];
  21867. else switch(z[2]) {
  21868. case "bool": if(typeof w[z[0]] == "string") w[z[0]] = parsexmlbool(w[z[0]]); break;
  21869. case "int": if(typeof w[z[0]] == "string") w[z[0]] = parseInt(w[z[0]], 10); break;
  21870. }
  21871. }
  21872. }
  21873. }
  21874. function push_defaults(target, defaults) {
  21875. for(var i = 0; i != defaults.length; ++i) { var z = defaults[i];
  21876. if(target[z[0]] == null) target[z[0]] = z[1];
  21877. else switch(z[2]) {
  21878. case "bool": if(typeof target[z[0]] == "string") target[z[0]] = parsexmlbool(target[z[0]]); break;
  21879. case "int": if(typeof target[z[0]] == "string") target[z[0]] = parseInt(target[z[0]], 10); break;
  21880. }
  21881. }
  21882. }
  21883. function parse_wb_defaults(wb) {
  21884. push_defaults(wb.WBProps, WBPropsDef);
  21885. push_defaults(wb.CalcPr, CalcPrDef);
  21886. push_defaults_array(wb.WBView, WBViewDef);
  21887. push_defaults_array(wb.Sheets, SheetDef);
  21888. _ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904);
  21889. }
  21890. function safe1904(wb) {
  21891. /* TODO: store date1904 somewhere else */
  21892. if(!wb.Workbook) return "false";
  21893. if(!wb.Workbook.WBProps) return "false";
  21894. return parsexmlbool(wb.Workbook.WBProps.date1904) ? "true" : "false";
  21895. }
  21896. var badchars = "][*?\/\\".split("");
  21897. function check_ws_name(n, safe) {
  21898. if(n.length > 31) { if(safe) return false; throw new Error("Sheet names cannot exceed 31 chars"); }
  21899. var _good = true;
  21900. badchars.forEach(function(c) {
  21901. if(n.indexOf(c) == -1) return;
  21902. if(!safe) throw new Error("Sheet name cannot contain : \\ / ? * [ ]");
  21903. _good = false;
  21904. });
  21905. return _good;
  21906. }
  21907. function check_wb_names(N, S, codes) {
  21908. N.forEach(function(n,i) {
  21909. check_ws_name(n);
  21910. for(var j = 0; j < i; ++j) if(n == N[j]) throw new Error("Duplicate Sheet Name: " + n);
  21911. if(codes) {
  21912. var cn = (S && S[i] && S[i].CodeName) || n;
  21913. if(cn.charCodeAt(0) == 95 && cn.length > 22) throw new Error("Bad Code Name: Worksheet" + cn);
  21914. }
  21915. });
  21916. }
  21917. function check_wb(wb) {
  21918. if(!wb || !wb.SheetNames || !wb.Sheets) throw new Error("Invalid Workbook");
  21919. if(!wb.SheetNames.length) throw new Error("Workbook is empty");
  21920. var Sheets = (wb.Workbook && wb.Workbook.Sheets) || [];
  21921. check_wb_names(wb.SheetNames, Sheets, !!wb.vbaraw);
  21922. for(var i = 0; i < wb.SheetNames.length; ++i) check_ws(wb.Sheets[wb.SheetNames[i]], wb.SheetNames[i], i);
  21923. /* TODO: validate workbook */
  21924. }
  21925. /* 18.2 Workbook */
  21926. var wbnsregex = /<\w+:workbook/;
  21927. function parse_wb_xml(data, opts) {
  21928. if(!data) throw new Error("Could not find file");
  21929. var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, Names:[], xmlns: "" };
  21930. var pass = false, xmlns = "xmlns";
  21931. var dname = {}, dnstart = 0;
  21932. data.replace(tagregex, function xml_wb(x, idx) {
  21933. var y = parsexmltag(x);
  21934. switch(strip_ns(y[0])) {
  21935. case '<?xml': break;
  21936. /* 18.2.27 workbook CT_Workbook 1 */
  21937. case '<workbook':
  21938. if(x.match(wbnsregex)) xmlns = "xmlns" + x.match(/<(\w+):/)[1];
  21939. wb.xmlns = y[xmlns];
  21940. break;
  21941. case '</workbook>': break;
  21942. /* 18.2.13 fileVersion CT_FileVersion ? */
  21943. case '<fileVersion': delete y[0]; wb.AppVersion = y; break;
  21944. case '<fileVersion/>': case '</fileVersion>': break;
  21945. /* 18.2.12 fileSharing CT_FileSharing ? */
  21946. case '<fileSharing':
  21947. break;
  21948. case '<fileSharing/>': break;
  21949. /* 18.2.28 workbookPr CT_WorkbookPr ? */
  21950. case '<workbookPr':
  21951. case '<workbookPr/>':
  21952. WBPropsDef.forEach(function(w) {
  21953. if(y[w[0]] == null) return;
  21954. switch(w[2]) {
  21955. case "bool": wb.WBProps[w[0]] = parsexmlbool(y[w[0]]); break;
  21956. case "int": wb.WBProps[w[0]] = parseInt(y[w[0]], 10); break;
  21957. default: wb.WBProps[w[0]] = y[w[0]];
  21958. }
  21959. });
  21960. if(y.codeName) wb.WBProps.CodeName = utf8read(y.codeName);
  21961. break;
  21962. case '</workbookPr>': break;
  21963. /* 18.2.29 workbookProtection CT_WorkbookProtection ? */
  21964. case '<workbookProtection':
  21965. break;
  21966. case '<workbookProtection/>': break;
  21967. /* 18.2.1 bookViews CT_BookViews ? */
  21968. case '<bookViews': case '<bookViews>': case '</bookViews>': break;
  21969. /* 18.2.30 workbookView CT_BookView + */
  21970. case '<workbookView': case '<workbookView/>': delete y[0]; wb.WBView.push(y); break;
  21971. case '</workbookView>': break;
  21972. /* 18.2.20 sheets CT_Sheets 1 */
  21973. case '<sheets': case '<sheets>': case '</sheets>': break; // aggregate sheet
  21974. /* 18.2.19 sheet CT_Sheet + */
  21975. case '<sheet':
  21976. switch(y.state) {
  21977. case "hidden": y.Hidden = 1; break;
  21978. case "veryHidden": y.Hidden = 2; break;
  21979. default: y.Hidden = 0;
  21980. }
  21981. delete y.state;
  21982. y.name = unescapexml(utf8read(y.name));
  21983. delete y[0]; wb.Sheets.push(y); break;
  21984. case '</sheet>': break;
  21985. /* 18.2.15 functionGroups CT_FunctionGroups ? */
  21986. case '<functionGroups': case '<functionGroups/>': break;
  21987. /* 18.2.14 functionGroup CT_FunctionGroup + */
  21988. case '<functionGroup': break;
  21989. /* 18.2.9 externalReferences CT_ExternalReferences ? */
  21990. case '<externalReferences': case '</externalReferences>': case '<externalReferences>': break;
  21991. /* 18.2.8 externalReference CT_ExternalReference + */
  21992. case '<externalReference': break;
  21993. /* 18.2.6 definedNames CT_DefinedNames ? */
  21994. case '<definedNames/>': break;
  21995. case '<definedNames>': case '<definedNames': pass=true; break;
  21996. case '</definedNames>': pass=false; break;
  21997. /* 18.2.5 definedName CT_DefinedName + */
  21998. case '<definedName': {
  21999. dname = {};
  22000. dname.Name = utf8read(y.name);
  22001. if(y.comment) dname.Comment = y.comment;
  22002. if(y.localSheetId) dname.Sheet = +y.localSheetId;
  22003. if(parsexmlbool(y.hidden||"0")) dname.Hidden = true;
  22004. dnstart = idx + x.length;
  22005. } break;
  22006. case '</definedName>': {
  22007. dname.Ref = unescapexml(utf8read(data.slice(dnstart, idx)));
  22008. wb.Names.push(dname);
  22009. } break;
  22010. case '<definedName/>': break;
  22011. /* 18.2.2 calcPr CT_CalcPr ? */
  22012. case '<calcPr': delete y[0]; wb.CalcPr = y; break;
  22013. case '<calcPr/>': delete y[0]; wb.CalcPr = y; break;
  22014. case '</calcPr>': break;
  22015. /* 18.2.16 oleSize CT_OleSize ? (ref required) */
  22016. case '<oleSize': break;
  22017. /* 18.2.4 customWorkbookViews CT_CustomWorkbookViews ? */
  22018. case '<customWorkbookViews>': case '</customWorkbookViews>': case '<customWorkbookViews': break;
  22019. /* 18.2.3 customWorkbookView CT_CustomWorkbookView + */
  22020. case '<customWorkbookView': case '</customWorkbookView>': break;
  22021. /* 18.2.18 pivotCaches CT_PivotCaches ? */
  22022. case '<pivotCaches>': case '</pivotCaches>': case '<pivotCaches': break;
  22023. /* 18.2.17 pivotCache CT_PivotCache ? */
  22024. case '<pivotCache': break;
  22025. /* 18.2.21 smartTagPr CT_SmartTagPr ? */
  22026. case '<smartTagPr': case '<smartTagPr/>': break;
  22027. /* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
  22028. case '<smartTagTypes': case '<smartTagTypes>': case '</smartTagTypes>': break;
  22029. /* 18.2.22 smartTagType CT_SmartTagType ? */
  22030. case '<smartTagType': break;
  22031. /* 18.2.24 webPublishing CT_WebPublishing ? */
  22032. case '<webPublishing': case '<webPublishing/>': break;
  22033. /* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
  22034. case '<fileRecoveryPr': case '<fileRecoveryPr/>': break;
  22035. /* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
  22036. case '<webPublishObjects>': case '<webPublishObjects': case '</webPublishObjects>': break;
  22037. /* 18.2.25 webPublishObject CT_WebPublishObject ? */
  22038. case '<webPublishObject': break;
  22039. /* 18.2.10 extLst CT_ExtensionList ? */
  22040. case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
  22041. /* 18.2.7 ext CT_Extension + */
  22042. case '<ext': pass=true; break; //TODO: check with versions of excel
  22043. case '</ext>': pass=false; break;
  22044. /* Others */
  22045. case '<ArchID': break;
  22046. case '<AlternateContent':
  22047. case '<AlternateContent>': pass=true; break;
  22048. case '</AlternateContent>': pass=false; break;
  22049. /* TODO */
  22050. case '<revisionPtr': break;
  22051. default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in workbook');
  22052. }
  22053. return x;
  22054. });
  22055. if(XMLNS.main.indexOf(wb.xmlns) === -1) throw new Error("Unknown Namespace: " + wb.xmlns);
  22056. parse_wb_defaults(wb);
  22057. return wb;
  22058. }
  22059. var WB_XML_ROOT = writextag('workbook', null, {
  22060. 'xmlns': XMLNS.main[0],
  22061. //'xmlns:mx': XMLNS.mx,
  22062. //'xmlns:s': XMLNS.main[0],
  22063. 'xmlns:r': XMLNS.r
  22064. });
  22065. function write_wb_xml(wb) {
  22066. var o = [XML_HEADER];
  22067. o[o.length] = WB_XML_ROOT;
  22068. var write_names = (wb.Workbook && (wb.Workbook.Names||[]).length > 0);
  22069. /* fileVersion */
  22070. /* fileSharing */
  22071. var workbookPr = ({codeName:"ThisWorkbook"});
  22072. if(wb.Workbook && wb.Workbook.WBProps) {
  22073. WBPropsDef.forEach(function(x) {
  22074. if((wb.Workbook.WBProps[x[0]]) == null) return;
  22075. if((wb.Workbook.WBProps[x[0]]) == x[1]) return;
  22076. workbookPr[x[0]] = (wb.Workbook.WBProps[x[0]]);
  22077. });
  22078. if(wb.Workbook.WBProps.CodeName) { workbookPr.codeName = wb.Workbook.WBProps.CodeName; delete workbookPr.CodeName; }
  22079. }
  22080. o[o.length] = (writextag('workbookPr', null, workbookPr));
  22081. /* workbookProtection */
  22082. var sheets = wb.Workbook && wb.Workbook.Sheets || [];
  22083. var i = 0;
  22084. /* bookViews only written if first worksheet is hidden */
  22085. if(sheets && sheets[0] && !!sheets[0].Hidden) {
  22086. o[o.length] = "<bookViews>";
  22087. for(i = 0; i != wb.SheetNames.length; ++i) {
  22088. if(!sheets[i]) break;
  22089. if(!sheets[i].Hidden) break;
  22090. }
  22091. if(i == wb.SheetNames.length) i = 0;
  22092. o[o.length] = '<workbookView firstSheet="' + i + '" activeTab="' + i + '"/>';
  22093. o[o.length] = "</bookViews>";
  22094. }
  22095. o[o.length] = "<sheets>";
  22096. for(i = 0; i != wb.SheetNames.length; ++i) {
  22097. var sht = ({name:escapexml(wb.SheetNames[i].slice(0,31))});
  22098. sht.sheetId = ""+(i+1);
  22099. sht["r:id"] = "rId"+(i+1);
  22100. if(sheets[i]) switch(sheets[i].Hidden) {
  22101. case 1: sht.state = "hidden"; break;
  22102. case 2: sht.state = "veryHidden"; break;
  22103. }
  22104. o[o.length] = (writextag('sheet',null,sht));
  22105. }
  22106. o[o.length] = "</sheets>";
  22107. /* functionGroups */
  22108. /* externalReferences */
  22109. if(write_names) {
  22110. o[o.length] = "<definedNames>";
  22111. if(wb.Workbook && wb.Workbook.Names) wb.Workbook.Names.forEach(function(n) {
  22112. var d = {name:n.Name};
  22113. if(n.Comment) d.comment = n.Comment;
  22114. if(n.Sheet != null) d.localSheetId = ""+n.Sheet;
  22115. if(n.Hidden) d.hidden = "1";
  22116. if(!n.Ref) return;
  22117. o[o.length] = writextag('definedName', escapexml(n.Ref), d);
  22118. });
  22119. o[o.length] = "</definedNames>";
  22120. }
  22121. /* calcPr */
  22122. /* oleSize */
  22123. /* customWorkbookViews */
  22124. /* pivotCaches */
  22125. /* smartTagPr */
  22126. /* smartTagTypes */
  22127. /* webPublishing */
  22128. /* fileRecoveryPr */
  22129. /* webPublishObjects */
  22130. /* extLst */
  22131. if(o.length>2){ o[o.length] = '</workbook>'; o[1]=o[1].replace("/>",">"); }
  22132. return o.join("");
  22133. }
  22134. /* [MS-XLSB] 2.4.304 BrtBundleSh */
  22135. function parse_BrtBundleSh(data, length) {
  22136. var z = {};
  22137. z.Hidden = data.read_shift(4); //hsState ST_SheetState
  22138. z.iTabID = data.read_shift(4);
  22139. z.strRelID = parse_RelID(data,length-8);
  22140. z.name = parse_XLWideString(data);
  22141. return z;
  22142. }
  22143. function write_BrtBundleSh(data, o) {
  22144. if(!o) o = new_buf(127);
  22145. o.write_shift(4, data.Hidden);
  22146. o.write_shift(4, data.iTabID);
  22147. write_RelID(data.strRelID, o);
  22148. write_XLWideString(data.name.slice(0,31), o);
  22149. return o.length > o.l ? o.slice(0, o.l) : o;
  22150. }
  22151. /* [MS-XLSB] 2.4.815 BrtWbProp */
  22152. function parse_BrtWbProp(data, length) {
  22153. var o = ({});
  22154. var flags = data.read_shift(4);
  22155. o.defaultThemeVersion = data.read_shift(4);
  22156. var strName = (length > 8) ? parse_XLWideString(data) : "";
  22157. if(strName.length > 0) o.CodeName = strName;
  22158. o.autoCompressPictures = !!(flags & 0x10000);
  22159. o.backupFile = !!(flags & 0x40);
  22160. o.checkCompatibility = !!(flags & 0x1000);
  22161. o.date1904 = !!(flags & 0x01);
  22162. o.filterPrivacy = !!(flags & 0x08);
  22163. o.hidePivotFieldList = !!(flags & 0x400);
  22164. o.promptedSolutions = !!(flags & 0x10);
  22165. o.publishItems = !!(flags & 0x800);
  22166. o.refreshAllConnections = !!(flags & 0x40000);
  22167. o.saveExternalLinkValues = !!(flags & 0x80);
  22168. o.showBorderUnselectedTables = !!(flags & 0x04);
  22169. o.showInkAnnotation = !!(flags & 0x20);
  22170. o.showObjects = ["all", "placeholders", "none"][(flags >> 13) & 0x03];
  22171. o.showPivotChartFilter = !!(flags & 0x8000);
  22172. o.updateLinks = ["userSet", "never", "always"][(flags >> 8) & 0x03];
  22173. return o;
  22174. }
  22175. function write_BrtWbProp(data, o) {
  22176. if(!o) o = new_buf(72);
  22177. var flags = 0;
  22178. if(data) {
  22179. /* TODO: mirror parse_BrtWbProp fields */
  22180. if(data.filterPrivacy) flags |= 0x08;
  22181. }
  22182. o.write_shift(4, flags);
  22183. o.write_shift(4, 0);
  22184. write_XLSBCodeName(data && data.CodeName || "ThisWorkbook", o);
  22185. return o.slice(0, o.l);
  22186. }
  22187. function parse_BrtFRTArchID$(data, length) {
  22188. var o = {};
  22189. data.read_shift(4);
  22190. o.ArchID = data.read_shift(4);
  22191. data.l += length - 8;
  22192. return o;
  22193. }
  22194. /* [MS-XLSB] 2.4.687 BrtName */
  22195. function parse_BrtName(data, length, opts) {
  22196. var end = data.l + length;
  22197. data.l += 4; //var flags = data.read_shift(4);
  22198. data.l += 1; //var chKey = data.read_shift(1);
  22199. var itab = data.read_shift(4);
  22200. var name = parse_XLNameWideString(data);
  22201. var formula = parse_XLSBNameParsedFormula(data, 0, opts);
  22202. var comment = parse_XLNullableWideString(data);
  22203. //if(0 /* fProc */) {
  22204. // unusedstring1: XLNullableWideString
  22205. // description: XLNullableWideString
  22206. // helpTopic: XLNullableWideString
  22207. // unusedstring2: XLNullableWideString
  22208. //}
  22209. data.l = end;
  22210. var out = ({Name:name, Ptg:formula});
  22211. if(itab < 0xFFFFFFF) out.Sheet = itab;
  22212. if(comment) out.Comment = comment;
  22213. return out;
  22214. }
  22215. /* [MS-XLSB] 2.1.7.61 Workbook */
  22216. function parse_wb_bin(data, opts) {
  22217. var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, xmlns: "" };
  22218. var state = [];
  22219. var pass = false;
  22220. if(!opts) opts = {};
  22221. opts.biff = 12;
  22222. var Names = [];
  22223. var supbooks = ([[]]);
  22224. supbooks.SheetNames = [];
  22225. supbooks.XTI = [];
  22226. recordhopper(data, function hopper_wb(val, R_n, RT) {
  22227. switch(RT) {
  22228. case 0x009C: /* 'BrtBundleSh' */
  22229. supbooks.SheetNames.push(val.name);
  22230. wb.Sheets.push(val); break;
  22231. case 0x0099: /* 'BrtWbProp' */
  22232. wb.WBProps = val; break;
  22233. case 0x0027: /* 'BrtName' */
  22234. if(val.Sheet != null) opts.SID = val.Sheet;
  22235. val.Ref = stringify_formula(val.Ptg, null, null, supbooks, opts);
  22236. delete opts.SID;
  22237. delete val.Ptg;
  22238. Names.push(val);
  22239. break;
  22240. case 0x040C: /* 'BrtNameExt' */ break;
  22241. case 0x0165: /* 'BrtSupSelf' */
  22242. case 0x0166: /* 'BrtSupSame' */
  22243. case 0x0163: /* 'BrtSupBookSrc' */
  22244. case 0x029B: /* 'BrtSupAddin' */
  22245. if(!supbooks[0].length) supbooks[0] = [RT, val];
  22246. else supbooks.push([RT, val]);
  22247. supbooks[supbooks.length - 1].XTI = [];
  22248. break;
  22249. case 0x016A: /* 'BrtExternSheet' */
  22250. if(supbooks.length === 0) { supbooks[0] = []; supbooks[0].XTI = []; }
  22251. supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val);
  22252. supbooks.XTI = supbooks.XTI.concat(val);
  22253. break;
  22254. case 0x0169: /* 'BrtPlaceholderName' */
  22255. break;
  22256. /* case 'BrtModelTimeGroupingCalcCol' */
  22257. case 0x0C00: /* 'BrtUid' */
  22258. case 0x0C01: /* 'BrtRevisionPtr' */
  22259. case 0x0817: /* 'BrtAbsPath15' */
  22260. case 0x0216: /* 'BrtBookProtection' */
  22261. case 0x02A5: /* 'BrtBookProtectionIso' */
  22262. case 0x009E: /* 'BrtBookView' */
  22263. case 0x009D: /* 'BrtCalcProp' */
  22264. case 0x0262: /* 'BrtCrashRecErr' */
  22265. case 0x0802: /* 'BrtDecoupledPivotCacheID' */
  22266. case 0x009B: /* 'BrtFileRecover' */
  22267. case 0x0224: /* 'BrtFileSharing' */
  22268. case 0x02A4: /* 'BrtFileSharingIso' */
  22269. case 0x0080: /* 'BrtFileVersion' */
  22270. case 0x0299: /* 'BrtFnGroup' */
  22271. case 0x0850: /* 'BrtModelRelationship' */
  22272. case 0x084D: /* 'BrtModelTable' */
  22273. case 0x0225: /* 'BrtOleSize' */
  22274. case 0x0805: /* 'BrtPivotTableRef' */
  22275. case 0x0254: /* 'BrtSmartTagType' */
  22276. case 0x081C: /* 'BrtTableSlicerCacheID' */
  22277. case 0x081B: /* 'BrtTableSlicerCacheIDs' */
  22278. case 0x0822: /* 'BrtTimelineCachePivotCacheID' */
  22279. case 0x018D: /* 'BrtUserBookView' */
  22280. case 0x009A: /* 'BrtWbFactoid' */
  22281. case 0x045D: /* 'BrtWbProp14' */
  22282. case 0x0229: /* 'BrtWebOpt' */
  22283. case 0x082B: /* 'BrtWorkBookPr15' */
  22284. break;
  22285. case 0x0023: /* 'BrtFRTBegin' */
  22286. state.push(R_n); pass = true; break;
  22287. case 0x0024: /* 'BrtFRTEnd' */
  22288. state.pop(); pass = false; break;
  22289. case 0x0025: /* 'BrtACBegin' */
  22290. state.push(R_n); pass = true; break;
  22291. case 0x0026: /* 'BrtACEnd' */
  22292. state.pop(); pass = false; break;
  22293. case 0x0010: /* 'BrtFRTArchID$' */ break;
  22294. default:
  22295. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  22296. else if((R_n||"").indexOf("End") > 0){/* empty */}
  22297. else if(!pass || (opts.WTF && state[state.length-1] != "BrtACBegin" && state[state.length-1] != "BrtFRTBegin")) throw new Error("Unexpected record " + RT + " " + R_n);
  22298. }
  22299. }, opts);
  22300. parse_wb_defaults(wb);
  22301. // $FlowIgnore
  22302. wb.Names = Names;
  22303. (wb).supbooks = supbooks;
  22304. return wb;
  22305. }
  22306. function write_BUNDLESHS(ba, wb) {
  22307. write_record(ba, "BrtBeginBundleShs");
  22308. for(var idx = 0; idx != wb.SheetNames.length; ++idx) {
  22309. var viz = wb.Workbook && wb.Workbook.Sheets && wb.Workbook.Sheets[idx] && wb.Workbook.Sheets[idx].Hidden || 0;
  22310. var d = { Hidden: viz, iTabID: idx+1, strRelID: 'rId' + (idx+1), name: wb.SheetNames[idx] };
  22311. write_record(ba, "BrtBundleSh", write_BrtBundleSh(d));
  22312. }
  22313. write_record(ba, "BrtEndBundleShs");
  22314. }
  22315. /* [MS-XLSB] 2.4.649 BrtFileVersion */
  22316. function write_BrtFileVersion(data, o) {
  22317. if(!o) o = new_buf(127);
  22318. for(var i = 0; i != 4; ++i) o.write_shift(4, 0);
  22319. write_XLWideString("SheetJS", o);
  22320. write_XLWideString(XLSX.version, o);
  22321. write_XLWideString(XLSX.version, o);
  22322. write_XLWideString("7262", o);
  22323. o.length = o.l;
  22324. return o.length > o.l ? o.slice(0, o.l) : o;
  22325. }
  22326. /* [MS-XLSB] 2.4.301 BrtBookView */
  22327. function write_BrtBookView(idx, o) {
  22328. if(!o) o = new_buf(29);
  22329. o.write_shift(-4, 0);
  22330. o.write_shift(-4, 460);
  22331. o.write_shift(4, 28800);
  22332. o.write_shift(4, 17600);
  22333. o.write_shift(4, 500);
  22334. o.write_shift(4, idx);
  22335. o.write_shift(4, idx);
  22336. var flags = 0x78;
  22337. o.write_shift(1, flags);
  22338. return o.length > o.l ? o.slice(0, o.l) : o;
  22339. }
  22340. function write_BOOKVIEWS(ba, wb) {
  22341. /* required if hidden tab appears before visible tab */
  22342. if(!wb.Workbook || !wb.Workbook.Sheets) return;
  22343. var sheets = wb.Workbook.Sheets;
  22344. var i = 0, vistab = -1, hidden = -1;
  22345. for(; i < sheets.length; ++i) {
  22346. if(!sheets[i] || !sheets[i].Hidden && vistab == -1) vistab = i;
  22347. else if(sheets[i].Hidden == 1 && hidden == -1) hidden = i;
  22348. }
  22349. if(hidden > vistab) return;
  22350. write_record(ba, "BrtBeginBookViews");
  22351. write_record(ba, "BrtBookView", write_BrtBookView(vistab));
  22352. /* 1*(BrtBookView *FRT) */
  22353. write_record(ba, "BrtEndBookViews");
  22354. }
  22355. /* [MS-XLSB] 2.4.305 BrtCalcProp */
  22356. /*function write_BrtCalcProp(data, o) {
  22357. if(!o) o = new_buf(26);
  22358. o.write_shift(4,0); // force recalc
  22359. o.write_shift(4,1);
  22360. o.write_shift(4,0);
  22361. write_Xnum(0, o);
  22362. o.write_shift(-4, 1023);
  22363. o.write_shift(1, 0x33);
  22364. o.write_shift(1, 0x00);
  22365. return o;
  22366. }*/
  22367. /* [MS-XLSB] 2.4.646 BrtFileRecover */
  22368. /*function write_BrtFileRecover(data, o) {
  22369. if(!o) o = new_buf(1);
  22370. o.write_shift(1,0);
  22371. return o;
  22372. }*/
  22373. /* [MS-XLSB] 2.1.7.61 Workbook */
  22374. function write_wb_bin(wb, opts) {
  22375. var ba = buf_array();
  22376. write_record(ba, "BrtBeginBook");
  22377. write_record(ba, "BrtFileVersion", write_BrtFileVersion());
  22378. /* [[BrtFileSharingIso] BrtFileSharing] */
  22379. write_record(ba, "BrtWbProp", write_BrtWbProp(wb.Workbook && wb.Workbook.WBProps || null));
  22380. /* [ACABSPATH] */
  22381. /* [[BrtBookProtectionIso] BrtBookProtection] */
  22382. write_BOOKVIEWS(ba, wb, opts);
  22383. write_BUNDLESHS(ba, wb, opts);
  22384. /* [FNGROUP] */
  22385. /* [EXTERNALS] */
  22386. /* *BrtName */
  22387. /* write_record(ba, "BrtCalcProp", write_BrtCalcProp()); */
  22388. /* [BrtOleSize] */
  22389. /* *(BrtUserBookView *FRT) */
  22390. /* [PIVOTCACHEIDS] */
  22391. /* [BrtWbFactoid] */
  22392. /* [SMARTTAGTYPES] */
  22393. /* [BrtWebOpt] */
  22394. /* write_record(ba, "BrtFileRecover", write_BrtFileRecover()); */
  22395. /* [WEBPUBITEMS] */
  22396. /* [CRERRS] */
  22397. /* FRTWORKBOOK */
  22398. write_record(ba, "BrtEndBook");
  22399. return ba.end();
  22400. }
  22401. function parse_wb(data, name, opts) {
  22402. if(name.slice(-4)===".bin") return parse_wb_bin((data), opts);
  22403. return parse_wb_xml((data), opts);
  22404. }
  22405. function parse_ws(data, name, idx, opts, rels, wb, themes, styles) {
  22406. if(name.slice(-4)===".bin") return parse_ws_bin((data), opts, idx, rels, wb, themes, styles);
  22407. return parse_ws_xml((data), opts, idx, rels, wb, themes, styles);
  22408. }
  22409. function parse_cs(data, name, idx, opts, rels, wb, themes, styles) {
  22410. if(name.slice(-4)===".bin") return parse_cs_bin((data), opts, idx, rels, wb, themes, styles);
  22411. return parse_cs_xml((data), opts, idx, rels, wb, themes, styles);
  22412. }
  22413. function parse_ms(data, name, idx, opts, rels, wb, themes, styles) {
  22414. if(name.slice(-4)===".bin") return parse_ms_bin((data), opts, idx, rels, wb, themes, styles);
  22415. return parse_ms_xml((data), opts, idx, rels, wb, themes, styles);
  22416. }
  22417. function parse_ds(data, name, idx, opts, rels, wb, themes, styles) {
  22418. if(name.slice(-4)===".bin") return parse_ds_bin((data), opts, idx, rels, wb, themes, styles);
  22419. return parse_ds_xml((data), opts, idx, rels, wb, themes, styles);
  22420. }
  22421. function parse_sty(data, name, themes, opts) {
  22422. if(name.slice(-4)===".bin") return parse_sty_bin((data), themes, opts);
  22423. return parse_sty_xml((data), themes, opts);
  22424. }
  22425. function parse_theme(data, name, opts) {
  22426. return parse_theme_xml(data, opts);
  22427. }
  22428. function parse_sst(data, name, opts) {
  22429. if(name.slice(-4)===".bin") return parse_sst_bin((data), opts);
  22430. return parse_sst_xml((data), opts);
  22431. }
  22432. function parse_cmnt(data, name, opts) {
  22433. if(name.slice(-4)===".bin") return parse_comments_bin((data), opts);
  22434. return parse_comments_xml((data), opts);
  22435. }
  22436. function parse_cc(data, name, opts) {
  22437. if(name.slice(-4)===".bin") return parse_cc_bin((data), name, opts);
  22438. return parse_cc_xml((data), name, opts);
  22439. }
  22440. function parse_xlink(data, rel, name, opts) {
  22441. if(name.slice(-4)===".bin") return parse_xlink_bin((data), rel, name, opts);
  22442. return parse_xlink_xml((data), rel, name, opts);
  22443. }
  22444. function write_wb(wb, name, opts) {
  22445. return (name.slice(-4)===".bin" ? write_wb_bin : write_wb_xml)(wb, opts);
  22446. }
  22447. function write_ws(data, name, opts, wb, rels) {
  22448. return (name.slice(-4)===".bin" ? write_ws_bin : write_ws_xml)(data, opts, wb, rels);
  22449. }
  22450. // eslint-disable-next-line no-unused-vars
  22451. function write_cs(data, name, opts, wb, rels) {
  22452. return (name.slice(-4)===".bin" ? write_cs_bin : write_cs_xml)(data, opts, wb, rels);
  22453. }
  22454. function write_sty(data, name, opts) {
  22455. return (name.slice(-4)===".bin" ? write_sty_bin : write_sty_xml)(data, opts);
  22456. }
  22457. function write_sst(data, name, opts) {
  22458. return (name.slice(-4)===".bin" ? write_sst_bin : write_sst_xml)(data, opts);
  22459. }
  22460. function write_cmnt(data, name, opts) {
  22461. return (name.slice(-4)===".bin" ? write_comments_bin : write_comments_xml)(data, opts);
  22462. }
  22463. /*
  22464. function write_cc(data, name:string, opts) {
  22465. return (name.slice(-4)===".bin" ? write_cc_bin : write_cc_xml)(data, opts);
  22466. }
  22467. */
  22468. var attregexg2=/([\w:]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:'))/g;
  22469. var attregex2=/([\w:]+)=((?:")(?:[^"]*)(?:")|(?:')(?:[^']*)(?:'))/;
  22470. function xlml_parsexmltag(tag, skip_root) {
  22471. var words = tag.split(/\s+/);
  22472. var z = ([]); if(!skip_root) z[0] = words[0];
  22473. if(words.length === 1) return z;
  22474. var m = tag.match(attregexg2), y, j, w, i;
  22475. if(m) for(i = 0; i != m.length; ++i) {
  22476. y = m[i].match(attregex2);
  22477. if((j=y[1].indexOf(":")) === -1) z[y[1]] = y[2].slice(1,y[2].length-1);
  22478. else {
  22479. if(y[1].slice(0,6) === "xmlns:") w = "xmlns"+y[1].slice(6);
  22480. else w = y[1].slice(j+1);
  22481. z[w] = y[2].slice(1,y[2].length-1);
  22482. }
  22483. }
  22484. return z;
  22485. }
  22486. function xlml_parsexmltagobj(tag) {
  22487. var words = tag.split(/\s+/);
  22488. var z = {};
  22489. if(words.length === 1) return z;
  22490. var m = tag.match(attregexg2), y, j, w, i;
  22491. if(m) for(i = 0; i != m.length; ++i) {
  22492. y = m[i].match(attregex2);
  22493. if((j=y[1].indexOf(":")) === -1) z[y[1]] = y[2].slice(1,y[2].length-1);
  22494. else {
  22495. if(y[1].slice(0,6) === "xmlns:") w = "xmlns"+y[1].slice(6);
  22496. else w = y[1].slice(j+1);
  22497. z[w] = y[2].slice(1,y[2].length-1);
  22498. }
  22499. }
  22500. return z;
  22501. }
  22502. // ----
  22503. function xlml_format(format, value) {
  22504. var fmt = XLMLFormatMap[format] || unescapexml(format);
  22505. if(fmt === "General") return SSF._general(value);
  22506. return SSF.format(fmt, value);
  22507. }
  22508. function xlml_set_custprop(Custprops, key, cp, val) {
  22509. var oval = val;
  22510. switch((cp[0].match(/dt:dt="([\w.]+)"/)||["",""])[1]) {
  22511. case "boolean": oval = parsexmlbool(val); break;
  22512. case "i2": case "int": oval = parseInt(val, 10); break;
  22513. case "r4": case "float": oval = parseFloat(val); break;
  22514. case "date": case "dateTime.tz": oval = parseDate(val); break;
  22515. case "i8": case "string": case "fixed": case "uuid": case "bin.base64": break;
  22516. default: throw new Error("bad custprop:" + cp[0]);
  22517. }
  22518. Custprops[unescapexml(key)] = oval;
  22519. }
  22520. function safe_format_xlml(cell, nf, o) {
  22521. if(cell.t === 'z') return;
  22522. if(!o || o.cellText !== false) try {
  22523. if(cell.t === 'e') { cell.w = cell.w || BErr[cell.v]; }
  22524. else if(nf === "General") {
  22525. if(cell.t === 'n') {
  22526. if((cell.v|0) === cell.v) cell.w = SSF._general_int(cell.v);
  22527. else cell.w = SSF._general_num(cell.v);
  22528. }
  22529. else cell.w = SSF._general(cell.v);
  22530. }
  22531. else cell.w = xlml_format(nf||"General", cell.v);
  22532. } catch(e) { if(o.WTF) throw e; }
  22533. try {
  22534. var z = XLMLFormatMap[nf]||nf||"General";
  22535. if(o.cellNF) cell.z = z;
  22536. if(o.cellDates && cell.t == 'n' && SSF.is_date(z)) {
  22537. var _d = SSF.parse_date_code(cell.v); if(_d) { cell.t = 'd'; cell.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
  22538. }
  22539. } catch(e) { if(o.WTF) throw e; }
  22540. }
  22541. function process_style_xlml(styles, stag, opts) {
  22542. if(opts.cellStyles) {
  22543. if(stag.Interior) {
  22544. var I = stag.Interior;
  22545. if(I.Pattern) I.patternType = XLMLPatternTypeMap[I.Pattern] || I.Pattern;
  22546. }
  22547. }
  22548. styles[stag.ID] = stag;
  22549. }
  22550. /* TODO: there must exist some form of OSP-blessed spec */
  22551. function parse_xlml_data(xml, ss, data, cell, base, styles, csty, row, arrayf, o) {
  22552. var nf = "General", sid = cell.StyleID, S = {}; o = o || {};
  22553. var interiors = [];
  22554. var i = 0;
  22555. if(sid === undefined && row) sid = row.StyleID;
  22556. if(sid === undefined && csty) sid = csty.StyleID;
  22557. while(styles[sid] !== undefined) {
  22558. if(styles[sid].nf) nf = styles[sid].nf;
  22559. if(styles[sid].Interior) interiors.push(styles[sid].Interior);
  22560. if(!styles[sid].Parent) break;
  22561. sid = styles[sid].Parent;
  22562. }
  22563. switch(data.Type) {
  22564. case 'Boolean':
  22565. cell.t = 'b';
  22566. cell.v = parsexmlbool(xml);
  22567. break;
  22568. case 'String':
  22569. cell.t = 's'; cell.r = xlml_fixstr(unescapexml(xml));
  22570. cell.v = (xml.indexOf("<") > -1 ? unescapexml(ss||xml).replace(/<.*?>/g, "") : cell.r); // todo: BR etc
  22571. break;
  22572. case 'DateTime':
  22573. if(xml.slice(-1) != "Z") xml += "Z";
  22574. cell.v = (parseDate(xml) - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
  22575. if(cell.v !== cell.v) cell.v = unescapexml(xml);
  22576. else if(cell.v<60) cell.v = cell.v -1;
  22577. if(!nf || nf == "General") nf = "yyyy-mm-dd";
  22578. /* falls through */
  22579. case 'Number':
  22580. if(cell.v === undefined) cell.v=+xml;
  22581. if(!cell.t) cell.t = 'n';
  22582. break;
  22583. case 'Error': cell.t = 'e'; cell.v = RBErr[xml]; if(o.cellText !== false) cell.w = xml; break;
  22584. default:
  22585. if(xml == "" && ss == "") { cell.t = 'z'; }
  22586. else { cell.t = 's'; cell.v = xlml_fixstr(ss||xml); }
  22587. break;
  22588. }
  22589. safe_format_xlml(cell, nf, o);
  22590. if(o.cellFormula !== false) {
  22591. if(cell.Formula) {
  22592. var fstr = unescapexml(cell.Formula);
  22593. /* strictly speaking, the leading = is required but some writers omit */
  22594. if(fstr.charCodeAt(0) == 61 /* = */) fstr = fstr.slice(1);
  22595. cell.f = rc_to_a1(fstr, base);
  22596. delete cell.Formula;
  22597. if(cell.ArrayRange == "RC") cell.F = rc_to_a1("RC:RC", base);
  22598. else if(cell.ArrayRange) {
  22599. cell.F = rc_to_a1(cell.ArrayRange, base);
  22600. arrayf.push([safe_decode_range(cell.F), cell.F]);
  22601. }
  22602. } else {
  22603. for(i = 0; i < arrayf.length; ++i)
  22604. if(base.r >= arrayf[i][0].s.r && base.r <= arrayf[i][0].e.r)
  22605. if(base.c >= arrayf[i][0].s.c && base.c <= arrayf[i][0].e.c)
  22606. cell.F = arrayf[i][1];
  22607. }
  22608. }
  22609. if(o.cellStyles) {
  22610. interiors.forEach(function(x) {
  22611. if(!S.patternType && x.patternType) S.patternType = x.patternType;
  22612. });
  22613. cell.s = S;
  22614. }
  22615. if(cell.StyleID !== undefined) cell.ixfe = cell.StyleID;
  22616. }
  22617. function xlml_clean_comment(comment) {
  22618. comment.t = comment.v || "";
  22619. comment.t = comment.t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");
  22620. comment.v = comment.w = comment.ixfe = undefined;
  22621. }
  22622. function xlml_normalize(d) {
  22623. if(has_buf && Buffer.isBuffer(d)) return d.toString('utf8');
  22624. if(typeof d === 'string') return d;
  22625. /* duktape */
  22626. if(typeof Uint8Array !== 'undefined' && d instanceof Uint8Array) return utf8read(a2s(ab2a(d)));
  22627. throw new Error("Bad input format: expected Buffer or string");
  22628. }
  22629. /* TODO: Everything */
  22630. /* UOS uses CJK in tags */
  22631. var xlmlregex = /<(\/?)([^\s?><!\/:]*:|)([^\s?<>:\/]+)(?:[\s?:\/][^>]*)?>/mg;
  22632. //var xlmlregex = /<(\/?)([a-z0-9]*:|)(\w+)[^>]*>/mg;
  22633. function parse_xlml_xml(d, _opts) {
  22634. var opts = _opts || {};
  22635. make_ssf(SSF);
  22636. var str = debom(xlml_normalize(d));
  22637. if(opts.type == 'binary' || opts.type == 'array' || opts.type == 'base64') {
  22638. if(typeof cptable !== 'undefined') str = cptable.utils.decode(65001, char_codes(str));
  22639. else str = utf8read(str);
  22640. }
  22641. var opening = str.slice(0, 1024).toLowerCase(), ishtml = false;
  22642. if(opening.indexOf("<?xml") == -1) ["html", "table", "head", "meta", "script", "style", "div"].forEach(function(tag) { if(opening.indexOf("<" + tag) >= 0) ishtml = true; });
  22643. if(ishtml) return HTML_.to_workbook(str, opts);
  22644. var Rn;
  22645. var state = [], tmp;
  22646. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  22647. var sheets = {}, sheetnames = [], cursheet = (opts.dense ? [] : {}), sheetname = "";
  22648. var table = {}, cell = ({}), row = {};// eslint-disable-line no-unused-vars
  22649. var dtag = xlml_parsexmltag('<Data ss:Type="String">'), didx = 0;
  22650. var c = 0, r = 0;
  22651. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  22652. var styles = {}, stag = {};
  22653. var ss = "", fidx = 0;
  22654. var merges = [];
  22655. var Props = {}, Custprops = {}, pidx = 0, cp = [];
  22656. var comments = [], comment = ({});
  22657. var cstys = [], csty, seencol = false;
  22658. var arrayf = [];
  22659. var rowinfo = [], rowobj = {}, cc = 0, rr = 0;
  22660. var Workbook = ({ Sheets:[], WBProps:{date1904:false} }), wsprops = {};
  22661. xlmlregex.lastIndex = 0;
  22662. str = str.replace(/<!--([\s\S]*?)-->/mg,"");
  22663. var raw_Rn3 = "";
  22664. while((Rn = xlmlregex.exec(str))) switch((Rn[3] = (raw_Rn3 = Rn[3]).toLowerCase())) {
  22665. case 'data' /*case 'Data'*/:
  22666. if(raw_Rn3 == "data") {
  22667. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  22668. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  22669. break;
  22670. }
  22671. if(state[state.length-1][1]) break;
  22672. if(Rn[1]==='/') parse_xlml_data(str.slice(didx, Rn.index), ss, dtag, state[state.length-1][0]==/*"Comment"*/"comment"?comment:cell, {c:c,r:r}, styles, cstys[c], row, arrayf, opts);
  22673. else { ss = ""; dtag = xlml_parsexmltag(Rn[0]); didx = Rn.index + Rn[0].length; }
  22674. break;
  22675. case 'cell' /*case 'Cell'*/:
  22676. if(Rn[1]==='/'){
  22677. if(comments.length > 0) cell.c = comments;
  22678. if((!opts.sheetRows || opts.sheetRows > r) && cell.v !== undefined) {
  22679. if(opts.dense) {
  22680. if(!cursheet[r]) cursheet[r] = [];
  22681. cursheet[r][c] = cell;
  22682. } else cursheet[encode_col(c) + encode_row(r)] = cell;
  22683. }
  22684. if(cell.HRef) {
  22685. cell.l = ({Target:cell.HRef});
  22686. if(cell.HRefScreenTip) cell.l.Tooltip = cell.HRefScreenTip;
  22687. delete cell.HRef; delete cell.HRefScreenTip;
  22688. }
  22689. if(cell.MergeAcross || cell.MergeDown) {
  22690. cc = c + (parseInt(cell.MergeAcross,10)|0);
  22691. rr = r + (parseInt(cell.MergeDown,10)|0);
  22692. merges.push({s:{c:c,r:r},e:{c:cc,r:rr}});
  22693. }
  22694. if(!opts.sheetStubs) { if(cell.MergeAcross) c = cc + 1; else ++c; }
  22695. else if(cell.MergeAcross || cell.MergeDown) {
  22696. for(var cma = c; cma <= cc; ++cma) {
  22697. for(var cmd = r; cmd <= rr; ++cmd) {
  22698. if(cma > c || cmd > r) {
  22699. if(opts.dense) {
  22700. if(!cursheet[cmd]) cursheet[cmd] = [];
  22701. cursheet[cmd][cma] = {t:'z'};
  22702. } else cursheet[encode_col(cma) + encode_row(cmd)] = {t:'z'};
  22703. }
  22704. }
  22705. }
  22706. c = cc + 1;
  22707. }
  22708. else ++c;
  22709. } else {
  22710. cell = xlml_parsexmltagobj(Rn[0]);
  22711. if(cell.Index) c = +cell.Index - 1;
  22712. if(c < refguess.s.c) refguess.s.c = c;
  22713. if(c > refguess.e.c) refguess.e.c = c;
  22714. if(Rn[0].slice(-2) === "/>") ++c;
  22715. comments = [];
  22716. }
  22717. break;
  22718. case 'row' /*case 'Row'*/:
  22719. if(Rn[1]==='/' || Rn[0].slice(-2) === "/>") {
  22720. if(r < refguess.s.r) refguess.s.r = r;
  22721. if(r > refguess.e.r) refguess.e.r = r;
  22722. if(Rn[0].slice(-2) === "/>") {
  22723. row = xlml_parsexmltag(Rn[0]);
  22724. if(row.Index) r = +row.Index - 1;
  22725. }
  22726. c = 0; ++r;
  22727. } else {
  22728. row = xlml_parsexmltag(Rn[0]);
  22729. if(row.Index) r = +row.Index - 1;
  22730. rowobj = {};
  22731. if(row.AutoFitHeight == "0" || row.Height) {
  22732. rowobj.hpx = parseInt(row.Height, 10); rowobj.hpt = px2pt(rowobj.hpx);
  22733. rowinfo[r] = rowobj;
  22734. }
  22735. if(row.Hidden == "1") { rowobj.hidden = true; rowinfo[r] = rowobj; }
  22736. }
  22737. break;
  22738. case 'worksheet' /*case 'Worksheet'*/: /* TODO: read range from FullRows/FullColumns */
  22739. if(Rn[1]==='/'){
  22740. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  22741. sheetnames.push(sheetname);
  22742. if(refguess.s.r <= refguess.e.r && refguess.s.c <= refguess.e.c) {
  22743. cursheet["!ref"] = encode_range(refguess);
  22744. if(opts.sheetRows && opts.sheetRows <= refguess.e.r) {
  22745. cursheet["!fullref"] = cursheet["!ref"];
  22746. refguess.e.r = opts.sheetRows - 1;
  22747. cursheet["!ref"] = encode_range(refguess);
  22748. }
  22749. }
  22750. if(merges.length) cursheet["!merges"] = merges;
  22751. if(cstys.length > 0) cursheet["!cols"] = cstys;
  22752. if(rowinfo.length > 0) cursheet["!rows"] = rowinfo;
  22753. sheets[sheetname] = cursheet;
  22754. } else {
  22755. refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  22756. r = c = 0;
  22757. state.push([Rn[3], false]);
  22758. tmp = xlml_parsexmltag(Rn[0]);
  22759. sheetname = unescapexml(tmp.Name);
  22760. cursheet = (opts.dense ? [] : {});
  22761. merges = [];
  22762. arrayf = [];
  22763. rowinfo = [];
  22764. wsprops = {name:sheetname, Hidden:0};
  22765. Workbook.Sheets.push(wsprops);
  22766. }
  22767. break;
  22768. case 'table' /*case 'Table'*/:
  22769. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  22770. else if(Rn[0].slice(-2) == "/>") break;
  22771. else {
  22772. table = xlml_parsexmltag(Rn[0]);
  22773. state.push([Rn[3], false]);
  22774. cstys = []; seencol = false;
  22775. }
  22776. break;
  22777. case 'style' /*case 'Style'*/:
  22778. if(Rn[1]==='/') process_style_xlml(styles, stag, opts);
  22779. else stag = xlml_parsexmltag(Rn[0]);
  22780. break;
  22781. case 'numberformat' /*case 'NumberFormat'*/:
  22782. stag.nf = unescapexml(xlml_parsexmltag(Rn[0]).Format || "General");
  22783. if(XLMLFormatMap[stag.nf]) stag.nf = XLMLFormatMap[stag.nf];
  22784. for(var ssfidx = 0; ssfidx != 0x188; ++ssfidx) if(SSF._table[ssfidx] == stag.nf) break;
  22785. if(ssfidx == 0x188) for(ssfidx = 0x39; ssfidx != 0x188; ++ssfidx) if(SSF._table[ssfidx] == null) { SSF.load(stag.nf, ssfidx); break; }
  22786. break;
  22787. case 'column' /*case 'Column'*/:
  22788. if(state[state.length-1][0] !== /*'Table'*/'table') break;
  22789. csty = xlml_parsexmltag(Rn[0]);
  22790. if(csty.Hidden) { csty.hidden = true; delete csty.Hidden; }
  22791. if(csty.Width) csty.wpx = parseInt(csty.Width, 10);
  22792. if(!seencol && csty.wpx > 10) {
  22793. seencol = true; MDW = DEF_MDW; //find_mdw_wpx(csty.wpx);
  22794. for(var _col = 0; _col < cstys.length; ++_col) if(cstys[_col]) process_col(cstys[_col]);
  22795. }
  22796. if(seencol) process_col(csty);
  22797. cstys[(csty.Index-1||cstys.length)] = csty;
  22798. for(var i = 0; i < +csty.Span; ++i) cstys[cstys.length] = dup(csty);
  22799. break;
  22800. case 'namedrange' /*case 'NamedRange'*/:
  22801. if(Rn[1]==='/') break;
  22802. if(!Workbook.Names) Workbook.Names = [];
  22803. var _NamedRange = parsexmltag(Rn[0]);
  22804. var _DefinedName = ({
  22805. Name: _NamedRange.Name,
  22806. Ref: rc_to_a1(_NamedRange.RefersTo.slice(1), {r:0, c:0})
  22807. });
  22808. if(Workbook.Sheets.length>0) _DefinedName.Sheet=Workbook.Sheets.length-1;
  22809. Workbook.Names.push(_DefinedName);
  22810. break;
  22811. case 'namedcell' /*case 'NamedCell'*/: break;
  22812. case 'b' /*case 'B'*/: break;
  22813. case 'i' /*case 'I'*/: break;
  22814. case 'u' /*case 'U'*/: break;
  22815. case 's' /*case 'S'*/: break;
  22816. case 'em' /*case 'EM'*/: break;
  22817. case 'h2' /*case 'H2'*/: break;
  22818. case 'h3' /*case 'H3'*/: break;
  22819. case 'sub' /*case 'Sub'*/: break;
  22820. case 'sup' /*case 'Sup'*/: break;
  22821. case 'span' /*case 'Span'*/: break;
  22822. case 'alignment' /*case 'Alignment'*/:
  22823. break;
  22824. case 'borders' /*case 'Borders'*/: break;
  22825. case 'border' /*case 'Border'*/: break;
  22826. case 'font' /*case 'Font'*/:
  22827. if(Rn[0].slice(-2) === "/>") break;
  22828. else if(Rn[1]==="/") ss += str.slice(fidx, Rn.index);
  22829. else fidx = Rn.index + Rn[0].length;
  22830. break;
  22831. case 'interior' /*case 'Interior'*/:
  22832. if(!opts.cellStyles) break;
  22833. stag.Interior = xlml_parsexmltag(Rn[0]);
  22834. break;
  22835. case 'protection' /*case 'Protection'*/: break;
  22836. case 'author' /*case 'Author'*/:
  22837. case 'title' /*case 'Title'*/:
  22838. case 'description' /*case 'Description'*/:
  22839. case 'created' /*case 'Created'*/:
  22840. case 'keywords' /*case 'Keywords'*/:
  22841. case 'subject' /*case 'Subject'*/:
  22842. case 'category' /*case 'Category'*/:
  22843. case 'company' /*case 'Company'*/:
  22844. case 'lastauthor' /*case 'LastAuthor'*/:
  22845. case 'lastsaved' /*case 'LastSaved'*/:
  22846. case 'lastprinted' /*case 'LastPrinted'*/:
  22847. case 'version' /*case 'Version'*/:
  22848. case 'revision' /*case 'Revision'*/:
  22849. case 'totaltime' /*case 'TotalTime'*/:
  22850. case 'hyperlinkbase' /*case 'HyperlinkBase'*/:
  22851. case 'manager' /*case 'Manager'*/:
  22852. case 'contentstatus' /*case 'ContentStatus'*/:
  22853. case 'identifier' /*case 'Identifier'*/:
  22854. case 'language' /*case 'Language'*/:
  22855. case 'appname' /*case 'AppName'*/:
  22856. if(Rn[0].slice(-2) === "/>") break;
  22857. else if(Rn[1]==="/") xlml_set_prop(Props, raw_Rn3, str.slice(pidx, Rn.index));
  22858. else pidx = Rn.index + Rn[0].length;
  22859. break;
  22860. case 'paragraphs' /*case 'Paragraphs'*/: break;
  22861. case 'styles' /*case 'Styles'*/:
  22862. case 'workbook' /*case 'Workbook'*/:
  22863. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  22864. else state.push([Rn[3], false]);
  22865. break;
  22866. case 'comment' /*case 'Comment'*/:
  22867. if(Rn[1]==='/'){
  22868. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  22869. xlml_clean_comment(comment);
  22870. comments.push(comment);
  22871. } else {
  22872. state.push([Rn[3], false]);
  22873. tmp = xlml_parsexmltag(Rn[0]);
  22874. comment = ({a:tmp.Author});
  22875. }
  22876. break;
  22877. case 'autofilter' /*case 'AutoFilter'*/:
  22878. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  22879. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  22880. var AutoFilter = xlml_parsexmltag(Rn[0]);
  22881. cursheet['!autofilter'] = { ref:rc_to_a1(AutoFilter.Range).replace(/\$/g,"") };
  22882. state.push([Rn[3], true]);
  22883. }
  22884. break;
  22885. case 'name' /*case 'Name'*/: break;
  22886. case 'datavalidation' /*case 'DataValidation'*/:
  22887. if(Rn[1]==='/'){
  22888. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  22889. } else {
  22890. if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  22891. }
  22892. break;
  22893. case 'pixelsperinch' /*case 'PixelsPerInch'*/:
  22894. break;
  22895. case 'componentoptions' /*case 'ComponentOptions'*/:
  22896. case 'documentproperties' /*case 'DocumentProperties'*/:
  22897. case 'customdocumentproperties' /*case 'CustomDocumentProperties'*/:
  22898. case 'officedocumentsettings' /*case 'OfficeDocumentSettings'*/:
  22899. case 'pivottable' /*case 'PivotTable'*/:
  22900. case 'pivotcache' /*case 'PivotCache'*/:
  22901. case 'names' /*case 'Names'*/:
  22902. case 'mapinfo' /*case 'MapInfo'*/:
  22903. case 'pagebreaks' /*case 'PageBreaks'*/:
  22904. case 'querytable' /*case 'QueryTable'*/:
  22905. case 'sorting' /*case 'Sorting'*/:
  22906. case 'schema' /*case 'Schema'*/: //case 'data' /*case 'data'*/:
  22907. case 'conditionalformatting' /*case 'ConditionalFormatting'*/:
  22908. case 'smarttagtype' /*case 'SmartTagType'*/:
  22909. case 'smarttags' /*case 'SmartTags'*/:
  22910. case 'excelworkbook' /*case 'ExcelWorkbook'*/:
  22911. case 'workbookoptions' /*case 'WorkbookOptions'*/:
  22912. case 'worksheetoptions' /*case 'WorksheetOptions'*/:
  22913. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  22914. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  22915. break;
  22916. default:
  22917. /* FODS file root is <office:document> */
  22918. if(state.length == 0 && Rn[3] == "document") return parse_fods(str, opts);
  22919. /* UOS file root is <uof:UOF> */
  22920. if(state.length == 0 && Rn[3] == "uof"/*"UOF"*/) return parse_fods(str, opts);
  22921. var seen = true;
  22922. switch(state[state.length-1][0]) {
  22923. /* OfficeDocumentSettings */
  22924. case 'officedocumentsettings' /*case 'OfficeDocumentSettings'*/: switch(Rn[3]) {
  22925. case 'allowpng' /*case 'AllowPNG'*/: break;
  22926. case 'removepersonalinformation' /*case 'RemovePersonalInformation'*/: break;
  22927. case 'downloadcomponents' /*case 'DownloadComponents'*/: break;
  22928. case 'locationofcomponents' /*case 'LocationOfComponents'*/: break;
  22929. case 'colors' /*case 'Colors'*/: break;
  22930. case 'color' /*case 'Color'*/: break;
  22931. case 'index' /*case 'Index'*/: break;
  22932. case 'rgb' /*case 'RGB'*/: break;
  22933. case 'targetscreensize' /*case 'TargetScreenSize'*/: break;
  22934. case 'readonlyrecommended' /*case 'ReadOnlyRecommended'*/: break;
  22935. default: seen = false;
  22936. } break;
  22937. /* ComponentOptions */
  22938. case 'componentoptions' /*case 'ComponentOptions'*/: switch(Rn[3]) {
  22939. case 'toolbar' /*case 'Toolbar'*/: break;
  22940. case 'hideofficelogo' /*case 'HideOfficeLogo'*/: break;
  22941. case 'spreadsheetautofit' /*case 'SpreadsheetAutoFit'*/: break;
  22942. case 'label' /*case 'Label'*/: break;
  22943. case 'caption' /*case 'Caption'*/: break;
  22944. case 'maxheight' /*case 'MaxHeight'*/: break;
  22945. case 'maxwidth' /*case 'MaxWidth'*/: break;
  22946. case 'nextsheetnumber' /*case 'NextSheetNumber'*/: break;
  22947. default: seen = false;
  22948. } break;
  22949. /* ExcelWorkbook */
  22950. case 'excelworkbook' /*case 'ExcelWorkbook'*/: switch(Rn[3]) {
  22951. case 'date1904' /*case 'Date1904'*/:
  22952. Workbook.WBProps.date1904 = true;
  22953. break;
  22954. case 'windowheight' /*case 'WindowHeight'*/: break;
  22955. case 'windowwidth' /*case 'WindowWidth'*/: break;
  22956. case 'windowtopx' /*case 'WindowTopX'*/: break;
  22957. case 'windowtopy' /*case 'WindowTopY'*/: break;
  22958. case 'tabratio' /*case 'TabRatio'*/: break;
  22959. case 'protectstructure' /*case 'ProtectStructure'*/: break;
  22960. case 'protectwindow' /*case 'ProtectWindow'*/: break;
  22961. case 'protectwindows' /*case 'ProtectWindows'*/: break;
  22962. case 'activesheet' /*case 'ActiveSheet'*/: break;
  22963. case 'displayinknotes' /*case 'DisplayInkNotes'*/: break;
  22964. case 'firstvisiblesheet' /*case 'FirstVisibleSheet'*/: break;
  22965. case 'supbook' /*case 'SupBook'*/: break;
  22966. case 'sheetname' /*case 'SheetName'*/: break;
  22967. case 'sheetindex' /*case 'SheetIndex'*/: break;
  22968. case 'sheetindexfirst' /*case 'SheetIndexFirst'*/: break;
  22969. case 'sheetindexlast' /*case 'SheetIndexLast'*/: break;
  22970. case 'dll' /*case 'Dll'*/: break;
  22971. case 'acceptlabelsinformulas' /*case 'AcceptLabelsInFormulas'*/: break;
  22972. case 'donotsavelinkvalues' /*case 'DoNotSaveLinkValues'*/: break;
  22973. case 'iteration' /*case 'Iteration'*/: break;
  22974. case 'maxiterations' /*case 'MaxIterations'*/: break;
  22975. case 'maxchange' /*case 'MaxChange'*/: break;
  22976. case 'path' /*case 'Path'*/: break;
  22977. case 'xct' /*case 'Xct'*/: break;
  22978. case 'count' /*case 'Count'*/: break;
  22979. case 'selectedsheets' /*case 'SelectedSheets'*/: break;
  22980. case 'calculation' /*case 'Calculation'*/: break;
  22981. case 'uncalced' /*case 'Uncalced'*/: break;
  22982. case 'startupprompt' /*case 'StartupPrompt'*/: break;
  22983. case 'crn' /*case 'Crn'*/: break;
  22984. case 'externname' /*case 'ExternName'*/: break;
  22985. case 'formula' /*case 'Formula'*/: break;
  22986. case 'colfirst' /*case 'ColFirst'*/: break;
  22987. case 'collast' /*case 'ColLast'*/: break;
  22988. case 'wantadvise' /*case 'WantAdvise'*/: break;
  22989. case 'boolean' /*case 'Boolean'*/: break;
  22990. case 'error' /*case 'Error'*/: break;
  22991. case 'text' /*case 'Text'*/: break;
  22992. case 'ole' /*case 'OLE'*/: break;
  22993. case 'noautorecover' /*case 'NoAutoRecover'*/: break;
  22994. case 'publishobjects' /*case 'PublishObjects'*/: break;
  22995. case 'donotcalculatebeforesave' /*case 'DoNotCalculateBeforeSave'*/: break;
  22996. case 'number' /*case 'Number'*/: break;
  22997. case 'refmoder1c1' /*case 'RefModeR1C1'*/: break;
  22998. case 'embedsavesmarttags' /*case 'EmbedSaveSmartTags'*/: break;
  22999. default: seen = false;
  23000. } break;
  23001. /* WorkbookOptions */
  23002. case 'workbookoptions' /*case 'WorkbookOptions'*/: switch(Rn[3]) {
  23003. case 'owcversion' /*case 'OWCVersion'*/: break;
  23004. case 'height' /*case 'Height'*/: break;
  23005. case 'width' /*case 'Width'*/: break;
  23006. default: seen = false;
  23007. } break;
  23008. /* WorksheetOptions */
  23009. case 'worksheetoptions' /*case 'WorksheetOptions'*/: switch(Rn[3]) {
  23010. case 'visible' /*case 'Visible'*/:
  23011. if(Rn[0].slice(-2) === "/>"){/* empty */}
  23012. else if(Rn[1]==="/") switch(str.slice(pidx, Rn.index)) {
  23013. case "SheetHidden": wsprops.Hidden = 1; break;
  23014. case "SheetVeryHidden": wsprops.Hidden = 2; break;
  23015. }
  23016. else pidx = Rn.index + Rn[0].length;
  23017. break;
  23018. case 'header' /*case 'Header'*/:
  23019. if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
  23020. cursheet['!margins'].header = parsexmltag(Rn[0]).Margin;
  23021. break;
  23022. case 'footer' /*case 'Footer'*/:
  23023. if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
  23024. cursheet['!margins'].footer = parsexmltag(Rn[0]).Margin;
  23025. break;
  23026. case 'pagemargins' /*case 'PageMargins'*/:
  23027. var pagemargins = parsexmltag(Rn[0]);
  23028. if(!cursheet['!margins']) default_margins(cursheet['!margins']={},'xlml');
  23029. if(pagemargins.Top) cursheet['!margins'].top = pagemargins.Top;
  23030. if(pagemargins.Left) cursheet['!margins'].left = pagemargins.Left;
  23031. if(pagemargins.Right) cursheet['!margins'].right = pagemargins.Right;
  23032. if(pagemargins.Bottom) cursheet['!margins'].bottom = pagemargins.Bottom;
  23033. break;
  23034. case 'displayrighttoleft' /*case 'DisplayRightToLeft'*/:
  23035. if(!Workbook.Views) Workbook.Views = [];
  23036. if(!Workbook.Views[0]) Workbook.Views[0] = {};
  23037. Workbook.Views[0].RTL = true;
  23038. break;
  23039. case 'freezepanes' /*case 'FreezePanes'*/: break;
  23040. case 'frozennosplit' /*case 'FrozenNoSplit'*/: break;
  23041. case 'splithorizontal' /*case 'SplitHorizontal'*/:
  23042. case 'splitvertical' /*case 'SplitVertical'*/:
  23043. break;
  23044. case 'donotdisplaygridlines' /*case 'DoNotDisplayGridlines'*/:
  23045. break;
  23046. case 'activerow' /*case 'ActiveRow'*/: break;
  23047. case 'activecol' /*case 'ActiveCol'*/: break;
  23048. case 'toprowbottompane' /*case 'TopRowBottomPane'*/: break;
  23049. case 'leftcolumnrightpane' /*case 'LeftColumnRightPane'*/: break;
  23050. case 'unsynced' /*case 'Unsynced'*/: break;
  23051. case 'print' /*case 'Print'*/: break;
  23052. case 'panes' /*case 'Panes'*/: break;
  23053. case 'scale' /*case 'Scale'*/: break;
  23054. case 'pane' /*case 'Pane'*/: break;
  23055. case 'number' /*case 'Number'*/: break;
  23056. case 'layout' /*case 'Layout'*/: break;
  23057. case 'pagesetup' /*case 'PageSetup'*/: break;
  23058. case 'selected' /*case 'Selected'*/: break;
  23059. case 'protectobjects' /*case 'ProtectObjects'*/: break;
  23060. case 'enableselection' /*case 'EnableSelection'*/: break;
  23061. case 'protectscenarios' /*case 'ProtectScenarios'*/: break;
  23062. case 'validprinterinfo' /*case 'ValidPrinterInfo'*/: break;
  23063. case 'horizontalresolution' /*case 'HorizontalResolution'*/: break;
  23064. case 'verticalresolution' /*case 'VerticalResolution'*/: break;
  23065. case 'numberofcopies' /*case 'NumberofCopies'*/: break;
  23066. case 'activepane' /*case 'ActivePane'*/: break;
  23067. case 'toprowvisible' /*case 'TopRowVisible'*/: break;
  23068. case 'leftcolumnvisible' /*case 'LeftColumnVisible'*/: break;
  23069. case 'fittopage' /*case 'FitToPage'*/: break;
  23070. case 'rangeselection' /*case 'RangeSelection'*/: break;
  23071. case 'papersizeindex' /*case 'PaperSizeIndex'*/: break;
  23072. case 'pagelayoutzoom' /*case 'PageLayoutZoom'*/: break;
  23073. case 'pagebreakzoom' /*case 'PageBreakZoom'*/: break;
  23074. case 'filteron' /*case 'FilterOn'*/: break;
  23075. case 'fitwidth' /*case 'FitWidth'*/: break;
  23076. case 'fitheight' /*case 'FitHeight'*/: break;
  23077. case 'commentslayout' /*case 'CommentsLayout'*/: break;
  23078. case 'zoom' /*case 'Zoom'*/: break;
  23079. case 'lefttoright' /*case 'LeftToRight'*/: break;
  23080. case 'gridlines' /*case 'Gridlines'*/: break;
  23081. case 'allowsort' /*case 'AllowSort'*/: break;
  23082. case 'allowfilter' /*case 'AllowFilter'*/: break;
  23083. case 'allowinsertrows' /*case 'AllowInsertRows'*/: break;
  23084. case 'allowdeleterows' /*case 'AllowDeleteRows'*/: break;
  23085. case 'allowinsertcols' /*case 'AllowInsertCols'*/: break;
  23086. case 'allowdeletecols' /*case 'AllowDeleteCols'*/: break;
  23087. case 'allowinserthyperlinks' /*case 'AllowInsertHyperlinks'*/: break;
  23088. case 'allowformatcells' /*case 'AllowFormatCells'*/: break;
  23089. case 'allowsizecols' /*case 'AllowSizeCols'*/: break;
  23090. case 'allowsizerows' /*case 'AllowSizeRows'*/: break;
  23091. case 'nosummaryrowsbelowdetail' /*case 'NoSummaryRowsBelowDetail'*/: break;
  23092. case 'tabcolorindex' /*case 'TabColorIndex'*/: break;
  23093. case 'donotdisplayheadings' /*case 'DoNotDisplayHeadings'*/: break;
  23094. case 'showpagelayoutzoom' /*case 'ShowPageLayoutZoom'*/: break;
  23095. case 'nosummarycolumnsrightdetail' /*case 'NoSummaryColumnsRightDetail'*/: break;
  23096. case 'blackandwhite' /*case 'BlackAndWhite'*/: break;
  23097. case 'donotdisplayzeros' /*case 'DoNotDisplayZeros'*/: break;
  23098. case 'displaypagebreak' /*case 'DisplayPageBreak'*/: break;
  23099. case 'rowcolheadings' /*case 'RowColHeadings'*/: break;
  23100. case 'donotdisplayoutline' /*case 'DoNotDisplayOutline'*/: break;
  23101. case 'noorientation' /*case 'NoOrientation'*/: break;
  23102. case 'allowusepivottables' /*case 'AllowUsePivotTables'*/: break;
  23103. case 'zeroheight' /*case 'ZeroHeight'*/: break;
  23104. case 'viewablerange' /*case 'ViewableRange'*/: break;
  23105. case 'selection' /*case 'Selection'*/: break;
  23106. case 'protectcontents' /*case 'ProtectContents'*/: break;
  23107. default: seen = false;
  23108. } break;
  23109. /* PivotTable */
  23110. case 'pivottable' /*case 'PivotTable'*/: case 'pivotcache' /*case 'PivotCache'*/: switch(Rn[3]) {
  23111. case 'immediateitemsondrop' /*case 'ImmediateItemsOnDrop'*/: break;
  23112. case 'showpagemultipleitemlabel' /*case 'ShowPageMultipleItemLabel'*/: break;
  23113. case 'compactrowindent' /*case 'CompactRowIndent'*/: break;
  23114. case 'location' /*case 'Location'*/: break;
  23115. case 'pivotfield' /*case 'PivotField'*/: break;
  23116. case 'orientation' /*case 'Orientation'*/: break;
  23117. case 'layoutform' /*case 'LayoutForm'*/: break;
  23118. case 'layoutsubtotallocation' /*case 'LayoutSubtotalLocation'*/: break;
  23119. case 'layoutcompactrow' /*case 'LayoutCompactRow'*/: break;
  23120. case 'position' /*case 'Position'*/: break;
  23121. case 'pivotitem' /*case 'PivotItem'*/: break;
  23122. case 'datatype' /*case 'DataType'*/: break;
  23123. case 'datafield' /*case 'DataField'*/: break;
  23124. case 'sourcename' /*case 'SourceName'*/: break;
  23125. case 'parentfield' /*case 'ParentField'*/: break;
  23126. case 'ptlineitems' /*case 'PTLineItems'*/: break;
  23127. case 'ptlineitem' /*case 'PTLineItem'*/: break;
  23128. case 'countofsameitems' /*case 'CountOfSameItems'*/: break;
  23129. case 'item' /*case 'Item'*/: break;
  23130. case 'itemtype' /*case 'ItemType'*/: break;
  23131. case 'ptsource' /*case 'PTSource'*/: break;
  23132. case 'cacheindex' /*case 'CacheIndex'*/: break;
  23133. case 'consolidationreference' /*case 'ConsolidationReference'*/: break;
  23134. case 'filename' /*case 'FileName'*/: break;
  23135. case 'reference' /*case 'Reference'*/: break;
  23136. case 'nocolumngrand' /*case 'NoColumnGrand'*/: break;
  23137. case 'norowgrand' /*case 'NoRowGrand'*/: break;
  23138. case 'blanklineafteritems' /*case 'BlankLineAfterItems'*/: break;
  23139. case 'hidden' /*case 'Hidden'*/: break;
  23140. case 'subtotal' /*case 'Subtotal'*/: break;
  23141. case 'basefield' /*case 'BaseField'*/: break;
  23142. case 'mapchilditems' /*case 'MapChildItems'*/: break;
  23143. case 'function' /*case 'Function'*/: break;
  23144. case 'refreshonfileopen' /*case 'RefreshOnFileOpen'*/: break;
  23145. case 'printsettitles' /*case 'PrintSetTitles'*/: break;
  23146. case 'mergelabels' /*case 'MergeLabels'*/: break;
  23147. case 'defaultversion' /*case 'DefaultVersion'*/: break;
  23148. case 'refreshname' /*case 'RefreshName'*/: break;
  23149. case 'refreshdate' /*case 'RefreshDate'*/: break;
  23150. case 'refreshdatecopy' /*case 'RefreshDateCopy'*/: break;
  23151. case 'versionlastrefresh' /*case 'VersionLastRefresh'*/: break;
  23152. case 'versionlastupdate' /*case 'VersionLastUpdate'*/: break;
  23153. case 'versionupdateablemin' /*case 'VersionUpdateableMin'*/: break;
  23154. case 'versionrefreshablemin' /*case 'VersionRefreshableMin'*/: break;
  23155. case 'calculation' /*case 'Calculation'*/: break;
  23156. default: seen = false;
  23157. } break;
  23158. /* PageBreaks */
  23159. case 'pagebreaks' /*case 'PageBreaks'*/: switch(Rn[3]) {
  23160. case 'colbreaks' /*case 'ColBreaks'*/: break;
  23161. case 'colbreak' /*case 'ColBreak'*/: break;
  23162. case 'rowbreaks' /*case 'RowBreaks'*/: break;
  23163. case 'rowbreak' /*case 'RowBreak'*/: break;
  23164. case 'colstart' /*case 'ColStart'*/: break;
  23165. case 'colend' /*case 'ColEnd'*/: break;
  23166. case 'rowend' /*case 'RowEnd'*/: break;
  23167. default: seen = false;
  23168. } break;
  23169. /* AutoFilter */
  23170. case 'autofilter' /*case 'AutoFilter'*/: switch(Rn[3]) {
  23171. case 'autofiltercolumn' /*case 'AutoFilterColumn'*/: break;
  23172. case 'autofiltercondition' /*case 'AutoFilterCondition'*/: break;
  23173. case 'autofilterand' /*case 'AutoFilterAnd'*/: break;
  23174. case 'autofilteror' /*case 'AutoFilterOr'*/: break;
  23175. default: seen = false;
  23176. } break;
  23177. /* QueryTable */
  23178. case 'querytable' /*case 'QueryTable'*/: switch(Rn[3]) {
  23179. case 'id' /*case 'Id'*/: break;
  23180. case 'autoformatfont' /*case 'AutoFormatFont'*/: break;
  23181. case 'autoformatpattern' /*case 'AutoFormatPattern'*/: break;
  23182. case 'querysource' /*case 'QuerySource'*/: break;
  23183. case 'querytype' /*case 'QueryType'*/: break;
  23184. case 'enableredirections' /*case 'EnableRedirections'*/: break;
  23185. case 'refreshedinxl9' /*case 'RefreshedInXl9'*/: break;
  23186. case 'urlstring' /*case 'URLString'*/: break;
  23187. case 'htmltables' /*case 'HTMLTables'*/: break;
  23188. case 'connection' /*case 'Connection'*/: break;
  23189. case 'commandtext' /*case 'CommandText'*/: break;
  23190. case 'refreshinfo' /*case 'RefreshInfo'*/: break;
  23191. case 'notitles' /*case 'NoTitles'*/: break;
  23192. case 'nextid' /*case 'NextId'*/: break;
  23193. case 'columninfo' /*case 'ColumnInfo'*/: break;
  23194. case 'overwritecells' /*case 'OverwriteCells'*/: break;
  23195. case 'donotpromptforfile' /*case 'DoNotPromptForFile'*/: break;
  23196. case 'textwizardsettings' /*case 'TextWizardSettings'*/: break;
  23197. case 'source' /*case 'Source'*/: break;
  23198. case 'number' /*case 'Number'*/: break;
  23199. case 'decimal' /*case 'Decimal'*/: break;
  23200. case 'thousandseparator' /*case 'ThousandSeparator'*/: break;
  23201. case 'trailingminusnumbers' /*case 'TrailingMinusNumbers'*/: break;
  23202. case 'formatsettings' /*case 'FormatSettings'*/: break;
  23203. case 'fieldtype' /*case 'FieldType'*/: break;
  23204. case 'delimiters' /*case 'Delimiters'*/: break;
  23205. case 'tab' /*case 'Tab'*/: break;
  23206. case 'comma' /*case 'Comma'*/: break;
  23207. case 'autoformatname' /*case 'AutoFormatName'*/: break;
  23208. case 'versionlastedit' /*case 'VersionLastEdit'*/: break;
  23209. case 'versionlastrefresh' /*case 'VersionLastRefresh'*/: break;
  23210. default: seen = false;
  23211. } break;
  23212. case 'datavalidation' /*case 'DataValidation'*/:
  23213. switch(Rn[3]) {
  23214. case 'range' /*case 'Range'*/: break;
  23215. case 'type' /*case 'Type'*/: break;
  23216. case 'min' /*case 'Min'*/: break;
  23217. case 'max' /*case 'Max'*/: break;
  23218. case 'sort' /*case 'Sort'*/: break;
  23219. case 'descending' /*case 'Descending'*/: break;
  23220. case 'order' /*case 'Order'*/: break;
  23221. case 'casesensitive' /*case 'CaseSensitive'*/: break;
  23222. case 'value' /*case 'Value'*/: break;
  23223. case 'errorstyle' /*case 'ErrorStyle'*/: break;
  23224. case 'errormessage' /*case 'ErrorMessage'*/: break;
  23225. case 'errortitle' /*case 'ErrorTitle'*/: break;
  23226. case 'inputmessage' /*case 'InputMessage'*/: break;
  23227. case 'inputtitle' /*case 'InputTitle'*/: break;
  23228. case 'combohide' /*case 'ComboHide'*/: break;
  23229. case 'inputhide' /*case 'InputHide'*/: break;
  23230. case 'condition' /*case 'Condition'*/: break;
  23231. case 'qualifier' /*case 'Qualifier'*/: break;
  23232. case 'useblank' /*case 'UseBlank'*/: break;
  23233. case 'value1' /*case 'Value1'*/: break;
  23234. case 'value2' /*case 'Value2'*/: break;
  23235. case 'format' /*case 'Format'*/: break;
  23236. case 'cellrangelist' /*case 'CellRangeList'*/: break;
  23237. default: seen = false;
  23238. } break;
  23239. case 'sorting' /*case 'Sorting'*/:
  23240. case 'conditionalformatting' /*case 'ConditionalFormatting'*/:
  23241. switch(Rn[3]) {
  23242. case 'range' /*case 'Range'*/: break;
  23243. case 'type' /*case 'Type'*/: break;
  23244. case 'min' /*case 'Min'*/: break;
  23245. case 'max' /*case 'Max'*/: break;
  23246. case 'sort' /*case 'Sort'*/: break;
  23247. case 'descending' /*case 'Descending'*/: break;
  23248. case 'order' /*case 'Order'*/: break;
  23249. case 'casesensitive' /*case 'CaseSensitive'*/: break;
  23250. case 'value' /*case 'Value'*/: break;
  23251. case 'errorstyle' /*case 'ErrorStyle'*/: break;
  23252. case 'errormessage' /*case 'ErrorMessage'*/: break;
  23253. case 'errortitle' /*case 'ErrorTitle'*/: break;
  23254. case 'cellrangelist' /*case 'CellRangeList'*/: break;
  23255. case 'inputmessage' /*case 'InputMessage'*/: break;
  23256. case 'inputtitle' /*case 'InputTitle'*/: break;
  23257. case 'combohide' /*case 'ComboHide'*/: break;
  23258. case 'inputhide' /*case 'InputHide'*/: break;
  23259. case 'condition' /*case 'Condition'*/: break;
  23260. case 'qualifier' /*case 'Qualifier'*/: break;
  23261. case 'useblank' /*case 'UseBlank'*/: break;
  23262. case 'value1' /*case 'Value1'*/: break;
  23263. case 'value2' /*case 'Value2'*/: break;
  23264. case 'format' /*case 'Format'*/: break;
  23265. default: seen = false;
  23266. } break;
  23267. /* MapInfo (schema) */
  23268. case 'mapinfo' /*case 'MapInfo'*/: case 'schema' /*case 'Schema'*/: case 'data' /*case 'data'*/: switch(Rn[3]) {
  23269. case 'map' /*case 'Map'*/: break;
  23270. case 'entry' /*case 'Entry'*/: break;
  23271. case 'range' /*case 'Range'*/: break;
  23272. case 'xpath' /*case 'XPath'*/: break;
  23273. case 'field' /*case 'Field'*/: break;
  23274. case 'xsdtype' /*case 'XSDType'*/: break;
  23275. case 'filteron' /*case 'FilterOn'*/: break;
  23276. case 'aggregate' /*case 'Aggregate'*/: break;
  23277. case 'elementtype' /*case 'ElementType'*/: break;
  23278. case 'attributetype' /*case 'AttributeType'*/: break;
  23279. /* These are from xsd (XML Schema Definition) */
  23280. case 'schema' /*case 'schema'*/:
  23281. case 'element' /*case 'element'*/:
  23282. case 'complextype' /*case 'complexType'*/:
  23283. case 'datatype' /*case 'datatype'*/:
  23284. case 'all' /*case 'all'*/:
  23285. case 'attribute' /*case 'attribute'*/:
  23286. case 'extends' /*case 'extends'*/: break;
  23287. case 'row' /*case 'row'*/: break;
  23288. default: seen = false;
  23289. } break;
  23290. /* SmartTags (can be anything) */
  23291. case 'smarttags' /*case 'SmartTags'*/: break;
  23292. default: seen = false; break;
  23293. }
  23294. if(seen) break;
  23295. /* CustomDocumentProperties */
  23296. if(Rn[3].match(/!\[CDATA/)) break;
  23297. if(!state[state.length-1][1]) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
  23298. if(state[state.length-1][0]===/*'CustomDocumentProperties'*/'customdocumentproperties') {
  23299. if(Rn[0].slice(-2) === "/>") break;
  23300. else if(Rn[1]==="/") xlml_set_custprop(Custprops, raw_Rn3, cp, str.slice(pidx, Rn.index));
  23301. else { cp = Rn; pidx = Rn.index + Rn[0].length; }
  23302. break;
  23303. }
  23304. if(opts.WTF) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
  23305. }
  23306. var out = ({});
  23307. if(!opts.bookSheets && !opts.bookProps) out.Sheets = sheets;
  23308. out.SheetNames = sheetnames;
  23309. out.Workbook = Workbook;
  23310. out.SSF = SSF.get_table();
  23311. out.Props = Props;
  23312. out.Custprops = Custprops;
  23313. return out;
  23314. }
  23315. function parse_xlml(data, opts) {
  23316. fix_read_opts(opts=opts||{});
  23317. switch(opts.type||"base64") {
  23318. case "base64": return parse_xlml_xml(Base64.decode(data), opts);
  23319. case "binary": case "buffer": case "file": return parse_xlml_xml(data, opts);
  23320. case "array": return parse_xlml_xml(a2s(data), opts);
  23321. }
  23322. }
  23323. /* TODO */
  23324. function write_props_xlml(wb, opts) {
  23325. var o = [];
  23326. /* DocumentProperties */
  23327. if(wb.Props) o.push(xlml_write_docprops(wb.Props, opts));
  23328. /* CustomDocumentProperties */
  23329. if(wb.Custprops) o.push(xlml_write_custprops(wb.Props, wb.Custprops, opts));
  23330. return o.join("");
  23331. }
  23332. /* TODO */
  23333. function write_wb_xlml() {
  23334. /* OfficeDocumentSettings */
  23335. /* ExcelWorkbook */
  23336. return "";
  23337. }
  23338. /* TODO */
  23339. function write_sty_xlml(wb, opts) {
  23340. /* Styles */
  23341. var styles = ['<Style ss:ID="Default" ss:Name="Normal"><NumberFormat/></Style>'];
  23342. opts.cellXfs.forEach(function(xf, id) {
  23343. var payload = [];
  23344. payload.push(writextag('NumberFormat', null, {"ss:Format": escapexml(SSF._table[xf.numFmtId])}));
  23345. var o = {"ss:ID": "s" + (21+id)};
  23346. styles.push(writextag('Style', payload.join(""), o));
  23347. });
  23348. return writextag("Styles", styles.join(""));
  23349. }
  23350. function write_name_xlml(n) { return writextag("NamedRange", null, {"ss:Name": n.Name, "ss:RefersTo":"=" + a1_to_rc(n.Ref, {r:0,c:0})}); }
  23351. function write_names_xlml(wb) {
  23352. if(!((wb||{}).Workbook||{}).Names) return "";
  23353. var names = wb.Workbook.Names;
  23354. var out = [];
  23355. for(var i = 0; i < names.length; ++i) {
  23356. var n = names[i];
  23357. if(n.Sheet != null) continue;
  23358. if(n.Name.match(/^_xlfn\./)) continue;
  23359. out.push(write_name_xlml(n));
  23360. }
  23361. return writextag("Names", out.join(""));
  23362. }
  23363. function write_ws_xlml_names(ws, opts, idx, wb) {
  23364. if(!ws) return "";
  23365. if(!((wb||{}).Workbook||{}).Names) return "";
  23366. var names = wb.Workbook.Names;
  23367. var out = [];
  23368. for(var i = 0; i < names.length; ++i) {
  23369. var n = names[i];
  23370. if(n.Sheet != idx) continue;
  23371. /*switch(n.Name) {
  23372. case "_": continue;
  23373. }*/
  23374. if(n.Name.match(/^_xlfn\./)) continue;
  23375. out.push(write_name_xlml(n));
  23376. }
  23377. return out.join("");
  23378. }
  23379. /* WorksheetOptions */
  23380. function write_ws_xlml_wsopts(ws, opts, idx, wb) {
  23381. if(!ws) return "";
  23382. var o = [];
  23383. /* NOTE: spec technically allows any order, but stick with implied order */
  23384. /* FitToPage */
  23385. /* DoNotDisplayColHeaders */
  23386. /* DoNotDisplayRowHeaders */
  23387. /* ViewableRange */
  23388. /* Selection */
  23389. /* GridlineColor */
  23390. /* Name */
  23391. /* ExcelWorksheetType */
  23392. /* IntlMacro */
  23393. /* Unsynced */
  23394. /* Selected */
  23395. /* CodeName */
  23396. if(ws['!margins']) {
  23397. o.push("<PageSetup>");
  23398. if(ws['!margins'].header) o.push(writextag("Header", null, {'x:Margin':ws['!margins'].header}));
  23399. if(ws['!margins'].footer) o.push(writextag("Footer", null, {'x:Margin':ws['!margins'].footer}));
  23400. o.push(writextag("PageMargins", null, {
  23401. 'x:Bottom': ws['!margins'].bottom || "0.75",
  23402. 'x:Left': ws['!margins'].left || "0.7",
  23403. 'x:Right': ws['!margins'].right || "0.7",
  23404. 'x:Top': ws['!margins'].top || "0.75"
  23405. }));
  23406. o.push("</PageSetup>");
  23407. }
  23408. /* PageSetup */
  23409. /* DisplayPageBreak */
  23410. /* TransitionExpressionEvaluation */
  23411. /* TransitionFormulaEntry */
  23412. /* Print */
  23413. /* Zoom */
  23414. /* PageLayoutZoom */
  23415. /* PageBreakZoom */
  23416. /* ShowPageBreakZoom */
  23417. /* DefaultRowHeight */
  23418. /* DefaultColumnWidth */
  23419. /* StandardWidth */
  23420. if(wb && wb.Workbook && wb.Workbook.Sheets && wb.Workbook.Sheets[idx]) {
  23421. /* Visible */
  23422. if(wb.Workbook.Sheets[idx].Hidden) o.push(writextag("Visible", (wb.Workbook.Sheets[idx].Hidden == 1 ? "SheetHidden" : "SheetVeryHidden"), {}));
  23423. else {
  23424. /* Selected */
  23425. for(var i = 0; i < idx; ++i) if(wb.Workbook.Sheets[i] && !wb.Workbook.Sheets[i].Hidden) break;
  23426. if(i == idx) o.push("<Selected/>");
  23427. }
  23428. }
  23429. /* LeftColumnVisible */
  23430. if(((((wb||{}).Workbook||{}).Views||[])[0]||{}).RTL) o.push("<DisplayRightToLeft/>");
  23431. /* GridlineColorIndex */
  23432. /* DisplayFormulas */
  23433. /* DoNotDisplayGridlines */
  23434. /* DoNotDisplayHeadings */
  23435. /* DoNotDisplayOutline */
  23436. /* ApplyAutomaticOutlineStyles */
  23437. /* NoSummaryRowsBelowDetail */
  23438. /* NoSummaryColumnsRightDetail */
  23439. /* DoNotDisplayZeros */
  23440. /* ActiveRow */
  23441. /* ActiveColumn */
  23442. /* FilterOn */
  23443. /* RangeSelection */
  23444. /* TopRowVisible */
  23445. /* TopRowBottomPane */
  23446. /* LeftColumnRightPane */
  23447. /* ActivePane */
  23448. /* SplitHorizontal */
  23449. /* SplitVertical */
  23450. /* FreezePanes */
  23451. /* FrozenNoSplit */
  23452. /* TabColorIndex */
  23453. /* Panes */
  23454. /* NOTE: Password not supported in XLML Format */
  23455. if(ws['!protect']) {
  23456. o.push(writetag("ProtectContents", "True"));
  23457. if(ws['!protect'].objects) o.push(writetag("ProtectObjects", "True"));
  23458. if(ws['!protect'].scenarios) o.push(writetag("ProtectScenarios", "True"));
  23459. if(ws['!protect'].selectLockedCells != null && !ws['!protect'].selectLockedCells) o.push(writetag("EnableSelection", "NoSelection"));
  23460. else if(ws['!protect'].selectUnlockedCells != null && !ws['!protect'].selectUnlockedCells) o.push(writetag("EnableSelection", "UnlockedCells"));
  23461. [
  23462. [ "formatCells", "AllowFormatCells" ],
  23463. [ "formatColumns", "AllowSizeCols" ],
  23464. [ "formatRows", "AllowSizeRows" ],
  23465. [ "insertColumns", "AllowInsertCols" ],
  23466. [ "insertRows", "AllowInsertRows" ],
  23467. [ "insertHyperlinks", "AllowInsertHyperlinks" ],
  23468. [ "deleteColumns", "AllowDeleteCols" ],
  23469. [ "deleteRows", "AllowDeleteRows" ],
  23470. [ "sort", "AllowSort" ],
  23471. [ "autoFilter", "AllowFilter" ],
  23472. [ "pivotTables", "AllowUsePivotTables" ]
  23473. ].forEach(function(x) { if(ws['!protect'][x[0]]) o.push("<"+x[1]+"/>"); });
  23474. }
  23475. if(o.length == 0) return "";
  23476. return writextag("WorksheetOptions", o.join(""), {xmlns:XLMLNS.x});
  23477. }
  23478. function write_ws_xlml_comment(comments) {
  23479. return comments.map(function(c) {
  23480. // TODO: formatted text
  23481. var t = xlml_unfixstr(c.t||"");
  23482. var d =writextag("ss:Data", t, {"xmlns":"http://www.w3.org/TR/REC-html40"});
  23483. return writextag("Comment", d, {"ss:Author":c.a});
  23484. }).join("");
  23485. }
  23486. function write_ws_xlml_cell(cell, ref, ws, opts, idx, wb, addr){
  23487. if(!cell || (cell.v == undefined && cell.f == undefined)) return "";
  23488. var attr = {};
  23489. if(cell.f) attr["ss:Formula"] = "=" + escapexml(a1_to_rc(cell.f, addr));
  23490. if(cell.F && cell.F.slice(0, ref.length) == ref) {
  23491. var end = decode_cell(cell.F.slice(ref.length + 1));
  23492. attr["ss:ArrayRange"] = "RC:R" + (end.r == addr.r ? "" : "[" + (end.r - addr.r) + "]") + "C" + (end.c == addr.c ? "" : "[" + (end.c - addr.c) + "]");
  23493. }
  23494. if(cell.l && cell.l.Target) {
  23495. attr["ss:HRef"] = escapexml(cell.l.Target);
  23496. if(cell.l.Tooltip) attr["x:HRefScreenTip"] = escapexml(cell.l.Tooltip);
  23497. }
  23498. if(ws['!merges']) {
  23499. var marr = ws['!merges'];
  23500. for(var mi = 0; mi != marr.length; ++mi) {
  23501. if(marr[mi].s.c != addr.c || marr[mi].s.r != addr.r) continue;
  23502. if(marr[mi].e.c > marr[mi].s.c) attr['ss:MergeAcross'] = marr[mi].e.c - marr[mi].s.c;
  23503. if(marr[mi].e.r > marr[mi].s.r) attr['ss:MergeDown'] = marr[mi].e.r - marr[mi].s.r;
  23504. }
  23505. }
  23506. var t = "", p = "";
  23507. switch(cell.t) {
  23508. case 'z': if(!opts.sheetStubs) return ""; break;
  23509. case 'n': t = 'Number'; p = String(cell.v); break;
  23510. case 'b': t = 'Boolean'; p = (cell.v ? "1" : "0"); break;
  23511. case 'e': t = 'Error'; p = BErr[cell.v]; break;
  23512. case 'd': t = 'DateTime'; p = new Date(cell.v).toISOString(); if(cell.z == null) cell.z = cell.z || SSF._table[14]; break;
  23513. case 's': t = 'String'; p = escapexlml(cell.v||""); break;
  23514. }
  23515. /* TODO: cell style */
  23516. var os = get_cell_style(opts.cellXfs, cell, opts);
  23517. attr["ss:StyleID"] = "s" + (21+os);
  23518. attr["ss:Index"] = addr.c + 1;
  23519. var _v = (cell.v != null ? p : "");
  23520. var m = cell.t == 'z' ? "" : ('<Data ss:Type="' + t + '">' + _v + '</Data>');
  23521. if((cell.c||[]).length > 0) m += write_ws_xlml_comment(cell.c);
  23522. return writextag("Cell", m, attr);
  23523. }
  23524. function write_ws_xlml_row(R, row) {
  23525. var o = '<Row ss:Index="' + (R+1) + '"';
  23526. if(row) {
  23527. if(row.hpt && !row.hpx) row.hpx = pt2px(row.hpt);
  23528. if(row.hpx) o += ' ss:AutoFitHeight="0" ss:Height="' + row.hpx + '"';
  23529. if(row.hidden) o += ' ss:Hidden="1"';
  23530. }
  23531. return o + '>';
  23532. }
  23533. /* TODO */
  23534. function write_ws_xlml_table(ws, opts, idx, wb) {
  23535. if(!ws['!ref']) return "";
  23536. var range = safe_decode_range(ws['!ref']);
  23537. var marr = ws['!merges'] || [], mi = 0;
  23538. var o = [];
  23539. if(ws['!cols']) ws['!cols'].forEach(function(n, i) {
  23540. process_col(n);
  23541. var w = !!n.width;
  23542. var p = col_obj_w(i, n);
  23543. var k = {"ss:Index":i+1};
  23544. if(w) k['ss:Width'] = width2px(p.width);
  23545. if(n.hidden) k['ss:Hidden']="1";
  23546. o.push(writextag("Column",null,k));
  23547. });
  23548. var dense = Array.isArray(ws);
  23549. for(var R = range.s.r; R <= range.e.r; ++R) {
  23550. var row = [write_ws_xlml_row(R, (ws['!rows']||[])[R])];
  23551. for(var C = range.s.c; C <= range.e.c; ++C) {
  23552. var skip = false;
  23553. for(mi = 0; mi != marr.length; ++mi) {
  23554. if(marr[mi].s.c > C) continue;
  23555. if(marr[mi].s.r > R) continue;
  23556. if(marr[mi].e.c < C) continue;
  23557. if(marr[mi].e.r < R) continue;
  23558. if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
  23559. break;
  23560. }
  23561. if(skip) continue;
  23562. var addr = {r:R,c:C};
  23563. var ref = encode_cell(addr), cell = dense ? (ws[R]||[])[C] : ws[ref];
  23564. row.push(write_ws_xlml_cell(cell, ref, ws, opts, idx, wb, addr));
  23565. }
  23566. row.push("</Row>");
  23567. if(row.length > 2) o.push(row.join(""));
  23568. }
  23569. return o.join("");
  23570. }
  23571. function write_ws_xlml(idx, opts, wb) {
  23572. var o = [];
  23573. var s = wb.SheetNames[idx];
  23574. var ws = wb.Sheets[s];
  23575. var t = ws ? write_ws_xlml_names(ws, opts, idx, wb) : "";
  23576. if(t.length > 0) o.push("<Names>" + t + "</Names>");
  23577. /* Table */
  23578. t = ws ? write_ws_xlml_table(ws, opts, idx, wb) : "";
  23579. if(t.length > 0) o.push("<Table>" + t + "</Table>");
  23580. /* WorksheetOptions */
  23581. o.push(write_ws_xlml_wsopts(ws, opts, idx, wb));
  23582. return o.join("");
  23583. }
  23584. function write_xlml(wb, opts) {
  23585. if(!opts) opts = {};
  23586. if(!wb.SSF) wb.SSF = SSF.get_table();
  23587. if(wb.SSF) {
  23588. make_ssf(SSF); SSF.load_table(wb.SSF);
  23589. // $FlowIgnore
  23590. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  23591. opts.ssf = wb.SSF;
  23592. opts.cellXfs = [];
  23593. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  23594. }
  23595. var d = [];
  23596. d.push(write_props_xlml(wb, opts));
  23597. d.push(write_wb_xlml(wb, opts));
  23598. d.push("");
  23599. d.push("");
  23600. for(var i = 0; i < wb.SheetNames.length; ++i)
  23601. d.push(writextag("Worksheet", write_ws_xlml(i, opts, wb), {"ss:Name":escapexml(wb.SheetNames[i])}));
  23602. d[2] = write_sty_xlml(wb, opts);
  23603. d[3] = write_names_xlml(wb, opts);
  23604. return XML_HEADER + writextag("Workbook", d.join(""), {
  23605. 'xmlns': XLMLNS.ss,
  23606. 'xmlns:o': XLMLNS.o,
  23607. 'xmlns:x': XLMLNS.x,
  23608. 'xmlns:ss': XLMLNS.ss,
  23609. 'xmlns:dt': XLMLNS.dt,
  23610. 'xmlns:html': XLMLNS.html
  23611. });
  23612. }
  23613. /* [MS-OLEDS] 2.3.8 CompObjStream */
  23614. function parse_compobj(obj) {
  23615. var v = {};
  23616. var o = obj.content;
  23617. /* [MS-OLEDS] 2.3.7 CompObjHeader -- All fields MUST be ignored */
  23618. o.l = 28;
  23619. v.AnsiUserType = o.read_shift(0, "lpstr-ansi");
  23620. v.AnsiClipboardFormat = parse_ClipboardFormatOrAnsiString(o);
  23621. if(o.length - o.l <= 4) return v;
  23622. var m = o.read_shift(4);
  23623. if(m == 0 || m > 40) return v;
  23624. o.l-=4; v.Reserved1 = o.read_shift(0, "lpstr-ansi");
  23625. if(o.length - o.l <= 4) return v;
  23626. m = o.read_shift(4);
  23627. if(m !== 0x71b239f4) return v;
  23628. v.UnicodeClipboardFormat = parse_ClipboardFormatOrUnicodeString(o);
  23629. m = o.read_shift(4);
  23630. if(m == 0 || m > 40) return v;
  23631. o.l-=4; v.Reserved2 = o.read_shift(0, "lpwstr");
  23632. }
  23633. /*
  23634. Continue logic for:
  23635. - 2.4.58 Continue
  23636. - 2.4.59 ContinueBigName
  23637. - 2.4.60 ContinueFrt
  23638. - 2.4.61 ContinueFrt11
  23639. - 2.4.62 ContinueFrt12
  23640. */
  23641. function slurp(R, blob, length, opts) {
  23642. var l = length;
  23643. var bufs = [];
  23644. var d = blob.slice(blob.l,blob.l+l);
  23645. if(opts && opts.enc && opts.enc.insitu) switch(R.n) {
  23646. case 'BOF': case 'FilePass': case 'FileLock': case 'InterfaceHdr': case 'RRDInfo': case 'RRDHead': case 'UsrExcl': break;
  23647. default:
  23648. if(d.length === 0) break;
  23649. opts.enc.insitu(d);
  23650. }
  23651. bufs.push(d);
  23652. blob.l += l;
  23653. var next = (XLSRecordEnum[__readUInt16LE(blob,blob.l)]);
  23654. var start = 0;
  23655. while(next != null && next.n.slice(0,8) === 'Continue') {
  23656. l = __readUInt16LE(blob,blob.l+2);
  23657. start = blob.l + 4;
  23658. if(next.n == 'ContinueFrt') start += 4;
  23659. else if(next.n.slice(0,11) == 'ContinueFrt') start += 12;
  23660. bufs.push(blob.slice(start,blob.l+4+l));
  23661. blob.l += 4+l;
  23662. next = (XLSRecordEnum[__readUInt16LE(blob, blob.l)]);
  23663. }
  23664. var b = (bconcat(bufs));
  23665. prep_blob(b, 0);
  23666. var ll = 0; b.lens = [];
  23667. for(var j = 0; j < bufs.length; ++j) { b.lens.push(ll); ll += bufs[j].length; }
  23668. return R.f(b, b.length, opts);
  23669. }
  23670. function safe_format_xf(p, opts, date1904) {
  23671. if(p.t === 'z') return;
  23672. if(!p.XF) return;
  23673. var fmtid = 0;
  23674. try {
  23675. fmtid = p.z || p.XF.numFmtId || 0;
  23676. if(opts.cellNF) p.z = SSF._table[fmtid];
  23677. } catch(e) { if(opts.WTF) throw e; }
  23678. if(!opts || opts.cellText !== false) try {
  23679. if(p.t === 'e') { p.w = p.w || BErr[p.v]; }
  23680. else if(fmtid === 0 || fmtid == "General") {
  23681. if(p.t === 'n') {
  23682. if((p.v|0) === p.v) p.w = SSF._general_int(p.v);
  23683. else p.w = SSF._general_num(p.v);
  23684. }
  23685. else p.w = SSF._general(p.v);
  23686. }
  23687. else p.w = SSF.format(fmtid,p.v, {date1904:!!date1904});
  23688. } catch(e) { if(opts.WTF) throw e; }
  23689. if(opts.cellDates && fmtid && p.t == 'n' && SSF.is_date(SSF._table[fmtid] || String(fmtid))) {
  23690. var _d = SSF.parse_date_code(p.v); if(_d) { p.t = 'd'; p.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
  23691. }
  23692. }
  23693. function make_cell(val, ixfe, t) {
  23694. return ({v:val, ixfe:ixfe, t:t});
  23695. }
  23696. // 2.3.2
  23697. function parse_workbook(blob, options) {
  23698. var wb = ({opts:{}});
  23699. var Sheets = {};
  23700. if(DENSE != null && options.dense == null) options.dense = DENSE;
  23701. var out = ((options.dense ? [] : {}));
  23702. var Directory = {};
  23703. var range = ({});
  23704. var last_formula = null;
  23705. var sst = ([]);
  23706. var cur_sheet = "";
  23707. var Preamble = {};
  23708. var lastcell, last_cell = "", cc, cmnt, rngC, rngR;
  23709. var sharedf = {};
  23710. var arrayf = [];
  23711. var temp_val;
  23712. var country;
  23713. var cell_valid = true;
  23714. var XFs = []; /* XF records */
  23715. var palette = [];
  23716. var Workbook = ({ Sheets:[], WBProps:{date1904:false}, Views:[{}] }), wsprops = {};
  23717. var get_rgb = function getrgb(icv) {
  23718. if(icv < 8) return XLSIcv[icv];
  23719. if(icv < 64) return palette[icv-8] || XLSIcv[icv];
  23720. return XLSIcv[icv];
  23721. };
  23722. var process_cell_style = function pcs(cell, line, options) {
  23723. var xfd = line.XF.data;
  23724. if(!xfd || !xfd.patternType || !options || !options.cellStyles) return;
  23725. line.s = ({});
  23726. line.s.patternType = xfd.patternType;
  23727. var t;
  23728. if((t = rgb2Hex(get_rgb(xfd.icvFore)))) { line.s.fgColor = {rgb:t}; }
  23729. if((t = rgb2Hex(get_rgb(xfd.icvBack)))) { line.s.bgColor = {rgb:t}; }
  23730. };
  23731. var addcell = function addcell(cell, line, options) {
  23732. if(file_depth > 1) return;
  23733. if(options.sheetRows && cell.r >= options.sheetRows) cell_valid = false;
  23734. if(!cell_valid) return;
  23735. if(options.cellStyles && line.XF && line.XF.data) process_cell_style(cell, line, options);
  23736. delete line.ixfe; delete line.XF;
  23737. lastcell = cell;
  23738. last_cell = encode_cell(cell);
  23739. if(!range || !range.s || !range.e) range = {s:{r:0,c:0},e:{r:0,c:0}};
  23740. if(cell.r < range.s.r) range.s.r = cell.r;
  23741. if(cell.c < range.s.c) range.s.c = cell.c;
  23742. if(cell.r + 1 > range.e.r) range.e.r = cell.r + 1;
  23743. if(cell.c + 1 > range.e.c) range.e.c = cell.c + 1;
  23744. if(options.cellFormula && line.f) {
  23745. for(var afi = 0; afi < arrayf.length; ++afi) {
  23746. if(arrayf[afi][0].s.c > cell.c || arrayf[afi][0].s.r > cell.r) continue;
  23747. if(arrayf[afi][0].e.c < cell.c || arrayf[afi][0].e.r < cell.r) continue;
  23748. line.F = encode_range(arrayf[afi][0]);
  23749. if(arrayf[afi][0].s.c != cell.c || arrayf[afi][0].s.r != cell.r) delete line.f;
  23750. if(line.f) line.f = "" + stringify_formula(arrayf[afi][1], range, cell, supbooks, opts);
  23751. break;
  23752. }
  23753. }
  23754. {
  23755. if(options.dense) {
  23756. if(!out[cell.r]) out[cell.r] = [];
  23757. out[cell.r][cell.c] = line;
  23758. } else out[last_cell] = line;
  23759. }
  23760. };
  23761. var opts = ({
  23762. enc: false, // encrypted
  23763. sbcch: 0, // cch in the preceding SupBook
  23764. snames: [], // sheetnames
  23765. sharedf: sharedf, // shared formulae by address
  23766. arrayf: arrayf, // array formulae array
  23767. rrtabid: [], // RRTabId
  23768. lastuser: "", // Last User from WriteAccess
  23769. biff: 8, // BIFF version
  23770. codepage: 0, // CP from CodePage record
  23771. winlocked: 0, // fLockWn from WinProtect
  23772. cellStyles: !!options && !!options.cellStyles,
  23773. WTF: !!options && !!options.wtf
  23774. });
  23775. if(options.password) opts.password = options.password;
  23776. var themes;
  23777. var merges = [];
  23778. var objects = [];
  23779. var colinfo = [], rowinfo = [];
  23780. // eslint-disable-next-line no-unused-vars
  23781. var defwidth = 0, defheight = 0; // twips / MDW respectively
  23782. var seencol = false;
  23783. var supbooks = ([]); // 1-indexed, will hold extern names
  23784. supbooks.SheetNames = opts.snames;
  23785. supbooks.sharedf = opts.sharedf;
  23786. supbooks.arrayf = opts.arrayf;
  23787. supbooks.names = [];
  23788. supbooks.XTI = [];
  23789. var last_Rn = '';
  23790. var file_depth = 0; /* TODO: make a real stack */
  23791. var BIFF2Fmt = 0, BIFF2FmtTable = [];
  23792. var FilterDatabases = []; /* TODO: sort out supbooks and process elsewhere */
  23793. var last_lbl;
  23794. /* explicit override for some broken writers */
  23795. opts.codepage = 1200;
  23796. set_cp(1200);
  23797. var seen_codepage = false;
  23798. while(blob.l < blob.length - 1) {
  23799. var s = blob.l;
  23800. var RecordType = blob.read_shift(2);
  23801. if(RecordType === 0 && last_Rn === 'EOF') break;
  23802. var length = (blob.l === blob.length ? 0 : blob.read_shift(2));
  23803. var R = XLSRecordEnum[RecordType];
  23804. //console.log(RecordType.toString(16), RecordType, R, blob.l, length, blob.length);
  23805. //if(!R) console.log(blob.slice(blob.l, blob.l + length));
  23806. if(R && R.f) {
  23807. if(options.bookSheets) {
  23808. if(last_Rn === 'BoundSheet8' && R.n !== 'BoundSheet8') break;
  23809. }
  23810. last_Rn = R.n;
  23811. if(R.r === 2 || R.r == 12) {
  23812. var rt = blob.read_shift(2); length -= 2;
  23813. if(!opts.enc && rt !== RecordType && (((rt&0xFF)<<8)|(rt>>8)) !== RecordType) throw new Error("rt mismatch: " + rt + "!=" + RecordType);
  23814. if(R.r == 12){ blob.l += 10; length -= 10; } // skip FRT
  23815. }
  23816. //console.error(R,blob.l,length,blob.length);
  23817. var val = ({});
  23818. if(R.n === 'EOF') val = R.f(blob, length, opts);
  23819. else val = slurp(R, blob, length, opts);
  23820. var Rn = R.n;
  23821. if(file_depth == 0 && Rn != 'BOF') continue;
  23822. /* nested switch statements to workaround V8 128 limit */
  23823. switch(Rn) {
  23824. /* Workbook Options */
  23825. case 'Date1904':
  23826. wb.opts.Date1904 = Workbook.WBProps.date1904 = val; break;
  23827. case 'WriteProtect': wb.opts.WriteProtect = true; break;
  23828. case 'FilePass':
  23829. if(!opts.enc) blob.l = 0;
  23830. opts.enc = val;
  23831. if(!options.password) throw new Error("File is password-protected");
  23832. if(val.valid == null) throw new Error("Encryption scheme unsupported");
  23833. if(!val.valid) throw new Error("Password is incorrect");
  23834. break;
  23835. case 'WriteAccess': opts.lastuser = val; break;
  23836. case 'FileSharing': break; //TODO
  23837. case 'CodePage':
  23838. var cpval = Number(val);
  23839. /* overrides based on test cases */
  23840. switch(cpval) {
  23841. case 0x5212: cpval = 1200; break;
  23842. case 0x8000: cpval = 10000; break;
  23843. case 0x8001: cpval = 1252; break;
  23844. }
  23845. set_cp(opts.codepage = cpval);
  23846. seen_codepage = true;
  23847. break;
  23848. case 'RRTabId': opts.rrtabid = val; break;
  23849. case 'WinProtect': opts.winlocked = val; break;
  23850. case 'Template': break; // TODO
  23851. case 'BookBool': break; // TODO
  23852. case 'UsesELFs': break;
  23853. case 'MTRSettings': break;
  23854. case 'RefreshAll':
  23855. case 'CalcCount':
  23856. case 'CalcDelta':
  23857. case 'CalcIter':
  23858. case 'CalcMode':
  23859. case 'CalcPrecision':
  23860. case 'CalcSaveRecalc':
  23861. wb.opts[Rn] = val; break;
  23862. case 'CalcRefMode': opts.CalcRefMode = val; break; // TODO: implement R1C1
  23863. case 'Uncalced': break;
  23864. case 'ForceFullCalculation': wb.opts.FullCalc = val; break;
  23865. case 'WsBool':
  23866. if(val.fDialog) out["!type"] = "dialog";
  23867. break; // TODO
  23868. case 'XF':
  23869. XFs.push(val); break;
  23870. case 'ExtSST': break; // TODO
  23871. case 'BookExt': break; // TODO
  23872. case 'RichTextStream': break;
  23873. case 'BkHim': break;
  23874. case 'SupBook':
  23875. supbooks.push([val]);
  23876. supbooks[supbooks.length-1].XTI = [];
  23877. break;
  23878. case 'ExternName':
  23879. supbooks[supbooks.length-1].push(val);
  23880. break;
  23881. case 'Index': break; // TODO
  23882. case 'Lbl':
  23883. last_lbl = ({
  23884. Name: val.Name,
  23885. Ref: stringify_formula(val.rgce,range,null,supbooks,opts)
  23886. });
  23887. if(val.itab > 0) last_lbl.Sheet = val.itab - 1;
  23888. supbooks.names.push(last_lbl);
  23889. if(!supbooks[0]) { supbooks[0] = []; supbooks[0].XTI = []; }
  23890. supbooks[supbooks.length-1].push(val);
  23891. if(val.Name == "_xlnm._FilterDatabase" && val.itab > 0)
  23892. if(val.rgce && val.rgce[0] && val.rgce[0][0] && val.rgce[0][0][0] == 'PtgArea3d')
  23893. FilterDatabases[val.itab - 1] = { ref: encode_range(val.rgce[0][0][1][2]) };
  23894. break;
  23895. case 'ExternCount': opts.ExternCount = val; break;
  23896. case 'ExternSheet':
  23897. if(supbooks.length == 0) { supbooks[0] = []; supbooks[0].XTI = []; }
  23898. supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val); supbooks.XTI = supbooks.XTI.concat(val); break;
  23899. case 'NameCmt':
  23900. /* TODO: search for correct name */
  23901. if(opts.biff < 8) break;
  23902. if(last_lbl != null) last_lbl.Comment = val[1];
  23903. break;
  23904. case 'Protect': out["!protect"] = val; break; /* for sheet or book */
  23905. case 'Password': if(val !== 0 && opts.WTF) console.error("Password verifier: " + val); break;
  23906. case 'Prot4Rev': case 'Prot4RevPass': break; /*TODO: Revision Control*/
  23907. case 'BoundSheet8': {
  23908. Directory[val.pos] = val;
  23909. opts.snames.push(val.name);
  23910. } break;
  23911. case 'EOF': {
  23912. if(--file_depth) break;
  23913. if(range.e) {
  23914. if(range.e.r > 0 && range.e.c > 0) {
  23915. range.e.r--; range.e.c--;
  23916. out["!ref"] = encode_range(range);
  23917. if(options.sheetRows && options.sheetRows <= range.e.r) {
  23918. var tmpri = range.e.r;
  23919. range.e.r = options.sheetRows - 1;
  23920. out["!fullref"] = out["!ref"];
  23921. out["!ref"] = encode_range(range);
  23922. range.e.r = tmpri;
  23923. }
  23924. range.e.r++; range.e.c++;
  23925. }
  23926. if(merges.length > 0) out["!merges"] = merges;
  23927. if(objects.length > 0) out["!objects"] = objects;
  23928. if(colinfo.length > 0) out["!cols"] = colinfo;
  23929. if(rowinfo.length > 0) out["!rows"] = rowinfo;
  23930. Workbook.Sheets.push(wsprops);
  23931. }
  23932. if(cur_sheet === "") Preamble = out; else Sheets[cur_sheet] = out;
  23933. out = ((options.dense ? [] : {}));
  23934. } break;
  23935. case 'BOF': {
  23936. if(opts.biff === 8) opts.biff = {
  23937. 0x0009:2,
  23938. 0x0209:3,
  23939. 0x0409:4
  23940. }[RecordType] || {
  23941. 0x0200:2,
  23942. 0x0300:3,
  23943. 0x0400:4,
  23944. 0x0500:5,
  23945. 0x0600:8,
  23946. 0x0002:2,
  23947. 0x0007:2
  23948. }[val.BIFFVer] || 8;
  23949. if(opts.biff == 8 && val.BIFFVer == 0 && val.dt == 16) opts.biff = 2;
  23950. if(file_depth++) break;
  23951. cell_valid = true;
  23952. out = ((options.dense ? [] : {}));
  23953. if(opts.biff < 8 && !seen_codepage) { seen_codepage = true; set_cp(opts.codepage = options.codepage || 1252); }
  23954. if(opts.biff < 5) {
  23955. if(cur_sheet === "") cur_sheet = "Sheet1";
  23956. range = {s:{r:0,c:0},e:{r:0,c:0}};
  23957. /* fake BoundSheet8 */
  23958. var fakebs8 = {pos: blob.l - length, name:cur_sheet};
  23959. Directory[fakebs8.pos] = fakebs8;
  23960. opts.snames.push(cur_sheet);
  23961. }
  23962. else cur_sheet = (Directory[s] || {name:""}).name;
  23963. if(val.dt == 0x20) out["!type"] = "chart";
  23964. if(val.dt == 0x40) out["!type"] = "macro";
  23965. merges = [];
  23966. objects = [];
  23967. opts.arrayf = arrayf = [];
  23968. colinfo = []; rowinfo = [];
  23969. defwidth = defheight = 0;
  23970. seencol = false;
  23971. wsprops = {Hidden:(Directory[s]||{hs:0}).hs, name:cur_sheet };
  23972. } break;
  23973. case 'Number': case 'BIFF2NUM': case 'BIFF2INT': {
  23974. if(out["!type"] == "chart") if(options.dense ? (out[val.r]||[])[val.c]: out[encode_cell({c:val.c, r:val.r})]) ++val.c;
  23975. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe]||{}, v:val.val, t:'n'});
  23976. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  23977. safe_format_xf(temp_val, options, wb.opts.Date1904);
  23978. addcell({c:val.c, r:val.r}, temp_val, options);
  23979. } break;
  23980. case 'BoolErr': {
  23981. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.val, t:val.t});
  23982. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  23983. safe_format_xf(temp_val, options, wb.opts.Date1904);
  23984. addcell({c:val.c, r:val.r}, temp_val, options);
  23985. } break;
  23986. case 'RK': {
  23987. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.rknum, t:'n'});
  23988. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  23989. safe_format_xf(temp_val, options, wb.opts.Date1904);
  23990. addcell({c:val.c, r:val.r}, temp_val, options);
  23991. } break;
  23992. case 'MulRk': {
  23993. for(var j = val.c; j <= val.C; ++j) {
  23994. var ixfe = val.rkrec[j-val.c][0];
  23995. temp_val= ({ixfe:ixfe, XF:XFs[ixfe], v:val.rkrec[j-val.c][1], t:'n'});
  23996. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  23997. safe_format_xf(temp_val, options, wb.opts.Date1904);
  23998. addcell({c:j, r:val.r}, temp_val, options);
  23999. }
  24000. } break;
  24001. case 'Formula': {
  24002. if(val.val == 'String') { last_formula = val; break; }
  24003. temp_val = make_cell(val.val, val.cell.ixfe, val.tt);
  24004. temp_val.XF = XFs[temp_val.ixfe];
  24005. if(options.cellFormula) {
  24006. var _f = val.formula;
  24007. if(_f && _f[0] && _f[0][0] && _f[0][0][0] == 'PtgExp') {
  24008. var _fr = _f[0][0][1][0], _fc = _f[0][0][1][1];
  24009. var _fe = encode_cell({r:_fr, c:_fc});
  24010. if(sharedf[_fe]) temp_val.f = ""+stringify_formula(val.formula,range,val.cell,supbooks, opts);
  24011. else temp_val.F = ((options.dense ? (out[_fr]||[])[_fc]: out[_fe]) || {}).F;
  24012. } else temp_val.f = ""+stringify_formula(val.formula,range,val.cell,supbooks, opts);
  24013. }
  24014. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24015. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24016. addcell(val.cell, temp_val, options);
  24017. last_formula = val;
  24018. } break;
  24019. case 'String': {
  24020. if(last_formula) { /* technically always true */
  24021. last_formula.val = val;
  24022. temp_val = make_cell(val, last_formula.cell.ixfe, 's');
  24023. temp_val.XF = XFs[temp_val.ixfe];
  24024. if(options.cellFormula) {
  24025. temp_val.f = ""+stringify_formula(last_formula.formula, range, last_formula.cell, supbooks, opts);
  24026. }
  24027. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24028. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24029. addcell(last_formula.cell, temp_val, options);
  24030. last_formula = null;
  24031. } else throw new Error("String record expects Formula");
  24032. } break;
  24033. case 'Array': {
  24034. arrayf.push(val);
  24035. var _arraystart = encode_cell(val[0].s);
  24036. cc = options.dense ? (out[val[0].s.r]||[])[val[0].s.c] : out[_arraystart];
  24037. if(options.cellFormula && cc) {
  24038. if(!last_formula) break; /* technically unreachable */
  24039. if(!_arraystart || !cc) break;
  24040. cc.f = ""+stringify_formula(val[1], range, val[0], supbooks, opts);
  24041. cc.F = encode_range(val[0]);
  24042. }
  24043. } break;
  24044. case 'ShrFmla': {
  24045. if(!cell_valid) break;
  24046. if(!options.cellFormula) break;
  24047. if(last_cell) {
  24048. /* TODO: capture range */
  24049. if(!last_formula) break; /* technically unreachable */
  24050. sharedf[encode_cell(last_formula.cell)]= val[0];
  24051. cc = options.dense ? (out[last_formula.cell.r]||[])[last_formula.cell.c] : out[encode_cell(last_formula.cell)];
  24052. (cc||{}).f = ""+stringify_formula(val[0], range, lastcell, supbooks, opts);
  24053. }
  24054. } break;
  24055. case 'LabelSst':
  24056. temp_val=make_cell(sst[val.isst].t, val.ixfe, 's');
  24057. if(sst[val.isst].h) temp_val.h = sst[val.isst].h;
  24058. temp_val.XF = XFs[temp_val.ixfe];
  24059. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24060. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24061. addcell({c:val.c, r:val.r}, temp_val, options);
  24062. break;
  24063. case 'Blank': if(options.sheetStubs) {
  24064. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], t:'z'});
  24065. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24066. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24067. addcell({c:val.c, r:val.r}, temp_val, options);
  24068. } break;
  24069. case 'MulBlank': if(options.sheetStubs) {
  24070. for(var _j = val.c; _j <= val.C; ++_j) {
  24071. var _ixfe = val.ixfe[_j-val.c];
  24072. temp_val= ({ixfe:_ixfe, XF:XFs[_ixfe], t:'z'});
  24073. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24074. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24075. addcell({c:_j, r:val.r}, temp_val, options);
  24076. }
  24077. } break;
  24078. case 'RString':
  24079. case 'Label': case 'BIFF2STR':
  24080. temp_val=make_cell(val.val, val.ixfe, 's');
  24081. temp_val.XF = XFs[temp_val.ixfe];
  24082. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24083. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24084. addcell({c:val.c, r:val.r}, temp_val, options);
  24085. break;
  24086. case 'Dimensions': {
  24087. if(file_depth === 1) range = val; /* TODO: stack */
  24088. } break;
  24089. case 'SST': {
  24090. sst = val;
  24091. } break;
  24092. case 'Format': { /* val = [id, fmt] */
  24093. if(opts.biff == 4) {
  24094. BIFF2FmtTable[BIFF2Fmt++] = val[1];
  24095. for(var b4idx = 0; b4idx < BIFF2Fmt + 163; ++b4idx) if(SSF._table[b4idx] == val[1]) break;
  24096. if(b4idx >= 163) SSF.load(val[1], BIFF2Fmt + 163);
  24097. }
  24098. else SSF.load(val[1], val[0]);
  24099. } break;
  24100. case 'BIFF2FORMAT': {
  24101. BIFF2FmtTable[BIFF2Fmt++] = val;
  24102. for(var b2idx = 0; b2idx < BIFF2Fmt + 163; ++b2idx) if(SSF._table[b2idx] == val) break;
  24103. if(b2idx >= 163) SSF.load(val, BIFF2Fmt + 163);
  24104. } break;
  24105. case 'MergeCells': merges = merges.concat(val); break;
  24106. case 'Obj': objects[val.cmo[0]] = opts.lastobj = val; break;
  24107. case 'TxO': opts.lastobj.TxO = val; break;
  24108. case 'ImData': opts.lastobj.ImData = val; break;
  24109. case 'HLink': {
  24110. for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR)
  24111. for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) {
  24112. cc = options.dense ? (out[rngR]||[])[rngC] : out[encode_cell({c:rngC,r:rngR})];
  24113. if(cc) cc.l = val[1];
  24114. }
  24115. } break;
  24116. case 'HLinkTooltip': {
  24117. for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR)
  24118. for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) {
  24119. cc = options.dense ? (out[rngR]||[])[rngC] : out[encode_cell({c:rngC,r:rngR})];
  24120. if(cc && cc.l) cc.l.Tooltip = val[1];
  24121. }
  24122. } break;
  24123. /* Comments */
  24124. case 'Note': {
  24125. if(opts.biff <= 5 && opts.biff >= 2) break; /* TODO: BIFF5 */
  24126. cc = options.dense ? (out[val[0].r]||[])[val[0].c] : out[encode_cell(val[0])];
  24127. var noteobj = objects[val[2]];
  24128. if(!cc) {
  24129. if(options.dense) {
  24130. if(!out[val[0].r]) out[val[0].r] = [];
  24131. cc = out[val[0].r][val[0].c] = ({t:"z"});
  24132. } else {
  24133. cc = out[encode_cell(val[0])] = ({t:"z"});
  24134. }
  24135. range.e.r = Math.max(range.e.r, val[0].r);
  24136. range.s.r = Math.min(range.s.r, val[0].r);
  24137. range.e.c = Math.max(range.e.c, val[0].c);
  24138. range.s.c = Math.min(range.s.c, val[0].c);
  24139. }
  24140. if(!cc.c) cc.c = [];
  24141. cmnt = {a:val[1],t:noteobj.TxO.t};
  24142. cc.c.push(cmnt);
  24143. } break;
  24144. default: switch(R.n) { /* nested */
  24145. case 'ClrtClient': break;
  24146. case 'XFExt': update_xfext(XFs[val.ixfe], val.ext); break;
  24147. case 'DefColWidth': defwidth = val; break;
  24148. case 'DefaultRowHeight': defheight = val[1]; break; // TODO: flags
  24149. case 'ColInfo': {
  24150. if(!opts.cellStyles) break;
  24151. while(val.e >= val.s) {
  24152. colinfo[val.e--] = { width: val.w/256 };
  24153. if(!seencol) { seencol = true; find_mdw_colw(val.w/256); }
  24154. process_col(colinfo[val.e+1]);
  24155. }
  24156. } break;
  24157. case 'Row': {
  24158. var rowobj = {};
  24159. if(val.level != null) { rowinfo[val.r] = rowobj; rowobj.level = val.level; }
  24160. if(val.hidden) { rowinfo[val.r] = rowobj; rowobj.hidden = true; }
  24161. if(val.hpt) {
  24162. rowinfo[val.r] = rowobj;
  24163. rowobj.hpt = val.hpt; rowobj.hpx = pt2px(val.hpt);
  24164. }
  24165. } break;
  24166. case 'LeftMargin':
  24167. case 'RightMargin':
  24168. case 'TopMargin':
  24169. case 'BottomMargin':
  24170. if(!out['!margins']) default_margins(out['!margins'] = {});
  24171. out['!margins'][Rn.slice(0,-6).toLowerCase()] = val;
  24172. break;
  24173. case 'Setup': // TODO
  24174. if(!out['!margins']) default_margins(out['!margins'] = {});
  24175. out['!margins'].header = val.header;
  24176. out['!margins'].footer = val.footer;
  24177. break;
  24178. case 'Window2': // TODO
  24179. // $FlowIgnore
  24180. if(val.RTL) Workbook.Views[0].RTL = true;
  24181. break;
  24182. case 'Header': break; // TODO
  24183. case 'Footer': break; // TODO
  24184. case 'HCenter': break; // TODO
  24185. case 'VCenter': break; // TODO
  24186. case 'Pls': break; // TODO
  24187. case 'GCW': break;
  24188. case 'LHRecord': break;
  24189. case 'DBCell': break; // TODO
  24190. case 'EntExU2': break; // TODO
  24191. case 'SxView': break; // TODO
  24192. case 'Sxvd': break; // TODO
  24193. case 'SXVI': break; // TODO
  24194. case 'SXVDEx': break; // TODO
  24195. case 'SxIvd': break; // TODO
  24196. case 'SXString': break; // TODO
  24197. case 'Sync': break;
  24198. case 'Addin': break;
  24199. case 'SXDI': break; // TODO
  24200. case 'SXLI': break; // TODO
  24201. case 'SXEx': break; // TODO
  24202. case 'QsiSXTag': break; // TODO
  24203. case 'Selection': break;
  24204. case 'Feat': break;
  24205. case 'FeatHdr': case 'FeatHdr11': break;
  24206. case 'Feature11': case 'Feature12': case 'List12': break;
  24207. case 'Country': country = val; break;
  24208. case 'RecalcId': break;
  24209. case 'DxGCol': break; // TODO: htmlify
  24210. case 'Fbi': case 'Fbi2': case 'GelFrame': break;
  24211. case 'Font': break; // TODO
  24212. case 'XFCRC': break; // TODO
  24213. case 'Style': break; // TODO
  24214. case 'StyleExt': break; // TODO
  24215. case 'Palette': palette = val; break;
  24216. case 'Theme': themes = val; break;
  24217. /* Protection */
  24218. case 'ScenarioProtect': break;
  24219. case 'ObjProtect': break;
  24220. /* Conditional Formatting */
  24221. case 'CondFmt12': break;
  24222. /* Table */
  24223. case 'Table': break; // TODO
  24224. case 'TableStyles': break; // TODO
  24225. case 'TableStyle': break; // TODO
  24226. case 'TableStyleElement': break; // TODO
  24227. /* PivotTable */
  24228. case 'SXStreamID': break; // TODO
  24229. case 'SXVS': break; // TODO
  24230. case 'DConRef': break; // TODO
  24231. case 'SXAddl': break; // TODO
  24232. case 'DConBin': break; // TODO
  24233. case 'DConName': break; // TODO
  24234. case 'SXPI': break; // TODO
  24235. case 'SxFormat': break; // TODO
  24236. case 'SxSelect': break; // TODO
  24237. case 'SxRule': break; // TODO
  24238. case 'SxFilt': break; // TODO
  24239. case 'SxItm': break; // TODO
  24240. case 'SxDXF': break; // TODO
  24241. /* Scenario Manager */
  24242. case 'ScenMan': break;
  24243. /* Data Consolidation */
  24244. case 'DCon': break;
  24245. /* Watched Cell */
  24246. case 'CellWatch': break;
  24247. /* Print Settings */
  24248. case 'PrintRowCol': break;
  24249. case 'PrintGrid': break;
  24250. case 'PrintSize': break;
  24251. case 'XCT': break;
  24252. case 'CRN': break;
  24253. case 'Scl': {
  24254. //console.log("Zoom Level:", val[0]/val[1],val);
  24255. } break;
  24256. case 'SheetExt': {
  24257. /* empty */
  24258. } break;
  24259. case 'SheetExtOptional': {
  24260. /* empty */
  24261. } break;
  24262. /* VBA */
  24263. case 'ObNoMacros': {
  24264. /* empty */
  24265. } break;
  24266. case 'ObProj': {
  24267. /* empty */
  24268. } break;
  24269. case 'CodeName': {
  24270. if(!cur_sheet) Workbook.WBProps.CodeName = val || "ThisWorkbook";
  24271. else wsprops.CodeName = val || wsprops.name;
  24272. } break;
  24273. case 'GUIDTypeLib': {
  24274. /* empty */
  24275. } break;
  24276. case 'WOpt': break; // TODO: WTF?
  24277. case 'PhoneticInfo': break;
  24278. case 'OleObjectSize': break;
  24279. /* Differential Formatting */
  24280. case 'DXF': case 'DXFN': case 'DXFN12': case 'DXFN12List': case 'DXFN12NoCB': break;
  24281. /* Data Validation */
  24282. case 'Dv': case 'DVal': break;
  24283. /* Data Series */
  24284. case 'BRAI': case 'Series': case 'SeriesText': break;
  24285. /* Data Connection */
  24286. case 'DConn': break;
  24287. case 'DbOrParamQry': break;
  24288. case 'DBQueryExt': break;
  24289. case 'OleDbConn': break;
  24290. case 'ExtString': break;
  24291. /* Formatting */
  24292. case 'IFmtRecord': break;
  24293. case 'CondFmt': case 'CF': case 'CF12': case 'CFEx': break;
  24294. /* Explicitly Ignored */
  24295. case 'Excel9File': break;
  24296. case 'Units': break;
  24297. case 'InterfaceHdr': case 'Mms': case 'InterfaceEnd': case 'DSF': break;
  24298. case 'BuiltInFnGroupCount': /* 2.4.30 0x0E or 0x10 but excel 2011 generates 0x11? */ break;
  24299. /* View Stuff */
  24300. case 'Window1': case 'HideObj': case 'GridSet': case 'Guts':
  24301. case 'UserBView': case 'UserSViewBegin': case 'UserSViewEnd': break;
  24302. case 'Pane': break;
  24303. default: switch(R.n) { /* nested */
  24304. /* Chart */
  24305. case 'Dat':
  24306. case 'Begin': case 'End':
  24307. case 'StartBlock': case 'EndBlock':
  24308. case 'Frame': case 'Area':
  24309. case 'Axis': case 'AxisLine': case 'Tick': break;
  24310. case 'AxesUsed':
  24311. case 'CrtLayout12': case 'CrtLayout12A': case 'CrtLink': case 'CrtLine': case 'CrtMlFrt': case 'CrtMlFrtContinue': break;
  24312. case 'LineFormat': case 'AreaFormat':
  24313. case 'Chart': case 'Chart3d': case 'Chart3DBarShape': case 'ChartFormat': case 'ChartFrtInfo': break;
  24314. case 'PlotArea': case 'PlotGrowth': break;
  24315. case 'SeriesList': case 'SerParent': case 'SerAuxTrend': break;
  24316. case 'DataFormat': case 'SerToCrt': case 'FontX': break;
  24317. case 'CatSerRange': case 'AxcExt': case 'SerFmt': break;
  24318. case 'ShtProps': break;
  24319. case 'DefaultText': case 'Text': case 'CatLab': break;
  24320. case 'DataLabExtContents': break;
  24321. case 'Legend': case 'LegendException': break;
  24322. case 'Pie': case 'Scatter': break;
  24323. case 'PieFormat': case 'MarkerFormat': break;
  24324. case 'StartObject': case 'EndObject': break;
  24325. case 'AlRuns': case 'ObjectLink': break;
  24326. case 'SIIndex': break;
  24327. case 'AttachedLabel': case 'YMult': break;
  24328. /* Chart Group */
  24329. case 'Line': case 'Bar': break;
  24330. case 'Surf': break;
  24331. /* Axis Group */
  24332. case 'AxisParent': break;
  24333. case 'Pos': break;
  24334. case 'ValueRange': break;
  24335. /* Pivot Chart */
  24336. case 'SXViewEx9': break; // TODO
  24337. case 'SXViewLink': break;
  24338. case 'PivotChartBits': break;
  24339. case 'SBaseRef': break;
  24340. case 'TextPropsStream': break;
  24341. /* Chart Misc */
  24342. case 'LnExt': break;
  24343. case 'MkrExt': break;
  24344. case 'CrtCoopt': break;
  24345. /* Query Table */
  24346. case 'Qsi': case 'Qsif': case 'Qsir': case 'QsiSXTag': break;
  24347. case 'TxtQry': break;
  24348. /* Filter */
  24349. case 'FilterMode': break;
  24350. case 'AutoFilter': case 'AutoFilterInfo': break;
  24351. case 'AutoFilter12': break;
  24352. case 'DropDownObjIds': break;
  24353. case 'Sort': break;
  24354. case 'SortData': break;
  24355. /* Drawing */
  24356. case 'ShapePropsStream': break;
  24357. case 'MsoDrawing': case 'MsoDrawingGroup': case 'MsoDrawingSelection': break;
  24358. /* Pub Stuff */
  24359. case 'WebPub': case 'AutoWebPub': break;
  24360. /* Print Stuff */
  24361. case 'HeaderFooter': case 'HFPicture': case 'PLV':
  24362. case 'HorizontalPageBreaks': case 'VerticalPageBreaks': break;
  24363. /* Behavioral */
  24364. case 'Backup': case 'CompressPictures': case 'Compat12': break;
  24365. /* Should not Happen */
  24366. case 'Continue': case 'ContinueFrt12': break;
  24367. /* Future Records */
  24368. case 'FrtFontList': case 'FrtWrapper': break;
  24369. default: switch(R.n) { /* nested */
  24370. /* BIFF5 records */
  24371. case 'TabIdConf': case 'Radar': case 'RadarArea': case 'DropBar': case 'Intl': case 'CoordList': case 'SerAuxErrBar': break;
  24372. /* BIFF2-4 records */
  24373. case 'BIFF2FONTCLR': case 'BIFF2FMTCNT': case 'BIFF2FONTXTRA': break;
  24374. case 'BIFF2XF': case 'BIFF3XF': case 'BIFF4XF': break;
  24375. case 'BIFF4FMTCNT': case 'BIFF2ROW': case 'BIFF2WINDOW2': break;
  24376. /* Miscellaneous */
  24377. case 'SCENARIO': case 'DConBin': case 'PicF': case 'DataLabExt':
  24378. case 'Lel': case 'BopPop': case 'BopPopCustom': case 'RealTimeData':
  24379. case 'Name': break;
  24380. case 'LHNGraph': case 'FnGroupName': case 'AddMenu': case 'LPr': break;
  24381. case 'ListObj': case 'ListField': break;
  24382. case 'RRSort': break;
  24383. case 'BigName': break;
  24384. case 'ToolbarHdr': case 'ToolbarEnd': break;
  24385. case 'DDEObjName': break;
  24386. case 'FRTArchId$': break;
  24387. default: if(options.WTF) throw 'Unrecognized Record ' + R.n;
  24388. }}}}
  24389. } else blob.l += length;
  24390. }
  24391. wb.SheetNames=keys(Directory).sort(function(a,b) { return Number(a) - Number(b); }).map(function(x){return Directory[x].name;});
  24392. if(!options.bookSheets) wb.Sheets=Sheets;
  24393. if(wb.Sheets) FilterDatabases.forEach(function(r,i) { wb.Sheets[wb.SheetNames[i]]['!autofilter'] = r; });
  24394. wb.Preamble=Preamble;
  24395. wb.Strings = sst;
  24396. wb.SSF = SSF.get_table();
  24397. if(opts.enc) wb.Encryption = opts.enc;
  24398. if(themes) wb.Themes = themes;
  24399. wb.Metadata = {};
  24400. if(country !== undefined) wb.Metadata.Country = country;
  24401. if(supbooks.names.length > 0) Workbook.Names = supbooks.names;
  24402. wb.Workbook = Workbook;
  24403. return wb;
  24404. }
  24405. /* TODO: split props*/
  24406. var PSCLSID = {
  24407. SI: "e0859ff2f94f6810ab9108002b27b3d9",
  24408. DSI: "02d5cdd59c2e1b10939708002b2cf9ae",
  24409. UDI: "05d5cdd59c2e1b10939708002b2cf9ae"
  24410. };
  24411. function parse_xls_props(cfb, props, o) {
  24412. /* [MS-OSHARED] 2.3.3.2.2 Document Summary Information Property Set */
  24413. var DSI = CFB.find(cfb, '!DocumentSummaryInformation');
  24414. if(DSI && DSI.size > 0) try {
  24415. var DocSummary = parse_PropertySetStream(DSI, DocSummaryPIDDSI, PSCLSID.DSI);
  24416. for(var d in DocSummary) props[d] = DocSummary[d];
  24417. } catch(e) {if(o.WTF) throw e;/* empty */}
  24418. /* [MS-OSHARED] 2.3.3.2.1 Summary Information Property Set*/
  24419. var SI = CFB.find(cfb, '!SummaryInformation');
  24420. if(SI && SI.size > 0) try {
  24421. var Summary = parse_PropertySetStream(SI, SummaryPIDSI, PSCLSID.SI);
  24422. for(var s in Summary) if(props[s] == null) props[s] = Summary[s];
  24423. } catch(e) {if(o.WTF) throw e;/* empty */}
  24424. if(props.HeadingPairs && props.TitlesOfParts) {
  24425. load_props_pairs(props.HeadingPairs, props.TitlesOfParts, props, o);
  24426. delete props.HeadingPairs; delete props.TitlesOfParts;
  24427. }
  24428. }
  24429. function write_xls_props(wb, cfb) {
  24430. var DSEntries = [], SEntries = [], CEntries = [];
  24431. var i = 0, Keys;
  24432. if(wb.Props) {
  24433. Keys = keys(wb.Props);
  24434. // $FlowIgnore
  24435. for(i = 0; i < Keys.length; ++i) (Object.prototype.hasOwnProperty.call(DocSummaryRE, Keys[i]) ? DSEntries : Object.prototype.hasOwnProperty.call(SummaryRE, Keys[i]) ? SEntries : CEntries).push([Keys[i], wb.Props[Keys[i]]]);
  24436. }
  24437. if(wb.Custprops) {
  24438. Keys = keys(wb.Custprops);
  24439. // $FlowIgnore
  24440. for(i = 0; i < Keys.length; ++i) if(!Object.prototype.hasOwnProperty.call((wb.Props||{}), Keys[i])) (Object.prototype.hasOwnProperty.call(DocSummaryRE, Keys[i]) ? DSEntries : Object.prototype.hasOwnProperty.call(SummaryRE, Keys[i]) ? SEntries : CEntries).push([Keys[i], wb.Custprops[Keys[i]]]);
  24441. }
  24442. var CEntries2 = [];
  24443. for(i = 0; i < CEntries.length; ++i) {
  24444. if(XLSPSSkip.indexOf(CEntries[i][0]) > -1) continue;
  24445. if(CEntries[i][1] == null) continue;
  24446. CEntries2.push(CEntries[i]);
  24447. }
  24448. if(SEntries.length) CFB.utils.cfb_add(cfb, "/\u0005SummaryInformation", write_PropertySetStream(SEntries, PSCLSID.SI, SummaryRE, SummaryPIDSI));
  24449. if(DSEntries.length || CEntries2.length) CFB.utils.cfb_add(cfb, "/\u0005DocumentSummaryInformation", write_PropertySetStream(DSEntries, PSCLSID.DSI, DocSummaryRE, DocSummaryPIDDSI, CEntries2.length ? CEntries2 : null, PSCLSID.UDI));
  24450. }
  24451. function parse_xlscfb(cfb, options) {
  24452. if(!options) options = {};
  24453. fix_read_opts(options);
  24454. reset_cp();
  24455. if(options.codepage) set_ansi(options.codepage);
  24456. var CompObj, WB;
  24457. if(cfb.FullPaths) {
  24458. if(CFB.find(cfb, '/encryption')) throw new Error("File is password-protected");
  24459. CompObj = CFB.find(cfb, '!CompObj');
  24460. WB = CFB.find(cfb, '/Workbook') || CFB.find(cfb, '/Book');
  24461. } else {
  24462. switch(options.type) {
  24463. case 'base64': cfb = s2a(Base64.decode(cfb)); break;
  24464. case 'binary': cfb = s2a(cfb); break;
  24465. case 'buffer': break;
  24466. case 'array': if(!Array.isArray(cfb)) cfb = Array.prototype.slice.call(cfb); break;
  24467. }
  24468. prep_blob(cfb, 0);
  24469. WB = ({content: cfb});
  24470. }
  24471. var WorkbookP;
  24472. var _data;
  24473. if(CompObj) parse_compobj(CompObj);
  24474. if(options.bookProps && !options.bookSheets) WorkbookP = ({});
  24475. else {
  24476. var T = has_buf ? 'buffer' : 'array';
  24477. if(WB && WB.content) WorkbookP = parse_workbook(WB.content, options);
  24478. /* Quattro Pro 7-8 */
  24479. else if((_data=CFB.find(cfb, 'PerfectOffice_MAIN')) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T, options));
  24480. /* Quattro Pro 9 */
  24481. else if((_data=CFB.find(cfb, 'NativeContent_MAIN')) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T, options));
  24482. else throw new Error("Cannot find Workbook stream");
  24483. if(options.bookVBA && cfb.FullPaths && CFB.find(cfb, '/_VBA_PROJECT_CUR/VBA/dir')) WorkbookP.vbaraw = make_vba_xls(cfb);
  24484. }
  24485. var props = {};
  24486. if(cfb.FullPaths) parse_xls_props(cfb, props, options);
  24487. WorkbookP.Props = WorkbookP.Custprops = props; /* TODO: split up properties */
  24488. if(options.bookFiles) WorkbookP.cfb = cfb;
  24489. /*WorkbookP.CompObjP = CompObjP; // TODO: storage? */
  24490. return WorkbookP;
  24491. }
  24492. function write_xlscfb(wb, opts) {
  24493. var o = opts || {};
  24494. var cfb = CFB.utils.cfb_new({root:"R"});
  24495. var wbpath = "/Workbook";
  24496. switch(o.bookType || "xls") {
  24497. case "xls": o.bookType = "biff8";
  24498. /* falls through */
  24499. case "xla": if(!o.bookType) o.bookType = "xla";
  24500. /* falls through */
  24501. case "biff8": wbpath = "/Workbook"; o.biff = 8; break;
  24502. case "biff5": wbpath = "/Book"; o.biff = 5; break;
  24503. default: throw new Error("invalid type " + o.bookType + " for XLS CFB");
  24504. }
  24505. CFB.utils.cfb_add(cfb, wbpath, write_biff_buf(wb, o));
  24506. if(o.biff == 8 && (wb.Props || wb.Custprops)) write_xls_props(wb, cfb);
  24507. // TODO: SI, DSI, CO
  24508. if(o.biff == 8 && wb.vbaraw) fill_vba_xls(cfb, CFB.read(wb.vbaraw, {type: typeof wb.vbaraw == "string" ? "binary" : "buffer"}));
  24509. return cfb;
  24510. }
  24511. /* [MS-XLSB] 2.3 Record Enumeration */
  24512. var XLSBRecordEnum = {
  24513. 0x0000: { n:"BrtRowHdr", f:parse_BrtRowHdr },
  24514. 0x0001: { n:"BrtCellBlank", f:parse_BrtCellBlank },
  24515. 0x0002: { n:"BrtCellRk", f:parse_BrtCellRk },
  24516. 0x0003: { n:"BrtCellError", f:parse_BrtCellError },
  24517. 0x0004: { n:"BrtCellBool", f:parse_BrtCellBool },
  24518. 0x0005: { n:"BrtCellReal", f:parse_BrtCellReal },
  24519. 0x0006: { n:"BrtCellSt", f:parse_BrtCellSt },
  24520. 0x0007: { n:"BrtCellIsst", f:parse_BrtCellIsst },
  24521. 0x0008: { n:"BrtFmlaString", f:parse_BrtFmlaString },
  24522. 0x0009: { n:"BrtFmlaNum", f:parse_BrtFmlaNum },
  24523. 0x000A: { n:"BrtFmlaBool", f:parse_BrtFmlaBool },
  24524. 0x000B: { n:"BrtFmlaError", f:parse_BrtFmlaError },
  24525. 0x0010: { n:"BrtFRTArchID$", f:parse_BrtFRTArchID$ },
  24526. 0x0013: { n:"BrtSSTItem", f:parse_RichStr },
  24527. 0x0014: { n:"BrtPCDIMissing" },
  24528. 0x0015: { n:"BrtPCDINumber" },
  24529. 0x0016: { n:"BrtPCDIBoolean" },
  24530. 0x0017: { n:"BrtPCDIError" },
  24531. 0x0018: { n:"BrtPCDIString" },
  24532. 0x0019: { n:"BrtPCDIDatetime" },
  24533. 0x001A: { n:"BrtPCDIIndex" },
  24534. 0x001B: { n:"BrtPCDIAMissing" },
  24535. 0x001C: { n:"BrtPCDIANumber" },
  24536. 0x001D: { n:"BrtPCDIABoolean" },
  24537. 0x001E: { n:"BrtPCDIAError" },
  24538. 0x001F: { n:"BrtPCDIAString" },
  24539. 0x0020: { n:"BrtPCDIADatetime" },
  24540. 0x0021: { n:"BrtPCRRecord" },
  24541. 0x0022: { n:"BrtPCRRecordDt" },
  24542. 0x0023: { n:"BrtFRTBegin" },
  24543. 0x0024: { n:"BrtFRTEnd" },
  24544. 0x0025: { n:"BrtACBegin" },
  24545. 0x0026: { n:"BrtACEnd" },
  24546. 0x0027: { n:"BrtName", f:parse_BrtName },
  24547. 0x0028: { n:"BrtIndexRowBlock" },
  24548. 0x002A: { n:"BrtIndexBlock" },
  24549. 0x002B: { n:"BrtFont", f:parse_BrtFont },
  24550. 0x002C: { n:"BrtFmt", f:parse_BrtFmt },
  24551. 0x002D: { n:"BrtFill", f:parse_BrtFill },
  24552. 0x002E: { n:"BrtBorder", f:parse_BrtBorder },
  24553. 0x002F: { n:"BrtXF", f:parse_BrtXF },
  24554. 0x0030: { n:"BrtStyle" },
  24555. 0x0031: { n:"BrtCellMeta" },
  24556. 0x0032: { n:"BrtValueMeta" },
  24557. 0x0033: { n:"BrtMdb" },
  24558. 0x0034: { n:"BrtBeginFmd" },
  24559. 0x0035: { n:"BrtEndFmd" },
  24560. 0x0036: { n:"BrtBeginMdx" },
  24561. 0x0037: { n:"BrtEndMdx" },
  24562. 0x0038: { n:"BrtBeginMdxTuple" },
  24563. 0x0039: { n:"BrtEndMdxTuple" },
  24564. 0x003A: { n:"BrtMdxMbrIstr" },
  24565. 0x003B: { n:"BrtStr" },
  24566. 0x003C: { n:"BrtColInfo", f:parse_ColInfo },
  24567. 0x003E: { n:"BrtCellRString" },
  24568. 0x003F: { n:"BrtCalcChainItem$", f:parse_BrtCalcChainItem$ },
  24569. 0x0040: { n:"BrtDVal", f:parse_BrtDVal },
  24570. 0x0041: { n:"BrtSxvcellNum" },
  24571. 0x0042: { n:"BrtSxvcellStr" },
  24572. 0x0043: { n:"BrtSxvcellBool" },
  24573. 0x0044: { n:"BrtSxvcellErr" },
  24574. 0x0045: { n:"BrtSxvcellDate" },
  24575. 0x0046: { n:"BrtSxvcellNil" },
  24576. 0x0080: { n:"BrtFileVersion" },
  24577. 0x0081: { n:"BrtBeginSheet" },
  24578. 0x0082: { n:"BrtEndSheet" },
  24579. 0x0083: { n:"BrtBeginBook", f:parsenoop, p:0 },
  24580. 0x0084: { n:"BrtEndBook" },
  24581. 0x0085: { n:"BrtBeginWsViews" },
  24582. 0x0086: { n:"BrtEndWsViews" },
  24583. 0x0087: { n:"BrtBeginBookViews" },
  24584. 0x0088: { n:"BrtEndBookViews" },
  24585. 0x0089: { n:"BrtBeginWsView", f:parse_BrtBeginWsView },
  24586. 0x008A: { n:"BrtEndWsView" },
  24587. 0x008B: { n:"BrtBeginCsViews" },
  24588. 0x008C: { n:"BrtEndCsViews" },
  24589. 0x008D: { n:"BrtBeginCsView" },
  24590. 0x008E: { n:"BrtEndCsView" },
  24591. 0x008F: { n:"BrtBeginBundleShs" },
  24592. 0x0090: { n:"BrtEndBundleShs" },
  24593. 0x0091: { n:"BrtBeginSheetData" },
  24594. 0x0092: { n:"BrtEndSheetData" },
  24595. 0x0093: { n:"BrtWsProp", f:parse_BrtWsProp },
  24596. 0x0094: { n:"BrtWsDim", f:parse_BrtWsDim, p:16 },
  24597. 0x0097: { n:"BrtPane", f:parse_BrtPane },
  24598. 0x0098: { n:"BrtSel" },
  24599. 0x0099: { n:"BrtWbProp", f:parse_BrtWbProp },
  24600. 0x009A: { n:"BrtWbFactoid" },
  24601. 0x009B: { n:"BrtFileRecover" },
  24602. 0x009C: { n:"BrtBundleSh", f:parse_BrtBundleSh },
  24603. 0x009D: { n:"BrtCalcProp" },
  24604. 0x009E: { n:"BrtBookView" },
  24605. 0x009F: { n:"BrtBeginSst", f:parse_BrtBeginSst },
  24606. 0x00A0: { n:"BrtEndSst" },
  24607. 0x00A1: { n:"BrtBeginAFilter", f:parse_UncheckedRfX },
  24608. 0x00A2: { n:"BrtEndAFilter" },
  24609. 0x00A3: { n:"BrtBeginFilterColumn" },
  24610. 0x00A4: { n:"BrtEndFilterColumn" },
  24611. 0x00A5: { n:"BrtBeginFilters" },
  24612. 0x00A6: { n:"BrtEndFilters" },
  24613. 0x00A7: { n:"BrtFilter" },
  24614. 0x00A8: { n:"BrtColorFilter" },
  24615. 0x00A9: { n:"BrtIconFilter" },
  24616. 0x00AA: { n:"BrtTop10Filter" },
  24617. 0x00AB: { n:"BrtDynamicFilter" },
  24618. 0x00AC: { n:"BrtBeginCustomFilters" },
  24619. 0x00AD: { n:"BrtEndCustomFilters" },
  24620. 0x00AE: { n:"BrtCustomFilter" },
  24621. 0x00AF: { n:"BrtAFilterDateGroupItem" },
  24622. 0x00B0: { n:"BrtMergeCell", f:parse_BrtMergeCell },
  24623. 0x00B1: { n:"BrtBeginMergeCells" },
  24624. 0x00B2: { n:"BrtEndMergeCells" },
  24625. 0x00B3: { n:"BrtBeginPivotCacheDef" },
  24626. 0x00B4: { n:"BrtEndPivotCacheDef" },
  24627. 0x00B5: { n:"BrtBeginPCDFields" },
  24628. 0x00B6: { n:"BrtEndPCDFields" },
  24629. 0x00B7: { n:"BrtBeginPCDField" },
  24630. 0x00B8: { n:"BrtEndPCDField" },
  24631. 0x00B9: { n:"BrtBeginPCDSource" },
  24632. 0x00BA: { n:"BrtEndPCDSource" },
  24633. 0x00BB: { n:"BrtBeginPCDSRange" },
  24634. 0x00BC: { n:"BrtEndPCDSRange" },
  24635. 0x00BD: { n:"BrtBeginPCDFAtbl" },
  24636. 0x00BE: { n:"BrtEndPCDFAtbl" },
  24637. 0x00BF: { n:"BrtBeginPCDIRun" },
  24638. 0x00C0: { n:"BrtEndPCDIRun" },
  24639. 0x00C1: { n:"BrtBeginPivotCacheRecords" },
  24640. 0x00C2: { n:"BrtEndPivotCacheRecords" },
  24641. 0x00C3: { n:"BrtBeginPCDHierarchies" },
  24642. 0x00C4: { n:"BrtEndPCDHierarchies" },
  24643. 0x00C5: { n:"BrtBeginPCDHierarchy" },
  24644. 0x00C6: { n:"BrtEndPCDHierarchy" },
  24645. 0x00C7: { n:"BrtBeginPCDHFieldsUsage" },
  24646. 0x00C8: { n:"BrtEndPCDHFieldsUsage" },
  24647. 0x00C9: { n:"BrtBeginExtConnection" },
  24648. 0x00CA: { n:"BrtEndExtConnection" },
  24649. 0x00CB: { n:"BrtBeginECDbProps" },
  24650. 0x00CC: { n:"BrtEndECDbProps" },
  24651. 0x00CD: { n:"BrtBeginECOlapProps" },
  24652. 0x00CE: { n:"BrtEndECOlapProps" },
  24653. 0x00CF: { n:"BrtBeginPCDSConsol" },
  24654. 0x00D0: { n:"BrtEndPCDSConsol" },
  24655. 0x00D1: { n:"BrtBeginPCDSCPages" },
  24656. 0x00D2: { n:"BrtEndPCDSCPages" },
  24657. 0x00D3: { n:"BrtBeginPCDSCPage" },
  24658. 0x00D4: { n:"BrtEndPCDSCPage" },
  24659. 0x00D5: { n:"BrtBeginPCDSCPItem" },
  24660. 0x00D6: { n:"BrtEndPCDSCPItem" },
  24661. 0x00D7: { n:"BrtBeginPCDSCSets" },
  24662. 0x00D8: { n:"BrtEndPCDSCSets" },
  24663. 0x00D9: { n:"BrtBeginPCDSCSet" },
  24664. 0x00DA: { n:"BrtEndPCDSCSet" },
  24665. 0x00DB: { n:"BrtBeginPCDFGroup" },
  24666. 0x00DC: { n:"BrtEndPCDFGroup" },
  24667. 0x00DD: { n:"BrtBeginPCDFGItems" },
  24668. 0x00DE: { n:"BrtEndPCDFGItems" },
  24669. 0x00DF: { n:"BrtBeginPCDFGRange" },
  24670. 0x00E0: { n:"BrtEndPCDFGRange" },
  24671. 0x00E1: { n:"BrtBeginPCDFGDiscrete" },
  24672. 0x00E2: { n:"BrtEndPCDFGDiscrete" },
  24673. 0x00E3: { n:"BrtBeginPCDSDTupleCache" },
  24674. 0x00E4: { n:"BrtEndPCDSDTupleCache" },
  24675. 0x00E5: { n:"BrtBeginPCDSDTCEntries" },
  24676. 0x00E6: { n:"BrtEndPCDSDTCEntries" },
  24677. 0x00E7: { n:"BrtBeginPCDSDTCEMembers" },
  24678. 0x00E8: { n:"BrtEndPCDSDTCEMembers" },
  24679. 0x00E9: { n:"BrtBeginPCDSDTCEMember" },
  24680. 0x00EA: { n:"BrtEndPCDSDTCEMember" },
  24681. 0x00EB: { n:"BrtBeginPCDSDTCQueries" },
  24682. 0x00EC: { n:"BrtEndPCDSDTCQueries" },
  24683. 0x00ED: { n:"BrtBeginPCDSDTCQuery" },
  24684. 0x00EE: { n:"BrtEndPCDSDTCQuery" },
  24685. 0x00EF: { n:"BrtBeginPCDSDTCSets" },
  24686. 0x00F0: { n:"BrtEndPCDSDTCSets" },
  24687. 0x00F1: { n:"BrtBeginPCDSDTCSet" },
  24688. 0x00F2: { n:"BrtEndPCDSDTCSet" },
  24689. 0x00F3: { n:"BrtBeginPCDCalcItems" },
  24690. 0x00F4: { n:"BrtEndPCDCalcItems" },
  24691. 0x00F5: { n:"BrtBeginPCDCalcItem" },
  24692. 0x00F6: { n:"BrtEndPCDCalcItem" },
  24693. 0x00F7: { n:"BrtBeginPRule" },
  24694. 0x00F8: { n:"BrtEndPRule" },
  24695. 0x00F9: { n:"BrtBeginPRFilters" },
  24696. 0x00FA: { n:"BrtEndPRFilters" },
  24697. 0x00FB: { n:"BrtBeginPRFilter" },
  24698. 0x00FC: { n:"BrtEndPRFilter" },
  24699. 0x00FD: { n:"BrtBeginPNames" },
  24700. 0x00FE: { n:"BrtEndPNames" },
  24701. 0x00FF: { n:"BrtBeginPName" },
  24702. 0x0100: { n:"BrtEndPName" },
  24703. 0x0101: { n:"BrtBeginPNPairs" },
  24704. 0x0102: { n:"BrtEndPNPairs" },
  24705. 0x0103: { n:"BrtBeginPNPair" },
  24706. 0x0104: { n:"BrtEndPNPair" },
  24707. 0x0105: { n:"BrtBeginECWebProps" },
  24708. 0x0106: { n:"BrtEndECWebProps" },
  24709. 0x0107: { n:"BrtBeginEcWpTables" },
  24710. 0x0108: { n:"BrtEndECWPTables" },
  24711. 0x0109: { n:"BrtBeginECParams" },
  24712. 0x010A: { n:"BrtEndECParams" },
  24713. 0x010B: { n:"BrtBeginECParam" },
  24714. 0x010C: { n:"BrtEndECParam" },
  24715. 0x010D: { n:"BrtBeginPCDKPIs" },
  24716. 0x010E: { n:"BrtEndPCDKPIs" },
  24717. 0x010F: { n:"BrtBeginPCDKPI" },
  24718. 0x0110: { n:"BrtEndPCDKPI" },
  24719. 0x0111: { n:"BrtBeginDims" },
  24720. 0x0112: { n:"BrtEndDims" },
  24721. 0x0113: { n:"BrtBeginDim" },
  24722. 0x0114: { n:"BrtEndDim" },
  24723. 0x0115: { n:"BrtIndexPartEnd" },
  24724. 0x0116: { n:"BrtBeginStyleSheet" },
  24725. 0x0117: { n:"BrtEndStyleSheet" },
  24726. 0x0118: { n:"BrtBeginSXView" },
  24727. 0x0119: { n:"BrtEndSXVI" },
  24728. 0x011A: { n:"BrtBeginSXVI" },
  24729. 0x011B: { n:"BrtBeginSXVIs" },
  24730. 0x011C: { n:"BrtEndSXVIs" },
  24731. 0x011D: { n:"BrtBeginSXVD" },
  24732. 0x011E: { n:"BrtEndSXVD" },
  24733. 0x011F: { n:"BrtBeginSXVDs" },
  24734. 0x0120: { n:"BrtEndSXVDs" },
  24735. 0x0121: { n:"BrtBeginSXPI" },
  24736. 0x0122: { n:"BrtEndSXPI" },
  24737. 0x0123: { n:"BrtBeginSXPIs" },
  24738. 0x0124: { n:"BrtEndSXPIs" },
  24739. 0x0125: { n:"BrtBeginSXDI" },
  24740. 0x0126: { n:"BrtEndSXDI" },
  24741. 0x0127: { n:"BrtBeginSXDIs" },
  24742. 0x0128: { n:"BrtEndSXDIs" },
  24743. 0x0129: { n:"BrtBeginSXLI" },
  24744. 0x012A: { n:"BrtEndSXLI" },
  24745. 0x012B: { n:"BrtBeginSXLIRws" },
  24746. 0x012C: { n:"BrtEndSXLIRws" },
  24747. 0x012D: { n:"BrtBeginSXLICols" },
  24748. 0x012E: { n:"BrtEndSXLICols" },
  24749. 0x012F: { n:"BrtBeginSXFormat" },
  24750. 0x0130: { n:"BrtEndSXFormat" },
  24751. 0x0131: { n:"BrtBeginSXFormats" },
  24752. 0x0132: { n:"BrtEndSxFormats" },
  24753. 0x0133: { n:"BrtBeginSxSelect" },
  24754. 0x0134: { n:"BrtEndSxSelect" },
  24755. 0x0135: { n:"BrtBeginISXVDRws" },
  24756. 0x0136: { n:"BrtEndISXVDRws" },
  24757. 0x0137: { n:"BrtBeginISXVDCols" },
  24758. 0x0138: { n:"BrtEndISXVDCols" },
  24759. 0x0139: { n:"BrtEndSXLocation" },
  24760. 0x013A: { n:"BrtBeginSXLocation" },
  24761. 0x013B: { n:"BrtEndSXView" },
  24762. 0x013C: { n:"BrtBeginSXTHs" },
  24763. 0x013D: { n:"BrtEndSXTHs" },
  24764. 0x013E: { n:"BrtBeginSXTH" },
  24765. 0x013F: { n:"BrtEndSXTH" },
  24766. 0x0140: { n:"BrtBeginISXTHRws" },
  24767. 0x0141: { n:"BrtEndISXTHRws" },
  24768. 0x0142: { n:"BrtBeginISXTHCols" },
  24769. 0x0143: { n:"BrtEndISXTHCols" },
  24770. 0x0144: { n:"BrtBeginSXTDMPS" },
  24771. 0x0145: { n:"BrtEndSXTDMPs" },
  24772. 0x0146: { n:"BrtBeginSXTDMP" },
  24773. 0x0147: { n:"BrtEndSXTDMP" },
  24774. 0x0148: { n:"BrtBeginSXTHItems" },
  24775. 0x0149: { n:"BrtEndSXTHItems" },
  24776. 0x014A: { n:"BrtBeginSXTHItem" },
  24777. 0x014B: { n:"BrtEndSXTHItem" },
  24778. 0x014C: { n:"BrtBeginMetadata" },
  24779. 0x014D: { n:"BrtEndMetadata" },
  24780. 0x014E: { n:"BrtBeginEsmdtinfo" },
  24781. 0x014F: { n:"BrtMdtinfo" },
  24782. 0x0150: { n:"BrtEndEsmdtinfo" },
  24783. 0x0151: { n:"BrtBeginEsmdb" },
  24784. 0x0152: { n:"BrtEndEsmdb" },
  24785. 0x0153: { n:"BrtBeginEsfmd" },
  24786. 0x0154: { n:"BrtEndEsfmd" },
  24787. 0x0155: { n:"BrtBeginSingleCells" },
  24788. 0x0156: { n:"BrtEndSingleCells" },
  24789. 0x0157: { n:"BrtBeginList" },
  24790. 0x0158: { n:"BrtEndList" },
  24791. 0x0159: { n:"BrtBeginListCols" },
  24792. 0x015A: { n:"BrtEndListCols" },
  24793. 0x015B: { n:"BrtBeginListCol" },
  24794. 0x015C: { n:"BrtEndListCol" },
  24795. 0x015D: { n:"BrtBeginListXmlCPr" },
  24796. 0x015E: { n:"BrtEndListXmlCPr" },
  24797. 0x015F: { n:"BrtListCCFmla" },
  24798. 0x0160: { n:"BrtListTrFmla" },
  24799. 0x0161: { n:"BrtBeginExternals" },
  24800. 0x0162: { n:"BrtEndExternals" },
  24801. 0x0163: { n:"BrtSupBookSrc", f:parse_RelID},
  24802. 0x0165: { n:"BrtSupSelf" },
  24803. 0x0166: { n:"BrtSupSame" },
  24804. 0x0167: { n:"BrtSupTabs" },
  24805. 0x0168: { n:"BrtBeginSupBook" },
  24806. 0x0169: { n:"BrtPlaceholderName" },
  24807. 0x016A: { n:"BrtExternSheet", f:parse_ExternSheet },
  24808. 0x016B: { n:"BrtExternTableStart" },
  24809. 0x016C: { n:"BrtExternTableEnd" },
  24810. 0x016E: { n:"BrtExternRowHdr" },
  24811. 0x016F: { n:"BrtExternCellBlank" },
  24812. 0x0170: { n:"BrtExternCellReal" },
  24813. 0x0171: { n:"BrtExternCellBool" },
  24814. 0x0172: { n:"BrtExternCellError" },
  24815. 0x0173: { n:"BrtExternCellString" },
  24816. 0x0174: { n:"BrtBeginEsmdx" },
  24817. 0x0175: { n:"BrtEndEsmdx" },
  24818. 0x0176: { n:"BrtBeginMdxSet" },
  24819. 0x0177: { n:"BrtEndMdxSet" },
  24820. 0x0178: { n:"BrtBeginMdxMbrProp" },
  24821. 0x0179: { n:"BrtEndMdxMbrProp" },
  24822. 0x017A: { n:"BrtBeginMdxKPI" },
  24823. 0x017B: { n:"BrtEndMdxKPI" },
  24824. 0x017C: { n:"BrtBeginEsstr" },
  24825. 0x017D: { n:"BrtEndEsstr" },
  24826. 0x017E: { n:"BrtBeginPRFItem" },
  24827. 0x017F: { n:"BrtEndPRFItem" },
  24828. 0x0180: { n:"BrtBeginPivotCacheIDs" },
  24829. 0x0181: { n:"BrtEndPivotCacheIDs" },
  24830. 0x0182: { n:"BrtBeginPivotCacheID" },
  24831. 0x0183: { n:"BrtEndPivotCacheID" },
  24832. 0x0184: { n:"BrtBeginISXVIs" },
  24833. 0x0185: { n:"BrtEndISXVIs" },
  24834. 0x0186: { n:"BrtBeginColInfos" },
  24835. 0x0187: { n:"BrtEndColInfos" },
  24836. 0x0188: { n:"BrtBeginRwBrk" },
  24837. 0x0189: { n:"BrtEndRwBrk" },
  24838. 0x018A: { n:"BrtBeginColBrk" },
  24839. 0x018B: { n:"BrtEndColBrk" },
  24840. 0x018C: { n:"BrtBrk" },
  24841. 0x018D: { n:"BrtUserBookView" },
  24842. 0x018E: { n:"BrtInfo" },
  24843. 0x018F: { n:"BrtCUsr" },
  24844. 0x0190: { n:"BrtUsr" },
  24845. 0x0191: { n:"BrtBeginUsers" },
  24846. 0x0193: { n:"BrtEOF" },
  24847. 0x0194: { n:"BrtUCR" },
  24848. 0x0195: { n:"BrtRRInsDel" },
  24849. 0x0196: { n:"BrtRREndInsDel" },
  24850. 0x0197: { n:"BrtRRMove" },
  24851. 0x0198: { n:"BrtRREndMove" },
  24852. 0x0199: { n:"BrtRRChgCell" },
  24853. 0x019A: { n:"BrtRREndChgCell" },
  24854. 0x019B: { n:"BrtRRHeader" },
  24855. 0x019C: { n:"BrtRRUserView" },
  24856. 0x019D: { n:"BrtRRRenSheet" },
  24857. 0x019E: { n:"BrtRRInsertSh" },
  24858. 0x019F: { n:"BrtRRDefName" },
  24859. 0x01A0: { n:"BrtRRNote" },
  24860. 0x01A1: { n:"BrtRRConflict" },
  24861. 0x01A2: { n:"BrtRRTQSIF" },
  24862. 0x01A3: { n:"BrtRRFormat" },
  24863. 0x01A4: { n:"BrtRREndFormat" },
  24864. 0x01A5: { n:"BrtRRAutoFmt" },
  24865. 0x01A6: { n:"BrtBeginUserShViews" },
  24866. 0x01A7: { n:"BrtBeginUserShView" },
  24867. 0x01A8: { n:"BrtEndUserShView" },
  24868. 0x01A9: { n:"BrtEndUserShViews" },
  24869. 0x01AA: { n:"BrtArrFmla", f:parse_BrtArrFmla },
  24870. 0x01AB: { n:"BrtShrFmla", f:parse_BrtShrFmla },
  24871. 0x01AC: { n:"BrtTable" },
  24872. 0x01AD: { n:"BrtBeginExtConnections" },
  24873. 0x01AE: { n:"BrtEndExtConnections" },
  24874. 0x01AF: { n:"BrtBeginPCDCalcMems" },
  24875. 0x01B0: { n:"BrtEndPCDCalcMems" },
  24876. 0x01B1: { n:"BrtBeginPCDCalcMem" },
  24877. 0x01B2: { n:"BrtEndPCDCalcMem" },
  24878. 0x01B3: { n:"BrtBeginPCDHGLevels" },
  24879. 0x01B4: { n:"BrtEndPCDHGLevels" },
  24880. 0x01B5: { n:"BrtBeginPCDHGLevel" },
  24881. 0x01B6: { n:"BrtEndPCDHGLevel" },
  24882. 0x01B7: { n:"BrtBeginPCDHGLGroups" },
  24883. 0x01B8: { n:"BrtEndPCDHGLGroups" },
  24884. 0x01B9: { n:"BrtBeginPCDHGLGroup" },
  24885. 0x01BA: { n:"BrtEndPCDHGLGroup" },
  24886. 0x01BB: { n:"BrtBeginPCDHGLGMembers" },
  24887. 0x01BC: { n:"BrtEndPCDHGLGMembers" },
  24888. 0x01BD: { n:"BrtBeginPCDHGLGMember" },
  24889. 0x01BE: { n:"BrtEndPCDHGLGMember" },
  24890. 0x01BF: { n:"BrtBeginQSI" },
  24891. 0x01C0: { n:"BrtEndQSI" },
  24892. 0x01C1: { n:"BrtBeginQSIR" },
  24893. 0x01C2: { n:"BrtEndQSIR" },
  24894. 0x01C3: { n:"BrtBeginDeletedNames" },
  24895. 0x01C4: { n:"BrtEndDeletedNames" },
  24896. 0x01C5: { n:"BrtBeginDeletedName" },
  24897. 0x01C6: { n:"BrtEndDeletedName" },
  24898. 0x01C7: { n:"BrtBeginQSIFs" },
  24899. 0x01C8: { n:"BrtEndQSIFs" },
  24900. 0x01C9: { n:"BrtBeginQSIF" },
  24901. 0x01CA: { n:"BrtEndQSIF" },
  24902. 0x01CB: { n:"BrtBeginAutoSortScope" },
  24903. 0x01CC: { n:"BrtEndAutoSortScope" },
  24904. 0x01CD: { n:"BrtBeginConditionalFormatting" },
  24905. 0x01CE: { n:"BrtEndConditionalFormatting" },
  24906. 0x01CF: { n:"BrtBeginCFRule" },
  24907. 0x01D0: { n:"BrtEndCFRule" },
  24908. 0x01D1: { n:"BrtBeginIconSet" },
  24909. 0x01D2: { n:"BrtEndIconSet" },
  24910. 0x01D3: { n:"BrtBeginDatabar" },
  24911. 0x01D4: { n:"BrtEndDatabar" },
  24912. 0x01D5: { n:"BrtBeginColorScale" },
  24913. 0x01D6: { n:"BrtEndColorScale" },
  24914. 0x01D7: { n:"BrtCFVO" },
  24915. 0x01D8: { n:"BrtExternValueMeta" },
  24916. 0x01D9: { n:"BrtBeginColorPalette" },
  24917. 0x01DA: { n:"BrtEndColorPalette" },
  24918. 0x01DB: { n:"BrtIndexedColor" },
  24919. 0x01DC: { n:"BrtMargins", f:parse_BrtMargins },
  24920. 0x01DD: { n:"BrtPrintOptions" },
  24921. 0x01DE: { n:"BrtPageSetup" },
  24922. 0x01DF: { n:"BrtBeginHeaderFooter" },
  24923. 0x01E0: { n:"BrtEndHeaderFooter" },
  24924. 0x01E1: { n:"BrtBeginSXCrtFormat" },
  24925. 0x01E2: { n:"BrtEndSXCrtFormat" },
  24926. 0x01E3: { n:"BrtBeginSXCrtFormats" },
  24927. 0x01E4: { n:"BrtEndSXCrtFormats" },
  24928. 0x01E5: { n:"BrtWsFmtInfo", f:parse_BrtWsFmtInfo },
  24929. 0x01E6: { n:"BrtBeginMgs" },
  24930. 0x01E7: { n:"BrtEndMGs" },
  24931. 0x01E8: { n:"BrtBeginMGMaps" },
  24932. 0x01E9: { n:"BrtEndMGMaps" },
  24933. 0x01EA: { n:"BrtBeginMG" },
  24934. 0x01EB: { n:"BrtEndMG" },
  24935. 0x01EC: { n:"BrtBeginMap" },
  24936. 0x01ED: { n:"BrtEndMap" },
  24937. 0x01EE: { n:"BrtHLink", f:parse_BrtHLink },
  24938. 0x01EF: { n:"BrtBeginDCon" },
  24939. 0x01F0: { n:"BrtEndDCon" },
  24940. 0x01F1: { n:"BrtBeginDRefs" },
  24941. 0x01F2: { n:"BrtEndDRefs" },
  24942. 0x01F3: { n:"BrtDRef" },
  24943. 0x01F4: { n:"BrtBeginScenMan" },
  24944. 0x01F5: { n:"BrtEndScenMan" },
  24945. 0x01F6: { n:"BrtBeginSct" },
  24946. 0x01F7: { n:"BrtEndSct" },
  24947. 0x01F8: { n:"BrtSlc" },
  24948. 0x01F9: { n:"BrtBeginDXFs" },
  24949. 0x01FA: { n:"BrtEndDXFs" },
  24950. 0x01FB: { n:"BrtDXF" },
  24951. 0x01FC: { n:"BrtBeginTableStyles" },
  24952. 0x01FD: { n:"BrtEndTableStyles" },
  24953. 0x01FE: { n:"BrtBeginTableStyle" },
  24954. 0x01FF: { n:"BrtEndTableStyle" },
  24955. 0x0200: { n:"BrtTableStyleElement" },
  24956. 0x0201: { n:"BrtTableStyleClient" },
  24957. 0x0202: { n:"BrtBeginVolDeps" },
  24958. 0x0203: { n:"BrtEndVolDeps" },
  24959. 0x0204: { n:"BrtBeginVolType" },
  24960. 0x0205: { n:"BrtEndVolType" },
  24961. 0x0206: { n:"BrtBeginVolMain" },
  24962. 0x0207: { n:"BrtEndVolMain" },
  24963. 0x0208: { n:"BrtBeginVolTopic" },
  24964. 0x0209: { n:"BrtEndVolTopic" },
  24965. 0x020A: { n:"BrtVolSubtopic" },
  24966. 0x020B: { n:"BrtVolRef" },
  24967. 0x020C: { n:"BrtVolNum" },
  24968. 0x020D: { n:"BrtVolErr" },
  24969. 0x020E: { n:"BrtVolStr" },
  24970. 0x020F: { n:"BrtVolBool" },
  24971. 0x0210: { n:"BrtBeginCalcChain$" },
  24972. 0x0211: { n:"BrtEndCalcChain$" },
  24973. 0x0212: { n:"BrtBeginSortState" },
  24974. 0x0213: { n:"BrtEndSortState" },
  24975. 0x0214: { n:"BrtBeginSortCond" },
  24976. 0x0215: { n:"BrtEndSortCond" },
  24977. 0x0216: { n:"BrtBookProtection" },
  24978. 0x0217: { n:"BrtSheetProtection" },
  24979. 0x0218: { n:"BrtRangeProtection" },
  24980. 0x0219: { n:"BrtPhoneticInfo" },
  24981. 0x021A: { n:"BrtBeginECTxtWiz" },
  24982. 0x021B: { n:"BrtEndECTxtWiz" },
  24983. 0x021C: { n:"BrtBeginECTWFldInfoLst" },
  24984. 0x021D: { n:"BrtEndECTWFldInfoLst" },
  24985. 0x021E: { n:"BrtBeginECTwFldInfo" },
  24986. 0x0224: { n:"BrtFileSharing" },
  24987. 0x0225: { n:"BrtOleSize" },
  24988. 0x0226: { n:"BrtDrawing", f:parse_RelID },
  24989. 0x0227: { n:"BrtLegacyDrawing" },
  24990. 0x0228: { n:"BrtLegacyDrawingHF" },
  24991. 0x0229: { n:"BrtWebOpt" },
  24992. 0x022A: { n:"BrtBeginWebPubItems" },
  24993. 0x022B: { n:"BrtEndWebPubItems" },
  24994. 0x022C: { n:"BrtBeginWebPubItem" },
  24995. 0x022D: { n:"BrtEndWebPubItem" },
  24996. 0x022E: { n:"BrtBeginSXCondFmt" },
  24997. 0x022F: { n:"BrtEndSXCondFmt" },
  24998. 0x0230: { n:"BrtBeginSXCondFmts" },
  24999. 0x0231: { n:"BrtEndSXCondFmts" },
  25000. 0x0232: { n:"BrtBkHim" },
  25001. 0x0234: { n:"BrtColor" },
  25002. 0x0235: { n:"BrtBeginIndexedColors" },
  25003. 0x0236: { n:"BrtEndIndexedColors" },
  25004. 0x0239: { n:"BrtBeginMRUColors" },
  25005. 0x023A: { n:"BrtEndMRUColors" },
  25006. 0x023C: { n:"BrtMRUColor" },
  25007. 0x023D: { n:"BrtBeginDVals" },
  25008. 0x023E: { n:"BrtEndDVals" },
  25009. 0x0241: { n:"BrtSupNameStart" },
  25010. 0x0242: { n:"BrtSupNameValueStart" },
  25011. 0x0243: { n:"BrtSupNameValueEnd" },
  25012. 0x0244: { n:"BrtSupNameNum" },
  25013. 0x0245: { n:"BrtSupNameErr" },
  25014. 0x0246: { n:"BrtSupNameSt" },
  25015. 0x0247: { n:"BrtSupNameNil" },
  25016. 0x0248: { n:"BrtSupNameBool" },
  25017. 0x0249: { n:"BrtSupNameFmla" },
  25018. 0x024A: { n:"BrtSupNameBits" },
  25019. 0x024B: { n:"BrtSupNameEnd" },
  25020. 0x024C: { n:"BrtEndSupBook" },
  25021. 0x024D: { n:"BrtCellSmartTagProperty" },
  25022. 0x024E: { n:"BrtBeginCellSmartTag" },
  25023. 0x024F: { n:"BrtEndCellSmartTag" },
  25024. 0x0250: { n:"BrtBeginCellSmartTags" },
  25025. 0x0251: { n:"BrtEndCellSmartTags" },
  25026. 0x0252: { n:"BrtBeginSmartTags" },
  25027. 0x0253: { n:"BrtEndSmartTags" },
  25028. 0x0254: { n:"BrtSmartTagType" },
  25029. 0x0255: { n:"BrtBeginSmartTagTypes" },
  25030. 0x0256: { n:"BrtEndSmartTagTypes" },
  25031. 0x0257: { n:"BrtBeginSXFilters" },
  25032. 0x0258: { n:"BrtEndSXFilters" },
  25033. 0x0259: { n:"BrtBeginSXFILTER" },
  25034. 0x025A: { n:"BrtEndSXFilter" },
  25035. 0x025B: { n:"BrtBeginFills" },
  25036. 0x025C: { n:"BrtEndFills" },
  25037. 0x025D: { n:"BrtBeginCellWatches" },
  25038. 0x025E: { n:"BrtEndCellWatches" },
  25039. 0x025F: { n:"BrtCellWatch" },
  25040. 0x0260: { n:"BrtBeginCRErrs" },
  25041. 0x0261: { n:"BrtEndCRErrs" },
  25042. 0x0262: { n:"BrtCrashRecErr" },
  25043. 0x0263: { n:"BrtBeginFonts" },
  25044. 0x0264: { n:"BrtEndFonts" },
  25045. 0x0265: { n:"BrtBeginBorders" },
  25046. 0x0266: { n:"BrtEndBorders" },
  25047. 0x0267: { n:"BrtBeginFmts" },
  25048. 0x0268: { n:"BrtEndFmts" },
  25049. 0x0269: { n:"BrtBeginCellXFs" },
  25050. 0x026A: { n:"BrtEndCellXFs" },
  25051. 0x026B: { n:"BrtBeginStyles" },
  25052. 0x026C: { n:"BrtEndStyles" },
  25053. 0x0271: { n:"BrtBigName" },
  25054. 0x0272: { n:"BrtBeginCellStyleXFs" },
  25055. 0x0273: { n:"BrtEndCellStyleXFs" },
  25056. 0x0274: { n:"BrtBeginComments" },
  25057. 0x0275: { n:"BrtEndComments" },
  25058. 0x0276: { n:"BrtBeginCommentAuthors" },
  25059. 0x0277: { n:"BrtEndCommentAuthors" },
  25060. 0x0278: { n:"BrtCommentAuthor", f:parse_BrtCommentAuthor },
  25061. 0x0279: { n:"BrtBeginCommentList" },
  25062. 0x027A: { n:"BrtEndCommentList" },
  25063. 0x027B: { n:"BrtBeginComment", f:parse_BrtBeginComment},
  25064. 0x027C: { n:"BrtEndComment" },
  25065. 0x027D: { n:"BrtCommentText", f:parse_BrtCommentText },
  25066. 0x027E: { n:"BrtBeginOleObjects" },
  25067. 0x027F: { n:"BrtOleObject" },
  25068. 0x0280: { n:"BrtEndOleObjects" },
  25069. 0x0281: { n:"BrtBeginSxrules" },
  25070. 0x0282: { n:"BrtEndSxRules" },
  25071. 0x0283: { n:"BrtBeginActiveXControls" },
  25072. 0x0284: { n:"BrtActiveX" },
  25073. 0x0285: { n:"BrtEndActiveXControls" },
  25074. 0x0286: { n:"BrtBeginPCDSDTCEMembersSortBy" },
  25075. 0x0288: { n:"BrtBeginCellIgnoreECs" },
  25076. 0x0289: { n:"BrtCellIgnoreEC" },
  25077. 0x028A: { n:"BrtEndCellIgnoreECs" },
  25078. 0x028B: { n:"BrtCsProp", f:parse_BrtCsProp },
  25079. 0x028C: { n:"BrtCsPageSetup" },
  25080. 0x028D: { n:"BrtBeginUserCsViews" },
  25081. 0x028E: { n:"BrtEndUserCsViews" },
  25082. 0x028F: { n:"BrtBeginUserCsView" },
  25083. 0x0290: { n:"BrtEndUserCsView" },
  25084. 0x0291: { n:"BrtBeginPcdSFCIEntries" },
  25085. 0x0292: { n:"BrtEndPCDSFCIEntries" },
  25086. 0x0293: { n:"BrtPCDSFCIEntry" },
  25087. 0x0294: { n:"BrtBeginListParts" },
  25088. 0x0295: { n:"BrtListPart" },
  25089. 0x0296: { n:"BrtEndListParts" },
  25090. 0x0297: { n:"BrtSheetCalcProp" },
  25091. 0x0298: { n:"BrtBeginFnGroup" },
  25092. 0x0299: { n:"BrtFnGroup" },
  25093. 0x029A: { n:"BrtEndFnGroup" },
  25094. 0x029B: { n:"BrtSupAddin" },
  25095. 0x029C: { n:"BrtSXTDMPOrder" },
  25096. 0x029D: { n:"BrtCsProtection" },
  25097. 0x029F: { n:"BrtBeginWsSortMap" },
  25098. 0x02A0: { n:"BrtEndWsSortMap" },
  25099. 0x02A1: { n:"BrtBeginRRSort" },
  25100. 0x02A2: { n:"BrtEndRRSort" },
  25101. 0x02A3: { n:"BrtRRSortItem" },
  25102. 0x02A4: { n:"BrtFileSharingIso" },
  25103. 0x02A5: { n:"BrtBookProtectionIso" },
  25104. 0x02A6: { n:"BrtSheetProtectionIso" },
  25105. 0x02A7: { n:"BrtCsProtectionIso" },
  25106. 0x02A8: { n:"BrtRangeProtectionIso" },
  25107. 0x02A9: { n:"BrtDValList" },
  25108. 0x0400: { n:"BrtRwDescent" },
  25109. 0x0401: { n:"BrtKnownFonts" },
  25110. 0x0402: { n:"BrtBeginSXTupleSet" },
  25111. 0x0403: { n:"BrtEndSXTupleSet" },
  25112. 0x0404: { n:"BrtBeginSXTupleSetHeader" },
  25113. 0x0405: { n:"BrtEndSXTupleSetHeader" },
  25114. 0x0406: { n:"BrtSXTupleSetHeaderItem" },
  25115. 0x0407: { n:"BrtBeginSXTupleSetData" },
  25116. 0x0408: { n:"BrtEndSXTupleSetData" },
  25117. 0x0409: { n:"BrtBeginSXTupleSetRow" },
  25118. 0x040A: { n:"BrtEndSXTupleSetRow" },
  25119. 0x040B: { n:"BrtSXTupleSetRowItem" },
  25120. 0x040C: { n:"BrtNameExt" },
  25121. 0x040D: { n:"BrtPCDH14" },
  25122. 0x040E: { n:"BrtBeginPCDCalcMem14" },
  25123. 0x040F: { n:"BrtEndPCDCalcMem14" },
  25124. 0x0410: { n:"BrtSXTH14" },
  25125. 0x0411: { n:"BrtBeginSparklineGroup" },
  25126. 0x0412: { n:"BrtEndSparklineGroup" },
  25127. 0x0413: { n:"BrtSparkline" },
  25128. 0x0414: { n:"BrtSXDI14" },
  25129. 0x0415: { n:"BrtWsFmtInfoEx14" },
  25130. 0x0416: { n:"BrtBeginConditionalFormatting14" },
  25131. 0x0417: { n:"BrtEndConditionalFormatting14" },
  25132. 0x0418: { n:"BrtBeginCFRule14" },
  25133. 0x0419: { n:"BrtEndCFRule14" },
  25134. 0x041A: { n:"BrtCFVO14" },
  25135. 0x041B: { n:"BrtBeginDatabar14" },
  25136. 0x041C: { n:"BrtBeginIconSet14" },
  25137. 0x041D: { n:"BrtDVal14", f: parse_BrtDVal14 },
  25138. 0x041E: { n:"BrtBeginDVals14" },
  25139. 0x041F: { n:"BrtColor14" },
  25140. 0x0420: { n:"BrtBeginSparklines" },
  25141. 0x0421: { n:"BrtEndSparklines" },
  25142. 0x0422: { n:"BrtBeginSparklineGroups" },
  25143. 0x0423: { n:"BrtEndSparklineGroups" },
  25144. 0x0425: { n:"BrtSXVD14" },
  25145. 0x0426: { n:"BrtBeginSXView14" },
  25146. 0x0427: { n:"BrtEndSXView14" },
  25147. 0x0428: { n:"BrtBeginSXView16" },
  25148. 0x0429: { n:"BrtEndSXView16" },
  25149. 0x042A: { n:"BrtBeginPCD14" },
  25150. 0x042B: { n:"BrtEndPCD14" },
  25151. 0x042C: { n:"BrtBeginExtConn14" },
  25152. 0x042D: { n:"BrtEndExtConn14" },
  25153. 0x042E: { n:"BrtBeginSlicerCacheIDs" },
  25154. 0x042F: { n:"BrtEndSlicerCacheIDs" },
  25155. 0x0430: { n:"BrtBeginSlicerCacheID" },
  25156. 0x0431: { n:"BrtEndSlicerCacheID" },
  25157. 0x0433: { n:"BrtBeginSlicerCache" },
  25158. 0x0434: { n:"BrtEndSlicerCache" },
  25159. 0x0435: { n:"BrtBeginSlicerCacheDef" },
  25160. 0x0436: { n:"BrtEndSlicerCacheDef" },
  25161. 0x0437: { n:"BrtBeginSlicersEx" },
  25162. 0x0438: { n:"BrtEndSlicersEx" },
  25163. 0x0439: { n:"BrtBeginSlicerEx" },
  25164. 0x043A: { n:"BrtEndSlicerEx" },
  25165. 0x043B: { n:"BrtBeginSlicer" },
  25166. 0x043C: { n:"BrtEndSlicer" },
  25167. 0x043D: { n:"BrtSlicerCachePivotTables" },
  25168. 0x043E: { n:"BrtBeginSlicerCacheOlapImpl" },
  25169. 0x043F: { n:"BrtEndSlicerCacheOlapImpl" },
  25170. 0x0440: { n:"BrtBeginSlicerCacheLevelsData" },
  25171. 0x0441: { n:"BrtEndSlicerCacheLevelsData" },
  25172. 0x0442: { n:"BrtBeginSlicerCacheLevelData" },
  25173. 0x0443: { n:"BrtEndSlicerCacheLevelData" },
  25174. 0x0444: { n:"BrtBeginSlicerCacheSiRanges" },
  25175. 0x0445: { n:"BrtEndSlicerCacheSiRanges" },
  25176. 0x0446: { n:"BrtBeginSlicerCacheSiRange" },
  25177. 0x0447: { n:"BrtEndSlicerCacheSiRange" },
  25178. 0x0448: { n:"BrtSlicerCacheOlapItem" },
  25179. 0x0449: { n:"BrtBeginSlicerCacheSelections" },
  25180. 0x044A: { n:"BrtSlicerCacheSelection" },
  25181. 0x044B: { n:"BrtEndSlicerCacheSelections" },
  25182. 0x044C: { n:"BrtBeginSlicerCacheNative" },
  25183. 0x044D: { n:"BrtEndSlicerCacheNative" },
  25184. 0x044E: { n:"BrtSlicerCacheNativeItem" },
  25185. 0x044F: { n:"BrtRangeProtection14" },
  25186. 0x0450: { n:"BrtRangeProtectionIso14" },
  25187. 0x0451: { n:"BrtCellIgnoreEC14" },
  25188. 0x0457: { n:"BrtList14" },
  25189. 0x0458: { n:"BrtCFIcon" },
  25190. 0x0459: { n:"BrtBeginSlicerCachesPivotCacheIDs" },
  25191. 0x045A: { n:"BrtEndSlicerCachesPivotCacheIDs" },
  25192. 0x045B: { n:"BrtBeginSlicers" },
  25193. 0x045C: { n:"BrtEndSlicers" },
  25194. 0x045D: { n:"BrtWbProp14" },
  25195. 0x045E: { n:"BrtBeginSXEdit" },
  25196. 0x045F: { n:"BrtEndSXEdit" },
  25197. 0x0460: { n:"BrtBeginSXEdits" },
  25198. 0x0461: { n:"BrtEndSXEdits" },
  25199. 0x0462: { n:"BrtBeginSXChange" },
  25200. 0x0463: { n:"BrtEndSXChange" },
  25201. 0x0464: { n:"BrtBeginSXChanges" },
  25202. 0x0465: { n:"BrtEndSXChanges" },
  25203. 0x0466: { n:"BrtSXTupleItems" },
  25204. 0x0468: { n:"BrtBeginSlicerStyle" },
  25205. 0x0469: { n:"BrtEndSlicerStyle" },
  25206. 0x046A: { n:"BrtSlicerStyleElement" },
  25207. 0x046B: { n:"BrtBeginStyleSheetExt14" },
  25208. 0x046C: { n:"BrtEndStyleSheetExt14" },
  25209. 0x046D: { n:"BrtBeginSlicerCachesPivotCacheID" },
  25210. 0x046E: { n:"BrtEndSlicerCachesPivotCacheID" },
  25211. 0x046F: { n:"BrtBeginConditionalFormattings" },
  25212. 0x0470: { n:"BrtEndConditionalFormattings" },
  25213. 0x0471: { n:"BrtBeginPCDCalcMemExt" },
  25214. 0x0472: { n:"BrtEndPCDCalcMemExt" },
  25215. 0x0473: { n:"BrtBeginPCDCalcMemsExt" },
  25216. 0x0474: { n:"BrtEndPCDCalcMemsExt" },
  25217. 0x0475: { n:"BrtPCDField14" },
  25218. 0x0476: { n:"BrtBeginSlicerStyles" },
  25219. 0x0477: { n:"BrtEndSlicerStyles" },
  25220. 0x0478: { n:"BrtBeginSlicerStyleElements" },
  25221. 0x0479: { n:"BrtEndSlicerStyleElements" },
  25222. 0x047A: { n:"BrtCFRuleExt" },
  25223. 0x047B: { n:"BrtBeginSXCondFmt14" },
  25224. 0x047C: { n:"BrtEndSXCondFmt14" },
  25225. 0x047D: { n:"BrtBeginSXCondFmts14" },
  25226. 0x047E: { n:"BrtEndSXCondFmts14" },
  25227. 0x0480: { n:"BrtBeginSortCond14" },
  25228. 0x0481: { n:"BrtEndSortCond14" },
  25229. 0x0482: { n:"BrtEndDVals14" },
  25230. 0x0483: { n:"BrtEndIconSet14" },
  25231. 0x0484: { n:"BrtEndDatabar14" },
  25232. 0x0485: { n:"BrtBeginColorScale14" },
  25233. 0x0486: { n:"BrtEndColorScale14" },
  25234. 0x0487: { n:"BrtBeginSxrules14" },
  25235. 0x0488: { n:"BrtEndSxrules14" },
  25236. 0x0489: { n:"BrtBeginPRule14" },
  25237. 0x048A: { n:"BrtEndPRule14" },
  25238. 0x048B: { n:"BrtBeginPRFilters14" },
  25239. 0x048C: { n:"BrtEndPRFilters14" },
  25240. 0x048D: { n:"BrtBeginPRFilter14" },
  25241. 0x048E: { n:"BrtEndPRFilter14" },
  25242. 0x048F: { n:"BrtBeginPRFItem14" },
  25243. 0x0490: { n:"BrtEndPRFItem14" },
  25244. 0x0491: { n:"BrtBeginCellIgnoreECs14" },
  25245. 0x0492: { n:"BrtEndCellIgnoreECs14" },
  25246. 0x0493: { n:"BrtDxf14" },
  25247. 0x0494: { n:"BrtBeginDxF14s" },
  25248. 0x0495: { n:"BrtEndDxf14s" },
  25249. 0x0499: { n:"BrtFilter14" },
  25250. 0x049A: { n:"BrtBeginCustomFilters14" },
  25251. 0x049C: { n:"BrtCustomFilter14" },
  25252. 0x049D: { n:"BrtIconFilter14" },
  25253. 0x049E: { n:"BrtPivotCacheConnectionName" },
  25254. 0x0800: { n:"BrtBeginDecoupledPivotCacheIDs" },
  25255. 0x0801: { n:"BrtEndDecoupledPivotCacheIDs" },
  25256. 0x0802: { n:"BrtDecoupledPivotCacheID" },
  25257. 0x0803: { n:"BrtBeginPivotTableRefs" },
  25258. 0x0804: { n:"BrtEndPivotTableRefs" },
  25259. 0x0805: { n:"BrtPivotTableRef" },
  25260. 0x0806: { n:"BrtSlicerCacheBookPivotTables" },
  25261. 0x0807: { n:"BrtBeginSxvcells" },
  25262. 0x0808: { n:"BrtEndSxvcells" },
  25263. 0x0809: { n:"BrtBeginSxRow" },
  25264. 0x080A: { n:"BrtEndSxRow" },
  25265. 0x080C: { n:"BrtPcdCalcMem15" },
  25266. 0x0813: { n:"BrtQsi15" },
  25267. 0x0814: { n:"BrtBeginWebExtensions" },
  25268. 0x0815: { n:"BrtEndWebExtensions" },
  25269. 0x0816: { n:"BrtWebExtension" },
  25270. 0x0817: { n:"BrtAbsPath15" },
  25271. 0x0818: { n:"BrtBeginPivotTableUISettings" },
  25272. 0x0819: { n:"BrtEndPivotTableUISettings" },
  25273. 0x081B: { n:"BrtTableSlicerCacheIDs" },
  25274. 0x081C: { n:"BrtTableSlicerCacheID" },
  25275. 0x081D: { n:"BrtBeginTableSlicerCache" },
  25276. 0x081E: { n:"BrtEndTableSlicerCache" },
  25277. 0x081F: { n:"BrtSxFilter15" },
  25278. 0x0820: { n:"BrtBeginTimelineCachePivotCacheIDs" },
  25279. 0x0821: { n:"BrtEndTimelineCachePivotCacheIDs" },
  25280. 0x0822: { n:"BrtTimelineCachePivotCacheID" },
  25281. 0x0823: { n:"BrtBeginTimelineCacheIDs" },
  25282. 0x0824: { n:"BrtEndTimelineCacheIDs" },
  25283. 0x0825: { n:"BrtBeginTimelineCacheID" },
  25284. 0x0826: { n:"BrtEndTimelineCacheID" },
  25285. 0x0827: { n:"BrtBeginTimelinesEx" },
  25286. 0x0828: { n:"BrtEndTimelinesEx" },
  25287. 0x0829: { n:"BrtBeginTimelineEx" },
  25288. 0x082A: { n:"BrtEndTimelineEx" },
  25289. 0x082B: { n:"BrtWorkBookPr15" },
  25290. 0x082C: { n:"BrtPCDH15" },
  25291. 0x082D: { n:"BrtBeginTimelineStyle" },
  25292. 0x082E: { n:"BrtEndTimelineStyle" },
  25293. 0x082F: { n:"BrtTimelineStyleElement" },
  25294. 0x0830: { n:"BrtBeginTimelineStylesheetExt15" },
  25295. 0x0831: { n:"BrtEndTimelineStylesheetExt15" },
  25296. 0x0832: { n:"BrtBeginTimelineStyles" },
  25297. 0x0833: { n:"BrtEndTimelineStyles" },
  25298. 0x0834: { n:"BrtBeginTimelineStyleElements" },
  25299. 0x0835: { n:"BrtEndTimelineStyleElements" },
  25300. 0x0836: { n:"BrtDxf15" },
  25301. 0x0837: { n:"BrtBeginDxfs15" },
  25302. 0x0838: { n:"brtEndDxfs15" },
  25303. 0x0839: { n:"BrtSlicerCacheHideItemsWithNoData" },
  25304. 0x083A: { n:"BrtBeginItemUniqueNames" },
  25305. 0x083B: { n:"BrtEndItemUniqueNames" },
  25306. 0x083C: { n:"BrtItemUniqueName" },
  25307. 0x083D: { n:"BrtBeginExtConn15" },
  25308. 0x083E: { n:"BrtEndExtConn15" },
  25309. 0x083F: { n:"BrtBeginOledbPr15" },
  25310. 0x0840: { n:"BrtEndOledbPr15" },
  25311. 0x0841: { n:"BrtBeginDataFeedPr15" },
  25312. 0x0842: { n:"BrtEndDataFeedPr15" },
  25313. 0x0843: { n:"BrtTextPr15" },
  25314. 0x0844: { n:"BrtRangePr15" },
  25315. 0x0845: { n:"BrtDbCommand15" },
  25316. 0x0846: { n:"BrtBeginDbTables15" },
  25317. 0x0847: { n:"BrtEndDbTables15" },
  25318. 0x0848: { n:"BrtDbTable15" },
  25319. 0x0849: { n:"BrtBeginDataModel" },
  25320. 0x084A: { n:"BrtEndDataModel" },
  25321. 0x084B: { n:"BrtBeginModelTables" },
  25322. 0x084C: { n:"BrtEndModelTables" },
  25323. 0x084D: { n:"BrtModelTable" },
  25324. 0x084E: { n:"BrtBeginModelRelationships" },
  25325. 0x084F: { n:"BrtEndModelRelationships" },
  25326. 0x0850: { n:"BrtModelRelationship" },
  25327. 0x0851: { n:"BrtBeginECTxtWiz15" },
  25328. 0x0852: { n:"BrtEndECTxtWiz15" },
  25329. 0x0853: { n:"BrtBeginECTWFldInfoLst15" },
  25330. 0x0854: { n:"BrtEndECTWFldInfoLst15" },
  25331. 0x0855: { n:"BrtBeginECTWFldInfo15" },
  25332. 0x0856: { n:"BrtFieldListActiveItem" },
  25333. 0x0857: { n:"BrtPivotCacheIdVersion" },
  25334. 0x0858: { n:"BrtSXDI15" },
  25335. 0x0859: { n:"BrtBeginModelTimeGroupings" },
  25336. 0x085A: { n:"BrtEndModelTimeGroupings" },
  25337. 0x085B: { n:"BrtBeginModelTimeGrouping" },
  25338. 0x085C: { n:"BrtEndModelTimeGrouping" },
  25339. 0x085D: { n:"BrtModelTimeGroupingCalcCol" },
  25340. 0x0C00: { n:"BrtUid" },
  25341. 0x0C01: { n:"BrtRevisionPtr" },
  25342. 0x13e7: { n:"BrtBeginCalcFeatures" },
  25343. 0x13e8: { n:"BrtEndCalcFeatures" },
  25344. 0x13e9: { n:"BrtCalcFeature" },
  25345. 0xFFFF: { n:"" }
  25346. };
  25347. var XLSBRE = evert_key(XLSBRecordEnum, 'n');
  25348. /* [MS-XLS] 2.3 Record Enumeration */
  25349. var XLSRecordEnum = {
  25350. 0x0003: { n:"BIFF2NUM", f:parse_BIFF2NUM },
  25351. 0x0004: { n:"BIFF2STR", f:parse_BIFF2STR },
  25352. 0x0006: { n:"Formula", f:parse_Formula },
  25353. 0x0009: { n:'BOF', f:parse_BOF },
  25354. 0x000a: { n:'EOF', f:parsenoop2 },
  25355. 0x000c: { n:"CalcCount", f:parseuint16 },
  25356. 0x000d: { n:"CalcMode", f:parseuint16 },
  25357. 0x000e: { n:"CalcPrecision", f:parsebool },
  25358. 0x000f: { n:"CalcRefMode", f:parsebool },
  25359. 0x0010: { n:"CalcDelta", f:parse_Xnum },
  25360. 0x0011: { n:"CalcIter", f:parsebool },
  25361. 0x0012: { n:"Protect", f:parsebool },
  25362. 0x0013: { n:"Password", f:parseuint16 },
  25363. 0x0014: { n:"Header", f:parse_XLHeaderFooter },
  25364. 0x0015: { n:"Footer", f:parse_XLHeaderFooter },
  25365. 0x0017: { n:"ExternSheet", f:parse_ExternSheet },
  25366. 0x0018: { n:"Lbl", f:parse_Lbl },
  25367. 0x0019: { n:"WinProtect", f:parsebool },
  25368. 0x001a: { n:"VerticalPageBreaks" },
  25369. 0x001b: { n:"HorizontalPageBreaks" },
  25370. 0x001c: { n:"Note", f:parse_Note },
  25371. 0x001d: { n:"Selection" },
  25372. 0x0022: { n:"Date1904", f:parsebool },
  25373. 0x0023: { n:"ExternName", f:parse_ExternName },
  25374. 0x0024: { n:"COLWIDTH" },
  25375. 0x0026: { n:"LeftMargin", f:parse_Xnum },
  25376. 0x0027: { n:"RightMargin", f:parse_Xnum },
  25377. 0x0028: { n:"TopMargin", f:parse_Xnum },
  25378. 0x0029: { n:"BottomMargin", f:parse_Xnum },
  25379. 0x002a: { n:"PrintRowCol", f:parsebool },
  25380. 0x002b: { n:"PrintGrid", f:parsebool },
  25381. 0x002f: { n:"FilePass", f:parse_FilePass },
  25382. 0x0031: { n:"Font", f:parse_Font },
  25383. 0x0033: { n:"PrintSize", f:parseuint16 },
  25384. 0x003c: { n:"Continue" },
  25385. 0x003d: { n:"Window1", f:parse_Window1 },
  25386. 0x0040: { n:"Backup", f:parsebool },
  25387. 0x0041: { n:"Pane", f:parse_Pane },
  25388. 0x0042: { n:'CodePage', f:parseuint16 },
  25389. 0x004d: { n:"Pls" },
  25390. 0x0050: { n:"DCon" },
  25391. 0x0051: { n:"DConRef" },
  25392. 0x0052: { n:"DConName" },
  25393. 0x0055: { n:"DefColWidth", f:parseuint16 },
  25394. 0x0059: { n:"XCT" },
  25395. 0x005a: { n:"CRN" },
  25396. 0x005b: { n:"FileSharing" },
  25397. 0x005c: { n:'WriteAccess', f:parse_WriteAccess },
  25398. 0x005d: { n:"Obj", f:parse_Obj },
  25399. 0x005e: { n:"Uncalced" },
  25400. 0x005f: { n:"CalcSaveRecalc", f:parsebool },
  25401. 0x0060: { n:"Template" },
  25402. 0x0061: { n:"Intl" },
  25403. 0x0063: { n:"ObjProtect", f:parsebool },
  25404. 0x007d: { n:"ColInfo", f:parse_ColInfo },
  25405. 0x0080: { n:"Guts", f:parse_Guts },
  25406. 0x0081: { n:"WsBool", f:parse_WsBool },
  25407. 0x0082: { n:"GridSet", f:parseuint16 },
  25408. 0x0083: { n:"HCenter", f:parsebool },
  25409. 0x0084: { n:"VCenter", f:parsebool },
  25410. 0x0085: { n:'BoundSheet8', f:parse_BoundSheet8 },
  25411. 0x0086: { n:"WriteProtect" },
  25412. 0x008c: { n:"Country", f:parse_Country },
  25413. 0x008d: { n:"HideObj", f:parseuint16 },
  25414. 0x0090: { n:"Sort" },
  25415. 0x0092: { n:"Palette", f:parse_Palette },
  25416. 0x0097: { n:"Sync" },
  25417. 0x0098: { n:"LPr" },
  25418. 0x0099: { n:"DxGCol" },
  25419. 0x009a: { n:"FnGroupName" },
  25420. 0x009b: { n:"FilterMode" },
  25421. 0x009c: { n:"BuiltInFnGroupCount", f:parseuint16 },
  25422. 0x009d: { n:"AutoFilterInfo" },
  25423. 0x009e: { n:"AutoFilter" },
  25424. 0x00a0: { n:"Scl", f:parse_Scl },
  25425. 0x00a1: { n:"Setup", f:parse_Setup },
  25426. 0x00ae: { n:"ScenMan" },
  25427. 0x00af: { n:"SCENARIO" },
  25428. 0x00b0: { n:"SxView" },
  25429. 0x00b1: { n:"Sxvd" },
  25430. 0x00b2: { n:"SXVI" },
  25431. 0x00b4: { n:"SxIvd" },
  25432. 0x00b5: { n:"SXLI" },
  25433. 0x00b6: { n:"SXPI" },
  25434. 0x00b8: { n:"DocRoute" },
  25435. 0x00b9: { n:"RecipName" },
  25436. 0x00bd: { n:"MulRk", f:parse_MulRk },
  25437. 0x00be: { n:"MulBlank", f:parse_MulBlank },
  25438. 0x00c1: { n:'Mms', f:parsenoop2 },
  25439. 0x00c5: { n:"SXDI" },
  25440. 0x00c6: { n:"SXDB" },
  25441. 0x00c7: { n:"SXFDB" },
  25442. 0x00c8: { n:"SXDBB" },
  25443. 0x00c9: { n:"SXNum" },
  25444. 0x00ca: { n:"SxBool", f:parsebool },
  25445. 0x00cb: { n:"SxErr" },
  25446. 0x00cc: { n:"SXInt" },
  25447. 0x00cd: { n:"SXString" },
  25448. 0x00ce: { n:"SXDtr" },
  25449. 0x00cf: { n:"SxNil" },
  25450. 0x00d0: { n:"SXTbl" },
  25451. 0x00d1: { n:"SXTBRGIITM" },
  25452. 0x00d2: { n:"SxTbpg" },
  25453. 0x00d3: { n:"ObProj" },
  25454. 0x00d5: { n:"SXStreamID" },
  25455. 0x00d7: { n:"DBCell" },
  25456. 0x00d8: { n:"SXRng" },
  25457. 0x00d9: { n:"SxIsxoper" },
  25458. 0x00da: { n:"BookBool", f:parseuint16 },
  25459. 0x00dc: { n:"DbOrParamQry" },
  25460. 0x00dd: { n:"ScenarioProtect", f:parsebool },
  25461. 0x00de: { n:"OleObjectSize" },
  25462. 0x00e0: { n:"XF", f:parse_XF },
  25463. 0x00e1: { n:'InterfaceHdr', f:parse_InterfaceHdr },
  25464. 0x00e2: { n:'InterfaceEnd', f:parsenoop2 },
  25465. 0x00e3: { n:"SXVS" },
  25466. 0x00e5: { n:"MergeCells", f:parse_MergeCells },
  25467. 0x00e9: { n:"BkHim" },
  25468. 0x00eb: { n:"MsoDrawingGroup" },
  25469. 0x00ec: { n:"MsoDrawing" },
  25470. 0x00ed: { n:"MsoDrawingSelection" },
  25471. 0x00ef: { n:"PhoneticInfo" },
  25472. 0x00f0: { n:"SxRule" },
  25473. 0x00f1: { n:"SXEx" },
  25474. 0x00f2: { n:"SxFilt" },
  25475. 0x00f4: { n:"SxDXF" },
  25476. 0x00f5: { n:"SxItm" },
  25477. 0x00f6: { n:"SxName" },
  25478. 0x00f7: { n:"SxSelect" },
  25479. 0x00f8: { n:"SXPair" },
  25480. 0x00f9: { n:"SxFmla" },
  25481. 0x00fb: { n:"SxFormat" },
  25482. 0x00fc: { n:"SST", f:parse_SST },
  25483. 0x00fd: { n:"LabelSst", f:parse_LabelSst },
  25484. 0x00ff: { n:"ExtSST", f:parse_ExtSST },
  25485. 0x0100: { n:"SXVDEx" },
  25486. 0x0103: { n:"SXFormula" },
  25487. 0x0122: { n:"SXDBEx" },
  25488. 0x0137: { n:"RRDInsDel" },
  25489. 0x0138: { n:"RRDHead" },
  25490. 0x013b: { n:"RRDChgCell" },
  25491. 0x013d: { n:"RRTabId", f:parseuint16a },
  25492. 0x013e: { n:"RRDRenSheet" },
  25493. 0x013f: { n:"RRSort" },
  25494. 0x0140: { n:"RRDMove" },
  25495. 0x014a: { n:"RRFormat" },
  25496. 0x014b: { n:"RRAutoFmt" },
  25497. 0x014d: { n:"RRInsertSh" },
  25498. 0x014e: { n:"RRDMoveBegin" },
  25499. 0x014f: { n:"RRDMoveEnd" },
  25500. 0x0150: { n:"RRDInsDelBegin" },
  25501. 0x0151: { n:"RRDInsDelEnd" },
  25502. 0x0152: { n:"RRDConflict" },
  25503. 0x0153: { n:"RRDDefName" },
  25504. 0x0154: { n:"RRDRstEtxp" },
  25505. 0x015f: { n:"LRng" },
  25506. 0x0160: { n:"UsesELFs", f:parsebool },
  25507. 0x0161: { n:"DSF", f:parsenoop2 },
  25508. 0x0191: { n:"CUsr" },
  25509. 0x0192: { n:"CbUsr" },
  25510. 0x0193: { n:"UsrInfo" },
  25511. 0x0194: { n:"UsrExcl" },
  25512. 0x0195: { n:"FileLock" },
  25513. 0x0196: { n:"RRDInfo" },
  25514. 0x0197: { n:"BCUsrs" },
  25515. 0x0198: { n:"UsrChk" },
  25516. 0x01a9: { n:"UserBView" },
  25517. 0x01aa: { n:"UserSViewBegin" },
  25518. 0x01ab: { n:"UserSViewEnd" },
  25519. 0x01ac: { n:"RRDUserView" },
  25520. 0x01ad: { n:"Qsi" },
  25521. 0x01ae: { n:"SupBook", f:parse_SupBook },
  25522. 0x01af: { n:"Prot4Rev", f:parsebool },
  25523. 0x01b0: { n:"CondFmt" },
  25524. 0x01b1: { n:"CF" },
  25525. 0x01b2: { n:"DVal" },
  25526. 0x01b5: { n:"DConBin" },
  25527. 0x01b6: { n:"TxO", f:parse_TxO },
  25528. 0x01b7: { n:"RefreshAll", f:parsebool },
  25529. 0x01b8: { n:"HLink", f:parse_HLink },
  25530. 0x01b9: { n:"Lel" },
  25531. 0x01ba: { n:"CodeName", f:parse_XLUnicodeString },
  25532. 0x01bb: { n:"SXFDBType" },
  25533. 0x01bc: { n:"Prot4RevPass", f:parseuint16 },
  25534. 0x01bd: { n:"ObNoMacros" },
  25535. 0x01be: { n:"Dv" },
  25536. 0x01c0: { n:"Excel9File", f:parsenoop2 },
  25537. 0x01c1: { n:"RecalcId", f:parse_RecalcId, r:2},
  25538. 0x01c2: { n:"EntExU2", f:parsenoop2 },
  25539. 0x0200: { n:"Dimensions", f:parse_Dimensions },
  25540. 0x0201: { n:"Blank", f:parse_Blank },
  25541. 0x0203: { n:"Number", f:parse_Number },
  25542. 0x0204: { n:"Label", f:parse_Label },
  25543. 0x0205: { n:"BoolErr", f:parse_BoolErr },
  25544. 0x0206: { n:"Formula", f:parse_Formula },
  25545. 0x0207: { n:"String", f:parse_String },
  25546. 0x0208: { n:'Row', f:parse_Row },
  25547. 0x020b: { n:"Index" },
  25548. 0x0221: { n:"Array", f:parse_Array },
  25549. 0x0225: { n:"DefaultRowHeight", f:parse_DefaultRowHeight },
  25550. 0x0236: { n:"Table" },
  25551. 0x023e: { n:"Window2", f:parse_Window2 },
  25552. 0x027e: { n:"RK", f:parse_RK },
  25553. 0x0293: { n:"Style" },
  25554. 0x0406: { n:"Formula", f:parse_Formula },
  25555. 0x0418: { n:"BigName" },
  25556. 0x041e: { n:"Format", f:parse_Format },
  25557. 0x043c: { n:"ContinueBigName" },
  25558. 0x04bc: { n:"ShrFmla", f:parse_ShrFmla },
  25559. 0x0800: { n:"HLinkTooltip", f:parse_HLinkTooltip },
  25560. 0x0801: { n:"WebPub" },
  25561. 0x0802: { n:"QsiSXTag" },
  25562. 0x0803: { n:"DBQueryExt" },
  25563. 0x0804: { n:"ExtString" },
  25564. 0x0805: { n:"TxtQry" },
  25565. 0x0806: { n:"Qsir" },
  25566. 0x0807: { n:"Qsif" },
  25567. 0x0808: { n:"RRDTQSIF" },
  25568. 0x0809: { n:'BOF', f:parse_BOF },
  25569. 0x080a: { n:"OleDbConn" },
  25570. 0x080b: { n:"WOpt" },
  25571. 0x080c: { n:"SXViewEx" },
  25572. 0x080d: { n:"SXTH" },
  25573. 0x080e: { n:"SXPIEx" },
  25574. 0x080f: { n:"SXVDTEx" },
  25575. 0x0810: { n:"SXViewEx9" },
  25576. 0x0812: { n:"ContinueFrt" },
  25577. 0x0813: { n:"RealTimeData" },
  25578. 0x0850: { n:"ChartFrtInfo" },
  25579. 0x0851: { n:"FrtWrapper" },
  25580. 0x0852: { n:"StartBlock" },
  25581. 0x0853: { n:"EndBlock" },
  25582. 0x0854: { n:"StartObject" },
  25583. 0x0855: { n:"EndObject" },
  25584. 0x0856: { n:"CatLab" },
  25585. 0x0857: { n:"YMult" },
  25586. 0x0858: { n:"SXViewLink" },
  25587. 0x0859: { n:"PivotChartBits" },
  25588. 0x085a: { n:"FrtFontList" },
  25589. 0x0862: { n:"SheetExt" },
  25590. 0x0863: { n:"BookExt", r:12},
  25591. 0x0864: { n:"SXAddl" },
  25592. 0x0865: { n:"CrErr" },
  25593. 0x0866: { n:"HFPicture" },
  25594. 0x0867: { n:'FeatHdr', f:parsenoop2 },
  25595. 0x0868: { n:"Feat" },
  25596. 0x086a: { n:"DataLabExt" },
  25597. 0x086b: { n:"DataLabExtContents" },
  25598. 0x086c: { n:"CellWatch" },
  25599. 0x0871: { n:"FeatHdr11" },
  25600. 0x0872: { n:"Feature11" },
  25601. 0x0874: { n:"DropDownObjIds" },
  25602. 0x0875: { n:"ContinueFrt11" },
  25603. 0x0876: { n:"DConn" },
  25604. 0x0877: { n:"List12" },
  25605. 0x0878: { n:"Feature12" },
  25606. 0x0879: { n:"CondFmt12" },
  25607. 0x087a: { n:"CF12" },
  25608. 0x087b: { n:"CFEx" },
  25609. 0x087c: { n:"XFCRC", f:parse_XFCRC, r:12 },
  25610. 0x087d: { n:"XFExt", f:parse_XFExt, r:12 },
  25611. 0x087e: { n:"AutoFilter12" },
  25612. 0x087f: { n:"ContinueFrt12" },
  25613. 0x0884: { n:"MDTInfo" },
  25614. 0x0885: { n:"MDXStr" },
  25615. 0x0886: { n:"MDXTuple" },
  25616. 0x0887: { n:"MDXSet" },
  25617. 0x0888: { n:"MDXProp" },
  25618. 0x0889: { n:"MDXKPI" },
  25619. 0x088a: { n:"MDB" },
  25620. 0x088b: { n:"PLV" },
  25621. 0x088c: { n:"Compat12", f:parsebool, r:12 },
  25622. 0x088d: { n:"DXF" },
  25623. 0x088e: { n:"TableStyles", r:12 },
  25624. 0x088f: { n:"TableStyle" },
  25625. 0x0890: { n:"TableStyleElement" },
  25626. 0x0892: { n:"StyleExt" },
  25627. 0x0893: { n:"NamePublish" },
  25628. 0x0894: { n:"NameCmt", f:parse_NameCmt, r:12 },
  25629. 0x0895: { n:"SortData" },
  25630. 0x0896: { n:"Theme", f:parse_Theme, r:12 },
  25631. 0x0897: { n:"GUIDTypeLib" },
  25632. 0x0898: { n:"FnGrp12" },
  25633. 0x0899: { n:"NameFnGrp12" },
  25634. 0x089a: { n:"MTRSettings", f:parse_MTRSettings, r:12 },
  25635. 0x089b: { n:"CompressPictures", f:parsenoop2 },
  25636. 0x089c: { n:"HeaderFooter" },
  25637. 0x089d: { n:"CrtLayout12" },
  25638. 0x089e: { n:"CrtMlFrt" },
  25639. 0x089f: { n:"CrtMlFrtContinue" },
  25640. 0x08a3: { n:"ForceFullCalculation", f:parse_ForceFullCalculation },
  25641. 0x08a4: { n:"ShapePropsStream" },
  25642. 0x08a5: { n:"TextPropsStream" },
  25643. 0x08a6: { n:"RichTextStream" },
  25644. 0x08a7: { n:"CrtLayout12A" },
  25645. 0x1001: { n:"Units" },
  25646. 0x1002: { n:"Chart" },
  25647. 0x1003: { n:"Series" },
  25648. 0x1006: { n:"DataFormat" },
  25649. 0x1007: { n:"LineFormat" },
  25650. 0x1009: { n:"MarkerFormat" },
  25651. 0x100a: { n:"AreaFormat" },
  25652. 0x100b: { n:"PieFormat" },
  25653. 0x100c: { n:"AttachedLabel" },
  25654. 0x100d: { n:"SeriesText" },
  25655. 0x1014: { n:"ChartFormat" },
  25656. 0x1015: { n:"Legend" },
  25657. 0x1016: { n:"SeriesList" },
  25658. 0x1017: { n:"Bar" },
  25659. 0x1018: { n:"Line" },
  25660. 0x1019: { n:"Pie" },
  25661. 0x101a: { n:"Area" },
  25662. 0x101b: { n:"Scatter" },
  25663. 0x101c: { n:"CrtLine" },
  25664. 0x101d: { n:"Axis" },
  25665. 0x101e: { n:"Tick" },
  25666. 0x101f: { n:"ValueRange" },
  25667. 0x1020: { n:"CatSerRange" },
  25668. 0x1021: { n:"AxisLine" },
  25669. 0x1022: { n:"CrtLink" },
  25670. 0x1024: { n:"DefaultText" },
  25671. 0x1025: { n:"Text" },
  25672. 0x1026: { n:"FontX", f:parseuint16 },
  25673. 0x1027: { n:"ObjectLink" },
  25674. 0x1032: { n:"Frame" },
  25675. 0x1033: { n:"Begin" },
  25676. 0x1034: { n:"End" },
  25677. 0x1035: { n:"PlotArea" },
  25678. 0x103a: { n:"Chart3d" },
  25679. 0x103c: { n:"PicF" },
  25680. 0x103d: { n:"DropBar" },
  25681. 0x103e: { n:"Radar" },
  25682. 0x103f: { n:"Surf" },
  25683. 0x1040: { n:"RadarArea" },
  25684. 0x1041: { n:"AxisParent" },
  25685. 0x1043: { n:"LegendException" },
  25686. 0x1044: { n:"ShtProps", f:parse_ShtProps },
  25687. 0x1045: { n:"SerToCrt" },
  25688. 0x1046: { n:"AxesUsed" },
  25689. 0x1048: { n:"SBaseRef" },
  25690. 0x104a: { n:"SerParent" },
  25691. 0x104b: { n:"SerAuxTrend" },
  25692. 0x104e: { n:"IFmtRecord" },
  25693. 0x104f: { n:"Pos" },
  25694. 0x1050: { n:"AlRuns" },
  25695. 0x1051: { n:"BRAI" },
  25696. 0x105b: { n:"SerAuxErrBar" },
  25697. 0x105c: { n:"ClrtClient", f:parse_ClrtClient },
  25698. 0x105d: { n:"SerFmt" },
  25699. 0x105f: { n:"Chart3DBarShape" },
  25700. 0x1060: { n:"Fbi" },
  25701. 0x1061: { n:"BopPop" },
  25702. 0x1062: { n:"AxcExt" },
  25703. 0x1063: { n:"Dat" },
  25704. 0x1064: { n:"PlotGrowth" },
  25705. 0x1065: { n:"SIIndex" },
  25706. 0x1066: { n:"GelFrame" },
  25707. 0x1067: { n:"BopPopCustom" },
  25708. 0x1068: { n:"Fbi2" },
  25709. 0x0000: { n:"Dimensions", f:parse_Dimensions },
  25710. 0x0002: { n:"BIFF2INT", f:parse_BIFF2INT },
  25711. 0x0005: { n:"BoolErr", f:parse_BoolErr },
  25712. 0x0007: { n:"String", f:parse_BIFF2STRING },
  25713. 0x0008: { n:"BIFF2ROW" },
  25714. 0x000b: { n:"Index" },
  25715. 0x0016: { n:"ExternCount", f:parseuint16 },
  25716. 0x001e: { n:"BIFF2FORMAT", f:parse_BIFF2Format },
  25717. 0x001f: { n:"BIFF2FMTCNT" }, /* 16-bit cnt of BIFF2FORMAT records */
  25718. 0x0020: { n:"BIFF2COLINFO" },
  25719. 0x0021: { n:"Array", f:parse_Array },
  25720. 0x0025: { n:"DefaultRowHeight", f:parse_DefaultRowHeight },
  25721. 0x0032: { n:"BIFF2FONTXTRA", f:parse_BIFF2FONTXTRA },
  25722. 0x0034: { n:"DDEObjName" },
  25723. 0x003e: { n:"BIFF2WINDOW2" },
  25724. 0x0043: { n:"BIFF2XF" },
  25725. 0x0045: { n:"BIFF2FONTCLR" },
  25726. 0x0056: { n:"BIFF4FMTCNT" }, /* 16-bit cnt, similar to BIFF2 */
  25727. 0x007e: { n:"RK" }, /* Not necessarily same as 0x027e */
  25728. 0x007f: { n:"ImData", f:parse_ImData },
  25729. 0x0087: { n:"Addin" },
  25730. 0x0088: { n:"Edg" },
  25731. 0x0089: { n:"Pub" },
  25732. 0x0091: { n:"Sub" },
  25733. 0x0094: { n:"LHRecord" },
  25734. 0x0095: { n:"LHNGraph" },
  25735. 0x0096: { n:"Sound" },
  25736. 0x00a9: { n:"CoordList" },
  25737. 0x00ab: { n:"GCW" },
  25738. 0x00bc: { n:"ShrFmla" }, /* Not necessarily same as 0x04bc */
  25739. 0x00bf: { n:"ToolbarHdr" },
  25740. 0x00c0: { n:"ToolbarEnd" },
  25741. 0x00c2: { n:"AddMenu" },
  25742. 0x00c3: { n:"DelMenu" },
  25743. 0x00d6: { n:"RString", f:parse_RString },
  25744. 0x00df: { n:"UDDesc" },
  25745. 0x00ea: { n:"TabIdConf" },
  25746. 0x0162: { n:"XL5Modify" },
  25747. 0x01a5: { n:"FileSharing2" },
  25748. 0x0209: { n:'BOF', f:parse_BOF },
  25749. 0x0218: { n:"Lbl", f:parse_Lbl },
  25750. 0x0223: { n:"ExternName", f:parse_ExternName },
  25751. 0x0231: { n:"Font" },
  25752. 0x0243: { n:"BIFF3XF" },
  25753. 0x0409: { n:'BOF', f:parse_BOF },
  25754. 0x0443: { n:"BIFF4XF" },
  25755. 0x086d: { n:"FeatInfo" },
  25756. 0x0873: { n:"FeatInfo11" },
  25757. 0x0881: { n:"SXAddl12" },
  25758. 0x08c0: { n:"AutoWebPub" },
  25759. 0x08c1: { n:"ListObj" },
  25760. 0x08c2: { n:"ListField" },
  25761. 0x08c3: { n:"ListDV" },
  25762. 0x08c4: { n:"ListCondFmt" },
  25763. 0x08c5: { n:"ListCF" },
  25764. 0x08c6: { n:"FMQry" },
  25765. 0x08c7: { n:"FMSQry" },
  25766. 0x08c8: { n:"PLV" },
  25767. 0x08c9: { n:"LnExt" },
  25768. 0x08ca: { n:"MkrExt" },
  25769. 0x08cb: { n:"CrtCoopt" },
  25770. 0x08d6: { n:"FRTArchId$", r:12 },
  25771. 0x7262: {}
  25772. };
  25773. var XLSRE = evert_key(XLSRecordEnum, 'n');
  25774. function write_biff_rec(ba, type, payload, length) {
  25775. var t = +type || +XLSRE[type];
  25776. if(isNaN(t)) return;
  25777. var len = length || (payload||[]).length || 0;
  25778. var o = ba.next(4);
  25779. o.write_shift(2, t);
  25780. o.write_shift(2, len);
  25781. if(len > 0 && is_buf(payload)) ba.push(payload);
  25782. }
  25783. function write_biff_continue(ba, type, payload, length) {
  25784. var len = length || (payload||[]).length || 0;
  25785. if(len <= 8224) return write_biff_rec(ba, type, payload, len);
  25786. var t = +type || +XLSRE[type];
  25787. if(isNaN(t)) return;
  25788. var parts = payload.parts || [], sidx = 0;
  25789. var i = 0, w = 0;
  25790. while(w + (parts[sidx] || 8224) <= 8224) { w+= (parts[sidx] || 8224); sidx++; }
  25791. var o = ba.next(4);
  25792. o.write_shift(2, t);
  25793. o.write_shift(2, w);
  25794. ba.push(payload.slice(i, i + w));
  25795. i += w;
  25796. while(i < len) {
  25797. o = ba.next(4);
  25798. o.write_shift(2, 0x3c); // TODO: figure out correct continue type
  25799. w = 0;
  25800. while(w + (parts[sidx] || 8224) <= 8224) { w+= (parts[sidx] || 8224); sidx++; }
  25801. o.write_shift(2, w);
  25802. ba.push(payload.slice(i, i+w)); i+= w;
  25803. }
  25804. }
  25805. function write_BIFF2Cell(out, r, c) {
  25806. if(!out) out = new_buf(7);
  25807. out.write_shift(2, r);
  25808. out.write_shift(2, c);
  25809. out.write_shift(2, 0);
  25810. out.write_shift(1, 0);
  25811. return out;
  25812. }
  25813. function write_BIFF2BERR(r, c, val, t) {
  25814. var out = new_buf(9);
  25815. write_BIFF2Cell(out, r, c);
  25816. if(t == 'e') { out.write_shift(1, val); out.write_shift(1, 1); }
  25817. else { out.write_shift(1, val?1:0); out.write_shift(1, 0); }
  25818. return out;
  25819. }
  25820. /* TODO: codepage, large strings */
  25821. function write_BIFF2LABEL(r, c, val) {
  25822. var out = new_buf(8 + 2*val.length);
  25823. write_BIFF2Cell(out, r, c);
  25824. out.write_shift(1, val.length);
  25825. out.write_shift(val.length, val, 'sbcs');
  25826. return out.l < out.length ? out.slice(0, out.l) : out;
  25827. }
  25828. function write_ws_biff2_cell(ba, cell, R, C) {
  25829. if(cell.v != null) switch(cell.t) {
  25830. case 'd': case 'n':
  25831. var v = cell.t == 'd' ? datenum(parseDate(cell.v)) : cell.v;
  25832. if((v == (v|0)) && (v >= 0) && (v < 65536))
  25833. write_biff_rec(ba, 0x0002, write_BIFF2INT(R, C, v));
  25834. else
  25835. write_biff_rec(ba, 0x0003, write_BIFF2NUM(R,C, v));
  25836. return;
  25837. case 'b': case 'e': write_biff_rec(ba, 0x0005, write_BIFF2BERR(R, C, cell.v, cell.t)); return;
  25838. /* TODO: codepage, sst */
  25839. case 's': case 'str':
  25840. write_biff_rec(ba, 0x0004, write_BIFF2LABEL(R, C, cell.v));
  25841. return;
  25842. }
  25843. write_biff_rec(ba, 0x0001, write_BIFF2Cell(null, R, C));
  25844. }
  25845. function write_ws_biff2(ba, ws, idx, opts) {
  25846. var dense = Array.isArray(ws);
  25847. var range = safe_decode_range(ws['!ref'] || "A1"), ref, rr = "", cols = [];
  25848. if(range.e.c > 0xFF || range.e.r > 0x3FFF) {
  25849. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
  25850. range.e.c = Math.min(range.e.c, 0xFF);
  25851. range.e.r = Math.min(range.e.c, 0x3FFF);
  25852. ref = encode_range(range);
  25853. }
  25854. for(var R = range.s.r; R <= range.e.r; ++R) {
  25855. rr = encode_row(R);
  25856. for(var C = range.s.c; C <= range.e.c; ++C) {
  25857. if(R === range.s.r) cols[C] = encode_col(C);
  25858. ref = cols[C] + rr;
  25859. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  25860. if(!cell) continue;
  25861. /* write cell */
  25862. write_ws_biff2_cell(ba, cell, R, C, opts);
  25863. }
  25864. }
  25865. }
  25866. /* Based on test files */
  25867. function write_biff2_buf(wb, opts) {
  25868. var o = opts || {};
  25869. if(DENSE != null && o.dense == null) o.dense = DENSE;
  25870. var ba = buf_array();
  25871. var idx = 0;
  25872. for(var i=0;i<wb.SheetNames.length;++i) if(wb.SheetNames[i] == o.sheet) idx=i;
  25873. if(idx == 0 && !!o.sheet && wb.SheetNames[0] != o.sheet) throw new Error("Sheet not found: " + o.sheet);
  25874. write_biff_rec(ba, 0x0009, write_BOF(wb, 0x10, o));
  25875. /* ... */
  25876. write_ws_biff2(ba, wb.Sheets[wb.SheetNames[idx]], idx, o, wb);
  25877. /* ... */
  25878. write_biff_rec(ba, 0x000A);
  25879. return ba.end();
  25880. }
  25881. function write_FONTS_biff8(ba, data, opts) {
  25882. write_biff_rec(ba, "Font", write_Font({
  25883. sz:12,
  25884. color: {theme:1},
  25885. name: "Arial",
  25886. family: 2,
  25887. scheme: "minor"
  25888. }, opts));
  25889. }
  25890. function write_FMTS_biff8(ba, NF, opts) {
  25891. if(!NF) return;
  25892. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  25893. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) write_biff_rec(ba, "Format", write_Format(i, NF[i], opts));
  25894. });
  25895. }
  25896. function write_FEAT(ba, ws) {
  25897. /* [MS-XLS] 2.4.112 */
  25898. var o = new_buf(19);
  25899. o.write_shift(4, 0x867); o.write_shift(4, 0); o.write_shift(4, 0);
  25900. o.write_shift(2, 3); o.write_shift(1, 1); o.write_shift(4, 0);
  25901. write_biff_rec(ba, "FeatHdr", o);
  25902. /* [MS-XLS] 2.4.111 */
  25903. o = new_buf(39);
  25904. o.write_shift(4, 0x868); o.write_shift(4, 0); o.write_shift(4, 0);
  25905. o.write_shift(2, 3); o.write_shift(1, 0); o.write_shift(4, 0);
  25906. o.write_shift(2, 1); o.write_shift(4, 4); o.write_shift(2, 0);
  25907. write_Ref8U(safe_decode_range(ws['!ref']||"A1"), o);
  25908. o.write_shift(4, 4);
  25909. write_biff_rec(ba, "Feat", o);
  25910. }
  25911. function write_CELLXFS_biff8(ba, opts) {
  25912. for(var i = 0; i < 16; ++i) write_biff_rec(ba, "XF", write_XF({numFmtId:0, style:true}, 0, opts));
  25913. opts.cellXfs.forEach(function(c) {
  25914. write_biff_rec(ba, "XF", write_XF(c, 0, opts));
  25915. });
  25916. }
  25917. function write_ws_biff8_hlinks(ba, ws) {
  25918. for(var R=0; R<ws['!links'].length; ++R) {
  25919. var HL = ws['!links'][R];
  25920. write_biff_rec(ba, "HLink", write_HLink(HL));
  25921. if(HL[1].Tooltip) write_biff_rec(ba, "HLinkTooltip", write_HLinkTooltip(HL));
  25922. }
  25923. delete ws['!links'];
  25924. }
  25925. function write_ws_biff8_cell(ba, cell, R, C, opts) {
  25926. var os = 16 + get_cell_style(opts.cellXfs, cell, opts);
  25927. if(cell.v == null && !cell.bf) {
  25928. write_biff_rec(ba, "Blank", write_XLSCell(R, C, os));
  25929. return;
  25930. }
  25931. if(cell.bf) write_biff_rec(ba, "Formula", write_Formula(cell, R, C, opts, os));
  25932. else switch(cell.t) {
  25933. case 'd': case 'n':
  25934. var v = cell.t == 'd' ? datenum(parseDate(cell.v)) : cell.v;
  25935. /* TODO: emit RK as appropriate */
  25936. write_biff_rec(ba, "Number", write_Number(R, C, v, os, opts));
  25937. break;
  25938. case 'b': case 'e':
  25939. write_biff_rec(ba, 0x0205, write_BoolErr(R, C, cell.v, os, opts, cell.t));
  25940. break;
  25941. /* TODO: codepage, sst */
  25942. case 's': case 'str':
  25943. if(opts.bookSST) {
  25944. var isst = get_sst_id(opts.Strings, cell.v, opts.revStrings);
  25945. write_biff_rec(ba, "LabelSst", write_LabelSst(R, C, isst, os, opts));
  25946. } else write_biff_rec(ba, "Label", write_Label(R, C, cell.v, os, opts));
  25947. break;
  25948. default:
  25949. write_biff_rec(ba, "Blank", write_XLSCell(R, C, os));
  25950. }
  25951. }
  25952. /* [MS-XLS] 2.1.7.20.5 */
  25953. function write_ws_biff8(idx, opts, wb) {
  25954. var ba = buf_array();
  25955. var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
  25956. var _WB = ((wb||{}).Workbook||{});
  25957. var _sheet = ((_WB.Sheets||[])[idx]||{});
  25958. var dense = Array.isArray(ws);
  25959. var b8 = opts.biff == 8;
  25960. var ref, rr = "", cols = [];
  25961. var range = safe_decode_range(ws['!ref'] || "A1");
  25962. var MAX_ROWS = b8 ? 65536 : 16384;
  25963. if(range.e.c > 0xFF || range.e.r >= MAX_ROWS) {
  25964. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
  25965. range.e.c = Math.min(range.e.c, 0xFF);
  25966. range.e.r = Math.min(range.e.c, MAX_ROWS-1);
  25967. }
  25968. write_biff_rec(ba, 0x0809, write_BOF(wb, 0x10, opts));
  25969. /* [Uncalced] Index */
  25970. write_biff_rec(ba, "CalcMode", writeuint16(1));
  25971. write_biff_rec(ba, "CalcCount", writeuint16(100));
  25972. write_biff_rec(ba, "CalcRefMode", writebool(true));
  25973. write_biff_rec(ba, "CalcIter", writebool(false));
  25974. write_biff_rec(ba, "CalcDelta", write_Xnum(0.001));
  25975. write_biff_rec(ba, "CalcSaveRecalc", writebool(true));
  25976. write_biff_rec(ba, "PrintRowCol", writebool(false));
  25977. write_biff_rec(ba, "PrintGrid", writebool(false));
  25978. write_biff_rec(ba, "GridSet", writeuint16(1));
  25979. write_biff_rec(ba, "Guts", write_Guts([0,0]));
  25980. /* DefaultRowHeight WsBool [Sync] [LPr] [HorizontalPageBreaks] [VerticalPageBreaks] */
  25981. /* Header (string) */
  25982. /* Footer (string) */
  25983. write_biff_rec(ba, "HCenter", writebool(false));
  25984. write_biff_rec(ba, "VCenter", writebool(false));
  25985. /* ... */
  25986. write_biff_rec(ba, 0x200, write_Dimensions(range, opts));
  25987. /* ... */
  25988. if(b8) ws['!links'] = [];
  25989. for(var R = range.s.r; R <= range.e.r; ++R) {
  25990. rr = encode_row(R);
  25991. for(var C = range.s.c; C <= range.e.c; ++C) {
  25992. if(R === range.s.r) cols[C] = encode_col(C);
  25993. ref = cols[C] + rr;
  25994. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  25995. if(!cell) continue;
  25996. /* write cell */
  25997. write_ws_biff8_cell(ba, cell, R, C, opts);
  25998. if(b8 && cell.l) ws['!links'].push([ref, cell.l]);
  25999. }
  26000. }
  26001. var cname = _sheet.CodeName || _sheet.name || s;
  26002. /* ... */
  26003. if(b8) write_biff_rec(ba, "Window2", write_Window2((_WB.Views||[])[0]));
  26004. /* ... */
  26005. if(b8 && (ws['!merges']||[]).length) write_biff_rec(ba, "MergeCells", write_MergeCells(ws['!merges']));
  26006. /* [LRng] *QUERYTABLE [PHONETICINFO] CONDFMTS */
  26007. if(b8) write_ws_biff8_hlinks(ba, ws);
  26008. /* [DVAL] */
  26009. write_biff_rec(ba, "CodeName", write_XLUnicodeString(cname, opts));
  26010. /* *WebPub *CellWatch [SheetExt] */
  26011. if(b8) write_FEAT(ba, ws);
  26012. /* *FEAT11 *RECORD12 */
  26013. write_biff_rec(ba, "EOF");
  26014. return ba.end();
  26015. }
  26016. /* [MS-XLS] 2.1.7.20.3 */
  26017. function write_biff8_global(wb, bufs, opts) {
  26018. var A = buf_array();
  26019. var _WB = ((wb||{}).Workbook||{});
  26020. var _sheets = (_WB.Sheets||[]);
  26021. var _wb = _WB.WBProps||{};
  26022. var b8 = opts.biff == 8, b5 = opts.biff == 5;
  26023. write_biff_rec(A, 0x0809, write_BOF(wb, 0x05, opts));
  26024. if(opts.bookType == "xla") write_biff_rec(A, "Addin");
  26025. write_biff_rec(A, "InterfaceHdr", b8 ? writeuint16(0x04b0) : null);
  26026. write_biff_rec(A, "Mms", writezeroes(2));
  26027. if(b5) write_biff_rec(A, "ToolbarHdr");
  26028. if(b5) write_biff_rec(A, "ToolbarEnd");
  26029. write_biff_rec(A, "InterfaceEnd");
  26030. write_biff_rec(A, "WriteAccess", write_WriteAccess("SheetJS", opts));
  26031. /* [FileSharing] */
  26032. write_biff_rec(A, "CodePage", writeuint16(b8 ? 0x04b0 : 0x04E4));
  26033. /* *2047 Lel */
  26034. if(b8) write_biff_rec(A, "DSF", writeuint16(0));
  26035. if(b8) write_biff_rec(A, "Excel9File");
  26036. write_biff_rec(A, "RRTabId", write_RRTabId(wb.SheetNames.length));
  26037. if(b8 && wb.vbaraw) write_biff_rec(A, "ObProj");
  26038. /* [ObNoMacros] */
  26039. if(b8 && wb.vbaraw) {
  26040. var cname = _wb.CodeName || "ThisWorkbook";
  26041. write_biff_rec(A, "CodeName", write_XLUnicodeString(cname, opts));
  26042. }
  26043. write_biff_rec(A, "BuiltInFnGroupCount", writeuint16(0x11));
  26044. /* *FnGroupName *FnGrp12 */
  26045. /* *Lbl */
  26046. /* [OleObjectSize] */
  26047. write_biff_rec(A, "WinProtect", writebool(false));
  26048. write_biff_rec(A, "Protect", writebool(false));
  26049. write_biff_rec(A, "Password", writeuint16(0));
  26050. if(b8) write_biff_rec(A, "Prot4Rev", writebool(false));
  26051. if(b8) write_biff_rec(A, "Prot4RevPass", writeuint16(0));
  26052. write_biff_rec(A, "Window1", write_Window1(opts));
  26053. write_biff_rec(A, "Backup", writebool(false));
  26054. write_biff_rec(A, "HideObj", writeuint16(0));
  26055. write_biff_rec(A, "Date1904", writebool(safe1904(wb)=="true"));
  26056. write_biff_rec(A, "CalcPrecision", writebool(true));
  26057. if(b8) write_biff_rec(A, "RefreshAll", writebool(false));
  26058. write_biff_rec(A, "BookBool", writeuint16(0));
  26059. /* ... */
  26060. write_FONTS_biff8(A, wb, opts);
  26061. write_FMTS_biff8(A, wb.SSF, opts);
  26062. write_CELLXFS_biff8(A, opts);
  26063. /* ... */
  26064. if(b8) write_biff_rec(A, "UsesELFs", writebool(false));
  26065. var a = A.end();
  26066. var C = buf_array();
  26067. /* METADATA [MTRSettings] [ForceFullCalculation] */
  26068. if(b8) write_biff_rec(C, "Country", write_Country());
  26069. /* *SUPBOOK *LBL *RTD [RecalcId] *HFPicture *MSODRAWINGGROUP */
  26070. /* BIFF8: [SST *Continue] ExtSST */
  26071. if(b8 && opts.Strings) write_biff_continue(C, "SST", write_SST(opts.Strings, opts));
  26072. /* *WebPub [WOpt] [CrErr] [BookExt] *FeatHdr *DConn [THEME] [CompressPictures] [Compat12] [GUIDTypeLib] */
  26073. write_biff_rec(C, "EOF");
  26074. var c = C.end();
  26075. var B = buf_array();
  26076. var blen = 0, j = 0;
  26077. for(j = 0; j < wb.SheetNames.length; ++j) blen += (b8 ? 12 : 11) + (b8 ? 2 : 1) * wb.SheetNames[j].length;
  26078. var start = a.length + blen + c.length;
  26079. for(j = 0; j < wb.SheetNames.length; ++j) {
  26080. var _sheet = _sheets[j] || ({});
  26081. write_biff_rec(B, "BoundSheet8", write_BoundSheet8({pos:start, hs:_sheet.Hidden||0, dt:0, name:wb.SheetNames[j]}, opts));
  26082. start += bufs[j].length;
  26083. }
  26084. /* 1*BoundSheet8 */
  26085. var b = B.end();
  26086. if(blen != b.length) throw new Error("BS8 " + blen + " != " + b.length);
  26087. var out = [];
  26088. if(a.length) out.push(a);
  26089. if(b.length) out.push(b);
  26090. if(c.length) out.push(c);
  26091. return __toBuffer([out]);
  26092. }
  26093. /* [MS-XLS] 2.1.7.20 Workbook Stream */
  26094. function write_biff8_buf(wb, opts) {
  26095. var o = opts || {};
  26096. var bufs = [];
  26097. if(wb && !wb.SSF) {
  26098. wb.SSF = SSF.get_table();
  26099. }
  26100. if(wb && wb.SSF) {
  26101. make_ssf(SSF); SSF.load_table(wb.SSF);
  26102. // $FlowIgnore
  26103. o.revssf = evert_num(wb.SSF); o.revssf[wb.SSF[65535]] = 0;
  26104. o.ssf = wb.SSF;
  26105. }
  26106. o.Strings = []; o.Strings.Count = 0; o.Strings.Unique = 0;
  26107. fix_write_opts(o);
  26108. o.cellXfs = [];
  26109. get_cell_style(o.cellXfs, {}, {revssf:{"General":0}});
  26110. if(!wb.Props) wb.Props = {};
  26111. for(var i = 0; i < wb.SheetNames.length; ++i) bufs[bufs.length] = write_ws_biff8(i, o, wb);
  26112. bufs.unshift(write_biff8_global(wb, bufs, o));
  26113. return __toBuffer([bufs]);
  26114. }
  26115. function write_biff_buf(wb, opts) {
  26116. var o = opts || {};
  26117. switch(o.biff || 2) {
  26118. case 8: case 5: return write_biff8_buf(wb, opts);
  26119. case 4: case 3: case 2: return write_biff2_buf(wb, opts);
  26120. }
  26121. throw new Error("invalid type " + o.bookType + " for BIFF");
  26122. }
  26123. /* note: browser DOM element cannot see mso- style attrs, must parse */
  26124. var HTML_ = (function() {
  26125. function html_to_sheet(str, _opts) {
  26126. var opts = _opts || {};
  26127. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  26128. var ws = opts.dense ? ([]) : ({});
  26129. str = str.replace(/<!--.*?-->/g, "");
  26130. var mtch = str.match(/<table/i);
  26131. if(!mtch) throw new Error("Invalid HTML: could not find <table>");
  26132. var mtch2 = str.match(/<\/table/i);
  26133. var i = mtch.index, j = mtch2 && mtch2.index || str.length;
  26134. var rows = split_regex(str.slice(i, j), /(:?<tr[^>]*>)/i, "<tr>");
  26135. var R = -1, C = 0, RS = 0, CS = 0;
  26136. var range = {s:{r:10000000, c:10000000},e:{r:0,c:0}};
  26137. var merges = [];
  26138. for(i = 0; i < rows.length; ++i) {
  26139. var row = rows[i].trim();
  26140. var hd = row.slice(0,3).toLowerCase();
  26141. if(hd == "<tr") { ++R; if(opts.sheetRows && opts.sheetRows <= R) { --R; break; } C = 0; continue; }
  26142. if(hd != "<td" && hd != "<th") continue;
  26143. var cells = row.split(/<\/t[dh]>/i);
  26144. for(j = 0; j < cells.length; ++j) {
  26145. var cell = cells[j].trim();
  26146. if(!cell.match(/<t[dh]/i)) continue;
  26147. var m = cell, cc = 0;
  26148. /* TODO: parse styles etc */
  26149. while(m.charAt(0) == "<" && (cc = m.indexOf(">")) > -1) m = m.slice(cc+1);
  26150. for(var midx = 0; midx < merges.length; ++midx) {
  26151. var _merge = merges[midx];
  26152. if(_merge.s.c == C && _merge.s.r < R && R <= _merge.e.r) { C = _merge.e.c + 1; midx = -1; }
  26153. }
  26154. var tag = parsexmltag(cell.slice(0, cell.indexOf(">")));
  26155. CS = tag.colspan ? +tag.colspan : 1;
  26156. if((RS = +tag.rowspan)>1 || CS>1) merges.push({s:{r:R,c:C},e:{r:R + (RS||1) - 1, c:C + CS - 1}});
  26157. var _t = tag.t || "";
  26158. /* TODO: generate stub cells */
  26159. if(!m.length) { C += CS; continue; }
  26160. m = htmldecode(m);
  26161. if(range.s.r > R) range.s.r = R; if(range.e.r < R) range.e.r = R;
  26162. if(range.s.c > C) range.s.c = C; if(range.e.c < C) range.e.c = C;
  26163. if(!m.length) continue;
  26164. var o = {t:'s', v:m};
  26165. if(opts.raw || !m.trim().length || _t == 's'){}
  26166. else if(m === 'TRUE') o = {t:'b', v:true};
  26167. else if(m === 'FALSE') o = {t:'b', v:false};
  26168. else if(!isNaN(fuzzynum(m))) o = {t:'n', v:fuzzynum(m)};
  26169. else if(!isNaN(fuzzydate(m).getDate())) {
  26170. o = ({t:'d', v:parseDate(m)});
  26171. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  26172. o.z = opts.dateNF || SSF._table[14];
  26173. }
  26174. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = o; }
  26175. else ws[encode_cell({r:R, c:C})] = o;
  26176. C += CS;
  26177. }
  26178. }
  26179. ws['!ref'] = encode_range(range);
  26180. if(merges.length) ws["!merges"] = merges;
  26181. return ws;
  26182. }
  26183. function html_to_book(str, opts) {
  26184. return sheet_to_workbook(html_to_sheet(str, opts), opts);
  26185. }
  26186. function make_html_row(ws, r, R, o) {
  26187. var M = (ws['!merges'] ||[]);
  26188. var oo = [];
  26189. for(var C = r.s.c; C <= r.e.c; ++C) {
  26190. var RS = 0, CS = 0;
  26191. for(var j = 0; j < M.length; ++j) {
  26192. if(M[j].s.r > R || M[j].s.c > C) continue;
  26193. if(M[j].e.r < R || M[j].e.c < C) continue;
  26194. if(M[j].s.r < R || M[j].s.c < C) { RS = -1; break; }
  26195. RS = M[j].e.r - M[j].s.r + 1; CS = M[j].e.c - M[j].s.c + 1; break;
  26196. }
  26197. if(RS < 0) continue;
  26198. var coord = encode_cell({r:R,c:C});
  26199. var cell = o.dense ? (ws[R]||[])[C] : ws[coord];
  26200. /* TODO: html entities */
  26201. var w = (cell && cell.v != null) && (cell.h || escapehtml(cell.w || (format_cell(cell), cell.w) || "")) || "";
  26202. var sp = ({});
  26203. if(RS > 1) sp.rowspan = RS;
  26204. if(CS > 1) sp.colspan = CS;
  26205. sp.t = cell && cell.t || 'z';
  26206. if(o.editable) w = '<span contenteditable="true">' + w + '</span>';
  26207. sp.id = (o.id || "sjs") + "-" + coord;
  26208. if(sp.t != "z") { sp.v = cell.v; if(cell.z != null) sp.z = cell.z; }
  26209. oo.push(writextag('td', w, sp));
  26210. }
  26211. var preamble = "<tr>";
  26212. return preamble + oo.join("") + "</tr>";
  26213. }
  26214. function make_html_preamble(ws, R, o) {
  26215. var out = [];
  26216. return out.join("") + '<table' + (o && o.id ? ' id="' + o.id + '"' : "") + '>';
  26217. }
  26218. var _BEGIN = '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body>';
  26219. var _END = '</body></html>';
  26220. function sheet_to_html(ws, opts/*, wb:?Workbook*/) {
  26221. var o = opts || {};
  26222. var header = o.header != null ? o.header : _BEGIN;
  26223. var footer = o.footer != null ? o.footer : _END;
  26224. var out = [header];
  26225. var r = decode_range(ws['!ref']);
  26226. o.dense = Array.isArray(ws);
  26227. out.push(make_html_preamble(ws, r, o));
  26228. for(var R = r.s.r; R <= r.e.r; ++R) out.push(make_html_row(ws, r, R, o));
  26229. out.push("</table>" + footer);
  26230. return out.join("");
  26231. }
  26232. return {
  26233. to_workbook: html_to_book,
  26234. to_sheet: html_to_sheet,
  26235. _row: make_html_row,
  26236. BEGIN: _BEGIN,
  26237. END: _END,
  26238. _preamble: make_html_preamble,
  26239. from_sheet: sheet_to_html
  26240. };
  26241. })();
  26242. function sheet_add_dom(ws, table, _opts) {
  26243. var opts = _opts || {};
  26244. if(DENSE != null) opts.dense = DENSE;
  26245. var or_R = 0, or_C = 0;
  26246. if(opts.origin != null) {
  26247. if(typeof opts.origin == 'number') or_R = opts.origin;
  26248. else {
  26249. var _origin = typeof opts.origin == "string" ? decode_cell(opts.origin) : opts.origin;
  26250. or_R = _origin.r; or_C = _origin.c;
  26251. }
  26252. }
  26253. var rows = table.getElementsByTagName('tr');
  26254. var sheetRows = Math.min(opts.sheetRows||10000000, rows.length);
  26255. var range = {s:{r:0,c:0},e:{r:or_R,c:or_C}};
  26256. if(ws["!ref"]) {
  26257. var _range = decode_range(ws["!ref"]);
  26258. range.s.r = Math.min(range.s.r, _range.s.r);
  26259. range.s.c = Math.min(range.s.c, _range.s.c);
  26260. range.e.r = Math.max(range.e.r, _range.e.r);
  26261. range.e.c = Math.max(range.e.c, _range.e.c);
  26262. if(or_R == -1) range.e.r = or_R = _range.e.r + 1;
  26263. }
  26264. var merges = [], midx = 0;
  26265. var rowinfo = ws["!rows"] || (ws["!rows"] = []);
  26266. var _R = 0, R = 0, _C = 0, C = 0, RS = 0, CS = 0;
  26267. if(!ws["!cols"]) ws['!cols'] = [];
  26268. for(; _R < rows.length && R < sheetRows; ++_R) {
  26269. var row = rows[_R];
  26270. if (is_dom_element_hidden(row)) {
  26271. if (opts.display) continue;
  26272. rowinfo[R] = {hidden: true};
  26273. }
  26274. var elts = (row.children);
  26275. for(_C = C = 0; _C < elts.length; ++_C) {
  26276. var elt = elts[_C];
  26277. if (opts.display && is_dom_element_hidden(elt)) continue;
  26278. var v = elt.hasAttribute('v') ? elt.getAttribute('v') : htmldecode(elt.innerHTML);
  26279. var z = elt.getAttribute('z');
  26280. for(midx = 0; midx < merges.length; ++midx) {
  26281. var m = merges[midx];
  26282. if(m.s.c == C + or_C && m.s.r < R + or_R && R + or_R <= m.e.r) { C = m.e.c+1 - or_C; midx = -1; }
  26283. }
  26284. /* TODO: figure out how to extract nonstandard mso- style */
  26285. CS = +elt.getAttribute("colspan") || 1;
  26286. if( ((RS = (+elt.getAttribute("rowspan") || 1)))>1 || CS>1) merges.push({s:{r:R + or_R,c:C + or_C},e:{r:R + or_R + (RS||1) - 1, c:C + or_C + (CS||1) - 1}});
  26287. var o = {t:'s', v:v};
  26288. var _t = elt.getAttribute("t") || "";
  26289. if(v != null) {
  26290. if(v.length == 0) o.t = _t || 'z';
  26291. else if(opts.raw || v.trim().length == 0 || _t == "s"){}
  26292. else if(v === 'TRUE') o = {t:'b', v:true};
  26293. else if(v === 'FALSE') o = {t:'b', v:false};
  26294. else if(!isNaN(fuzzynum(v))) o = {t:'n', v:fuzzynum(v)};
  26295. else if(!isNaN(fuzzydate(v).getDate())) {
  26296. o = ({t:'d', v:parseDate(v)});
  26297. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  26298. o.z = opts.dateNF || SSF._table[14];
  26299. }
  26300. }
  26301. if(o.z === undefined && z != null) o.z = z;
  26302. if(opts.dense) { if(!ws[R + or_R]) ws[R + or_R] = []; ws[R + or_R][C + or_C] = o; }
  26303. else ws[encode_cell({c:C + or_C, r:R + or_R})] = o;
  26304. if(range.e.c < C + or_C) range.e.c = C + or_C;
  26305. C += CS;
  26306. }
  26307. ++R;
  26308. }
  26309. if(merges.length) ws['!merges'] = (ws["!merges"] || []).concat(merges);
  26310. range.e.r = Math.max(range.e.r, R - 1 + or_R);
  26311. ws['!ref'] = encode_range(range);
  26312. if(R >= sheetRows) ws['!fullref'] = encode_range((range.e.r = rows.length-_R+R-1 + or_R,range)); // We can count the real number of rows to parse but we don't to improve the performance
  26313. return ws;
  26314. }
  26315. function parse_dom_table(table, _opts) {
  26316. var opts = _opts || {};
  26317. var ws = opts.dense ? ([]) : ({});
  26318. return sheet_add_dom(ws, table, _opts);
  26319. }
  26320. function table_to_book(table, opts) {
  26321. return sheet_to_workbook(parse_dom_table(table, opts), opts);
  26322. }
  26323. function is_dom_element_hidden(element) {
  26324. var display = '';
  26325. var get_computed_style = get_get_computed_style_function(element);
  26326. if(get_computed_style) display = get_computed_style(element).getPropertyValue('display');
  26327. if(!display) display = element.style.display; // Fallback for cases when getComputedStyle is not available (e.g. an old browser or some Node.js environments) or doesn't work (e.g. if the element is not inserted to a document)
  26328. return display === 'none';
  26329. }
  26330. /* global getComputedStyle */
  26331. function get_get_computed_style_function(element) {
  26332. // The proper getComputedStyle implementation is the one defined in the element window
  26333. if(element.ownerDocument.defaultView && typeof element.ownerDocument.defaultView.getComputedStyle === 'function') return element.ownerDocument.defaultView.getComputedStyle;
  26334. // If it is not available, try to get one from the global namespace
  26335. if(typeof getComputedStyle === 'function') return getComputedStyle;
  26336. return null;
  26337. }
  26338. /* OpenDocument */
  26339. var parse_content_xml = (function() {
  26340. var parse_text_p = function(text) {
  26341. /* 6.1.2 White Space Characters */
  26342. var fixed = text
  26343. .replace(/[\t\r\n]/g, " ").trim().replace(/ +/g, " ")
  26344. .replace(/<text:s\/>/g," ")
  26345. .replace(/<text:s text:c="(\d+)"\/>/g, function($$,$1) { return Array(parseInt($1,10)+1).join(" "); })
  26346. .replace(/<text:tab[^>]*\/>/g,"\t")
  26347. .replace(/<text:line-break\/>/g,"\n");
  26348. var v = unescapexml(fixed.replace(/<[^>]*>/g,""));
  26349. return [v];
  26350. };
  26351. var number_formats = {
  26352. /* ods name: [short ssf fmt, long ssf fmt] */
  26353. day: ["d", "dd"],
  26354. month: ["m", "mm"],
  26355. year: ["y", "yy"],
  26356. hours: ["h", "hh"],
  26357. minutes: ["m", "mm"],
  26358. seconds: ["s", "ss"],
  26359. "am-pm": ["A/P", "AM/PM"],
  26360. "day-of-week": ["ddd", "dddd"],
  26361. era: ["e", "ee"],
  26362. /* there is no native representation of LO "Q" format */
  26363. quarter: ["\\Qm", "m\\\"th quarter\""]
  26364. };
  26365. return function pcx(d, _opts) {
  26366. var opts = _opts || {};
  26367. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  26368. var str = xlml_normalize(d);
  26369. var state = [], tmp;
  26370. var tag;
  26371. var NFtag = {name:""}, NF = "", pidx = 0;
  26372. var sheetag;
  26373. var rowtag;
  26374. var Sheets = {}, SheetNames = [];
  26375. var ws = opts.dense ? ([]) : ({});
  26376. var Rn, q;
  26377. var ctag = ({value:""});
  26378. var textp = "", textpidx = 0, textptag;
  26379. var textR = [];
  26380. var R = -1, C = -1, range = {s: {r:1000000,c:10000000}, e: {r:0, c:0}};
  26381. var row_ol = 0;
  26382. var number_format_map = {};
  26383. var merges = [], mrange = {}, mR = 0, mC = 0;
  26384. var rowinfo = [], rowpeat = 1, colpeat = 1;
  26385. var arrayf = [];
  26386. var WB = {Names:[]};
  26387. var atag = ({});
  26388. var _Ref = ["", ""];
  26389. var comments = [], comment = ({});
  26390. var creator = "", creatoridx = 0;
  26391. var isstub = false, intable = false;
  26392. var i = 0;
  26393. xlmlregex.lastIndex = 0;
  26394. str = str.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  26395. while((Rn = xlmlregex.exec(str))) switch((Rn[3]=Rn[3].replace(/_.*$/,""))) {
  26396. case 'table': case '工作表': // 9.1.2 <table:table>
  26397. if(Rn[1]==='/') {
  26398. if(range.e.c >= range.s.c && range.e.r >= range.s.r) ws['!ref'] = encode_range(range);
  26399. else ws['!ref'] = "A1:A1";
  26400. if(opts.sheetRows > 0 && opts.sheetRows <= range.e.r) {
  26401. ws['!fullref'] = ws['!ref'];
  26402. range.e.r = opts.sheetRows - 1;
  26403. ws['!ref'] = encode_range(range);
  26404. }
  26405. if(merges.length) ws['!merges'] = merges;
  26406. if(rowinfo.length) ws["!rows"] = rowinfo;
  26407. sheetag.name = sheetag['名称'] || sheetag.name;
  26408. if(typeof JSON !== 'undefined') JSON.stringify(sheetag);
  26409. SheetNames.push(sheetag.name);
  26410. Sheets[sheetag.name] = ws;
  26411. intable = false;
  26412. }
  26413. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  26414. sheetag = parsexmltag(Rn[0], false);
  26415. R = C = -1;
  26416. range.s.r = range.s.c = 10000000; range.e.r = range.e.c = 0;
  26417. ws = opts.dense ? ([]) : ({}); merges = [];
  26418. rowinfo = [];
  26419. intable = true;
  26420. }
  26421. break;
  26422. case 'table-row-group': // 9.1.9 <table:table-row-group>
  26423. if(Rn[1] === "/") --row_ol; else ++row_ol;
  26424. break;
  26425. case 'table-row': case '行': // 9.1.3 <table:table-row>
  26426. if(Rn[1] === '/') { R+=rowpeat; rowpeat = 1; break; }
  26427. rowtag = parsexmltag(Rn[0], false);
  26428. if(rowtag['行号']) R = rowtag['行号'] - 1; else if(R == -1) R = 0;
  26429. rowpeat = +rowtag['number-rows-repeated'] || 1;
  26430. /* TODO: remove magic */
  26431. if(rowpeat < 10) for(i = 0; i < rowpeat; ++i) if(row_ol > 0) rowinfo[R + i] = {level: row_ol};
  26432. C = -1; break;
  26433. case 'covered-table-cell': // 9.1.5 <table:covered-table-cell>
  26434. if(Rn[1] !== '/') ++C;
  26435. if(opts.sheetStubs) {
  26436. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = {t:'z'}; }
  26437. else ws[encode_cell({r:R,c:C})] = {t:'z'};
  26438. }
  26439. textp = ""; textR = [];
  26440. break; /* stub */
  26441. case 'table-cell': case '数据':
  26442. if(Rn[0].charAt(Rn[0].length-2) === '/') {
  26443. ++C;
  26444. ctag = parsexmltag(Rn[0], false);
  26445. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  26446. q = ({t:'z', v:null});
  26447. if(ctag.formula && opts.cellFormula != false) q.f = ods_to_csf_formula(unescapexml(ctag.formula));
  26448. if((ctag['数据类型'] || ctag['value-type']) == "string") {
  26449. q.t = "s"; q.v = unescapexml(ctag['string-value'] || "");
  26450. if(opts.dense) {
  26451. if(!ws[R]) ws[R] = [];
  26452. ws[R][C] = q;
  26453. } else {
  26454. ws[encode_cell({r:R,c:C})] = q;
  26455. }
  26456. }
  26457. C+= colpeat-1;
  26458. } else if(Rn[1]!=='/') {
  26459. ++C;
  26460. colpeat = 1;
  26461. var rptR = rowpeat ? R + rowpeat - 1 : R;
  26462. if(C > range.e.c) range.e.c = C;
  26463. if(C < range.s.c) range.s.c = C;
  26464. if(R < range.s.r) range.s.r = R;
  26465. if(rptR > range.e.r) range.e.r = rptR;
  26466. ctag = parsexmltag(Rn[0], false);
  26467. comments = []; comment = ({});
  26468. q = ({t:ctag['数据类型'] || ctag['value-type'], v:null});
  26469. if(opts.cellFormula) {
  26470. if(ctag.formula) ctag.formula = unescapexml(ctag.formula);
  26471. if(ctag['number-matrix-columns-spanned'] && ctag['number-matrix-rows-spanned']) {
  26472. mR = parseInt(ctag['number-matrix-rows-spanned'],10) || 0;
  26473. mC = parseInt(ctag['number-matrix-columns-spanned'],10) || 0;
  26474. mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
  26475. q.F = encode_range(mrange);
  26476. arrayf.push([mrange, q.F]);
  26477. }
  26478. if(ctag.formula) q.f = ods_to_csf_formula(ctag.formula);
  26479. else for(i = 0; i < arrayf.length; ++i)
  26480. if(R >= arrayf[i][0].s.r && R <= arrayf[i][0].e.r)
  26481. if(C >= arrayf[i][0].s.c && C <= arrayf[i][0].e.c)
  26482. q.F = arrayf[i][1];
  26483. }
  26484. if(ctag['number-columns-spanned'] || ctag['number-rows-spanned']) {
  26485. mR = parseInt(ctag['number-rows-spanned'],10) || 0;
  26486. mC = parseInt(ctag['number-columns-spanned'],10) || 0;
  26487. mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
  26488. merges.push(mrange);
  26489. }
  26490. /* 19.675.2 table:number-columns-repeated */
  26491. if(ctag['number-columns-repeated']) colpeat = parseInt(ctag['number-columns-repeated'], 10);
  26492. /* 19.385 office:value-type */
  26493. switch(q.t) {
  26494. case 'boolean': q.t = 'b'; q.v = parsexmlbool(ctag['boolean-value']); break;
  26495. case 'float': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  26496. case 'percentage': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  26497. case 'currency': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  26498. case 'date': q.t = 'd'; q.v = parseDate(ctag['date-value']);
  26499. if(!opts.cellDates) { q.t = 'n'; q.v = datenum(q.v); }
  26500. q.z = 'm/d/yy'; break;
  26501. case 'time': q.t = 'n'; q.v = parse_isodur(ctag['time-value'])/86400; break;
  26502. case 'number': q.t = 'n'; q.v = parseFloat(ctag['数据数值']); break;
  26503. default:
  26504. if(q.t === 'string' || q.t === 'text' || !q.t) {
  26505. q.t = 's';
  26506. if(ctag['string-value'] != null) { textp = unescapexml(ctag['string-value']); textR = []; }
  26507. } else throw new Error('Unsupported value type ' + q.t);
  26508. }
  26509. } else {
  26510. isstub = false;
  26511. if(q.t === 's') {
  26512. q.v = textp || '';
  26513. if(textR.length) q.R = textR;
  26514. isstub = textpidx == 0;
  26515. }
  26516. if(atag.Target) q.l = atag;
  26517. if(comments.length > 0) { q.c = comments; comments = []; }
  26518. if(textp && opts.cellText !== false) q.w = textp;
  26519. if(isstub) { q.t = "z"; delete q.v; }
  26520. if(!isstub || opts.sheetStubs) {
  26521. if(!(opts.sheetRows && opts.sheetRows <= R)) {
  26522. for(var rpt = 0; rpt < rowpeat; ++rpt) {
  26523. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  26524. if(opts.dense) {
  26525. if(!ws[R + rpt]) ws[R + rpt] = [];
  26526. ws[R + rpt][C] = rpt == 0 ? q : dup(q);
  26527. while(--colpeat > 0) ws[R + rpt][C + colpeat] = dup(q);
  26528. } else {
  26529. ws[encode_cell({r:R + rpt,c:C})] = q;
  26530. while(--colpeat > 0) ws[encode_cell({r:R + rpt,c:C + colpeat})] = dup(q);
  26531. }
  26532. if(range.e.c <= C) range.e.c = C;
  26533. }
  26534. }
  26535. }
  26536. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  26537. C += colpeat-1; colpeat = 0;
  26538. q = {};
  26539. textp = ""; textR = [];
  26540. }
  26541. atag = ({});
  26542. break; // 9.1.4 <table:table-cell>
  26543. /* pure state */
  26544. case 'document': // TODO: <office:document> is the root for FODS
  26545. case 'document-content': case '电子表格文档': // 3.1.3.2 <office:document-content>
  26546. case 'spreadsheet': case '主体': // 3.7 <office:spreadsheet>
  26547. case 'scripts': // 3.12 <office:scripts>
  26548. case 'styles': // TODO <office:styles>
  26549. case 'font-face-decls': // 3.14 <office:font-face-decls>
  26550. case 'master-styles': //3.15.4 <office:master-styles> -- relevant for FODS
  26551. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
  26552. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  26553. break;
  26554. case 'annotation': // 14.1 <office:annotation>
  26555. if(Rn[1]==='/'){
  26556. if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
  26557. comment.t = textp;
  26558. if(textR.length) comment.R = textR;
  26559. comment.a = creator;
  26560. comments.push(comment);
  26561. }
  26562. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {state.push([Rn[3], false]);}
  26563. creator = ""; creatoridx = 0;
  26564. textp = ""; textpidx = 0; textR = [];
  26565. break;
  26566. case 'creator': // 4.3.2.7 <dc:creator>
  26567. if(Rn[1]==='/') { creator = str.slice(creatoridx,Rn.index); }
  26568. else creatoridx = Rn.index + Rn[0].length;
  26569. break;
  26570. /* ignore state */
  26571. case 'meta': case '元数据': // TODO: <office:meta> <uof:元数据> FODS/UOF
  26572. case 'settings': // TODO: <office:settings>
  26573. case 'config-item-set': // TODO: <office:config-item-set>
  26574. case 'config-item-map-indexed': // TODO: <office:config-item-map-indexed>
  26575. case 'config-item-map-entry': // TODO: <office:config-item-map-entry>
  26576. case 'config-item-map-named': // TODO: <office:config-item-map-entry>
  26577. case 'shapes': // 9.2.8 <table:shapes>
  26578. case 'frame': // 10.4.2 <draw:frame>
  26579. case 'text-box': // 10.4.3 <draw:text-box>
  26580. case 'image': // 10.4.4 <draw:image>
  26581. case 'data-pilot-tables': // 9.6.2 <table:data-pilot-tables>
  26582. case 'list-style': // 16.30 <text:list-style>
  26583. case 'form': // 13.13 <form:form>
  26584. case 'dde-links': // 9.8 <table:dde-links>
  26585. case 'event-listeners': // TODO
  26586. case 'chart': // TODO
  26587. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
  26588. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], false]);
  26589. textp = ""; textpidx = 0; textR = [];
  26590. break;
  26591. case 'scientific-number': // TODO: <number:scientific-number>
  26592. break;
  26593. case 'currency-symbol': // TODO: <number:currency-symbol>
  26594. break;
  26595. case 'currency-style': // TODO: <number:currency-style>
  26596. break;
  26597. case 'number-style': // 16.27.2 <number:number-style>
  26598. case 'percentage-style': // 16.27.9 <number:percentage-style>
  26599. case 'date-style': // 16.27.10 <number:date-style>
  26600. case 'time-style': // 16.27.18 <number:time-style>
  26601. if(Rn[1]==='/'){
  26602. number_format_map[NFtag.name] = NF;
  26603. if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
  26604. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  26605. NF = "";
  26606. NFtag = parsexmltag(Rn[0], false);
  26607. state.push([Rn[3], true]);
  26608. } break;
  26609. case 'script': break; // 3.13 <office:script>
  26610. case 'libraries': break; // TODO: <ooo:libraries>
  26611. case 'automatic-styles': break; // 3.15.3 <office:automatic-styles>
  26612. case 'default-style': // TODO: <style:default-style>
  26613. case 'page-layout': break; // TODO: <style:page-layout>
  26614. case 'style': // 16.2 <style:style>
  26615. break;
  26616. case 'map': break; // 16.3 <style:map>
  26617. case 'font-face': break; // 16.21 <style:font-face>
  26618. case 'paragraph-properties': break; // 17.6 <style:paragraph-properties>
  26619. case 'table-properties': break; // 17.15 <style:table-properties>
  26620. case 'table-column-properties': break; // 17.16 <style:table-column-properties>
  26621. case 'table-row-properties': break; // 17.17 <style:table-row-properties>
  26622. case 'table-cell-properties': break; // 17.18 <style:table-cell-properties>
  26623. case 'number': // 16.27.3 <number:number>
  26624. switch(state[state.length-1][0]) {
  26625. case 'time-style':
  26626. case 'date-style':
  26627. tag = parsexmltag(Rn[0], false);
  26628. NF += number_formats[Rn[3]][tag.style==='long'?1:0]; break;
  26629. } break;
  26630. case 'fraction': break; // TODO 16.27.6 <number:fraction>
  26631. case 'day': // 16.27.11 <number:day>
  26632. case 'month': // 16.27.12 <number:month>
  26633. case 'year': // 16.27.13 <number:year>
  26634. case 'era': // 16.27.14 <number:era>
  26635. case 'day-of-week': // 16.27.15 <number:day-of-week>
  26636. case 'week-of-year': // 16.27.16 <number:week-of-year>
  26637. case 'quarter': // 16.27.17 <number:quarter>
  26638. case 'hours': // 16.27.19 <number:hours>
  26639. case 'minutes': // 16.27.20 <number:minutes>
  26640. case 'seconds': // 16.27.21 <number:seconds>
  26641. case 'am-pm': // 16.27.22 <number:am-pm>
  26642. switch(state[state.length-1][0]) {
  26643. case 'time-style':
  26644. case 'date-style':
  26645. tag = parsexmltag(Rn[0], false);
  26646. NF += number_formats[Rn[3]][tag.style==='long'?1:0]; break;
  26647. } break;
  26648. case 'boolean-style': break; // 16.27.23 <number:boolean-style>
  26649. case 'boolean': break; // 16.27.24 <number:boolean>
  26650. case 'text-style': break; // 16.27.25 <number:text-style>
  26651. case 'text': // 16.27.26 <number:text>
  26652. if(Rn[0].slice(-2) === "/>") break;
  26653. else if(Rn[1]==="/") switch(state[state.length-1][0]) {
  26654. case 'number-style':
  26655. case 'date-style':
  26656. case 'time-style':
  26657. NF += str.slice(pidx, Rn.index);
  26658. break;
  26659. }
  26660. else pidx = Rn.index + Rn[0].length;
  26661. break;
  26662. case 'named-range': // 9.4.12 <table:named-range>
  26663. tag = parsexmltag(Rn[0], false);
  26664. _Ref = ods_to_csf_3D(tag['cell-range-address']);
  26665. var nrange = ({Name:tag.name, Ref:_Ref[0] + '!' + _Ref[1]});
  26666. if(intable) nrange.Sheet = SheetNames.length;
  26667. WB.Names.push(nrange);
  26668. break;
  26669. case 'text-content': break; // 16.27.27 <number:text-content>
  26670. case 'text-properties': break; // 16.27.27 <style:text-properties>
  26671. case 'embedded-text': break; // 16.27.4 <number:embedded-text>
  26672. case 'body': case '电子表格': break; // 3.3 16.9.6 19.726.3
  26673. case 'forms': break; // 12.25.2 13.2
  26674. case 'table-column': break; // 9.1.6 <table:table-column>
  26675. case 'table-header-rows': break; // 9.1.7 <table:table-header-rows>
  26676. case 'table-rows': break; // 9.1.12 <table:table-rows>
  26677. /* TODO: outline levels */
  26678. case 'table-column-group': break; // 9.1.10 <table:table-column-group>
  26679. case 'table-header-columns': break; // 9.1.11 <table:table-header-columns>
  26680. case 'table-columns': break; // 9.1.12 <table:table-columns>
  26681. case 'null-date': break; // 9.4.2 <table:null-date> TODO: date1904
  26682. case 'graphic-properties': break; // 17.21 <style:graphic-properties>
  26683. case 'calculation-settings': break; // 9.4.1 <table:calculation-settings>
  26684. case 'named-expressions': break; // 9.4.11 <table:named-expressions>
  26685. case 'label-range': break; // 9.4.9 <table:label-range>
  26686. case 'label-ranges': break; // 9.4.10 <table:label-ranges>
  26687. case 'named-expression': break; // 9.4.13 <table:named-expression>
  26688. case 'sort': break; // 9.4.19 <table:sort>
  26689. case 'sort-by': break; // 9.4.20 <table:sort-by>
  26690. case 'sort-groups': break; // 9.4.22 <table:sort-groups>
  26691. case 'tab': break; // 6.1.4 <text:tab>
  26692. case 'line-break': break; // 6.1.5 <text:line-break>
  26693. case 'span': break; // 6.1.7 <text:span>
  26694. case 'p': case '文本串': // 5.1.3 <text:p>
  26695. if(['master-styles'].indexOf(state[state.length-1][0]) > -1) break;
  26696. if(Rn[1]==='/' && (!ctag || !ctag['string-value'])) {
  26697. var ptp = parse_text_p(str.slice(textpidx,Rn.index), textptag);
  26698. textp = (textp.length > 0 ? textp + "\n" : "") + ptp[0];
  26699. } else { textptag = parsexmltag(Rn[0], false); textpidx = Rn.index + Rn[0].length; }
  26700. break; // <text:p>
  26701. case 's': break; // <text:s>
  26702. case 'database-range': // 9.4.15 <table:database-range>
  26703. if(Rn[1]==='/') break;
  26704. try {
  26705. _Ref = ods_to_csf_3D(parsexmltag(Rn[0])['target-range-address']);
  26706. Sheets[_Ref[0]]['!autofilter'] = { ref:_Ref[1] };
  26707. } catch(e) {/* empty */}
  26708. break;
  26709. case 'date': break; // <*:date>
  26710. case 'object': break; // 10.4.6.2 <draw:object>
  26711. case 'title': case '标题': break; // <*:title> OR <uof:标题>
  26712. case 'desc': break; // <*:desc>
  26713. case 'binary-data': break; // 10.4.5 TODO: b64 blob
  26714. /* 9.2 Advanced Tables */
  26715. case 'table-source': break; // 9.2.6
  26716. case 'scenario': break; // 9.2.6
  26717. case 'iteration': break; // 9.4.3 <table:iteration>
  26718. case 'content-validations': break; // 9.4.4 <table:
  26719. case 'content-validation': break; // 9.4.5 <table:
  26720. case 'help-message': break; // 9.4.6 <table:
  26721. case 'error-message': break; // 9.4.7 <table:
  26722. case 'database-ranges': break; // 9.4.14 <table:database-ranges>
  26723. case 'filter': break; // 9.5.2 <table:filter>
  26724. case 'filter-and': break; // 9.5.3 <table:filter-and>
  26725. case 'filter-or': break; // 9.5.4 <table:filter-or>
  26726. case 'filter-condition': break; // 9.5.5 <table:filter-condition>
  26727. case 'list-level-style-bullet': break; // 16.31 <text:
  26728. case 'list-level-style-number': break; // 16.32 <text:
  26729. case 'list-level-properties': break; // 17.19 <style:
  26730. /* 7.3 Document Fields */
  26731. case 'sender-firstname': // 7.3.6.2
  26732. case 'sender-lastname': // 7.3.6.3
  26733. case 'sender-initials': // 7.3.6.4
  26734. case 'sender-title': // 7.3.6.5
  26735. case 'sender-position': // 7.3.6.6
  26736. case 'sender-email': // 7.3.6.7
  26737. case 'sender-phone-private': // 7.3.6.8
  26738. case 'sender-fax': // 7.3.6.9
  26739. case 'sender-company': // 7.3.6.10
  26740. case 'sender-phone-work': // 7.3.6.11
  26741. case 'sender-street': // 7.3.6.12
  26742. case 'sender-city': // 7.3.6.13
  26743. case 'sender-postal-code': // 7.3.6.14
  26744. case 'sender-country': // 7.3.6.15
  26745. case 'sender-state-or-province': // 7.3.6.16
  26746. case 'author-name': // 7.3.7.1
  26747. case 'author-initials': // 7.3.7.2
  26748. case 'chapter': // 7.3.8
  26749. case 'file-name': // 7.3.9
  26750. case 'template-name': // 7.3.9
  26751. case 'sheet-name': // 7.3.9
  26752. break;
  26753. case 'event-listener':
  26754. break;
  26755. /* TODO: FODS Properties */
  26756. case 'initial-creator':
  26757. case 'creation-date':
  26758. case 'print-date':
  26759. case 'generator':
  26760. case 'document-statistic':
  26761. case 'user-defined':
  26762. case 'editing-duration':
  26763. case 'editing-cycles':
  26764. break;
  26765. /* TODO: FODS Config */
  26766. case 'config-item':
  26767. break;
  26768. /* TODO: style tokens */
  26769. case 'page-number': break; // TODO <text:page-number>
  26770. case 'page-count': break; // TODO <text:page-count>
  26771. case 'time': break; // TODO <text:time>
  26772. /* 9.3 Advanced Table Cells */
  26773. case 'cell-range-source': break; // 9.3.1 <table:
  26774. case 'detective': break; // 9.3.2 <table:
  26775. case 'operation': break; // 9.3.3 <table:
  26776. case 'highlighted-range': break; // 9.3.4 <table:
  26777. /* 9.6 Data Pilot Tables <table: */
  26778. case 'data-pilot-table': // 9.6.3
  26779. case 'source-cell-range': // 9.6.5
  26780. case 'source-service': // 9.6.6
  26781. case 'data-pilot-field': // 9.6.7
  26782. case 'data-pilot-level': // 9.6.8
  26783. case 'data-pilot-subtotals': // 9.6.9
  26784. case 'data-pilot-subtotal': // 9.6.10
  26785. case 'data-pilot-members': // 9.6.11
  26786. case 'data-pilot-member': // 9.6.12
  26787. case 'data-pilot-display-info': // 9.6.13
  26788. case 'data-pilot-sort-info': // 9.6.14
  26789. case 'data-pilot-layout-info': // 9.6.15
  26790. case 'data-pilot-field-reference': // 9.6.16
  26791. case 'data-pilot-groups': // 9.6.17
  26792. case 'data-pilot-group': // 9.6.18
  26793. case 'data-pilot-group-member': // 9.6.19
  26794. break;
  26795. /* 10.3 Drawing Shapes */
  26796. case 'rect': // 10.3.2
  26797. break;
  26798. /* 14.6 DDE Connections */
  26799. case 'dde-connection-decls': // 14.6.2 <text:
  26800. case 'dde-connection-decl': // 14.6.3 <text:
  26801. case 'dde-link': // 14.6.4 <table:
  26802. case 'dde-source': // 14.6.5 <office:
  26803. break;
  26804. case 'properties': break; // 13.7 <form:properties>
  26805. case 'property': break; // 13.8 <form:property>
  26806. case 'a': // 6.1.8 hyperlink
  26807. if(Rn[1]!== '/') {
  26808. atag = parsexmltag(Rn[0], false);
  26809. if(!atag.href) break;
  26810. atag.Target = atag.href; delete atag.href;
  26811. if(atag.Target.charAt(0) == "#" && atag.Target.indexOf(".") > -1) {
  26812. _Ref = ods_to_csf_3D(atag.Target.slice(1));
  26813. atag.Target = "#" + _Ref[0] + "!" + _Ref[1];
  26814. }
  26815. }
  26816. break;
  26817. /* non-standard */
  26818. case 'table-protection': break;
  26819. case 'data-pilot-grand-total': break; // <table:
  26820. case 'office-document-common-attrs': break; // bare
  26821. default: switch(Rn[2]) {
  26822. case 'dc:': // TODO: properties
  26823. case 'calcext:': // ignore undocumented extensions
  26824. case 'loext:': // ignore undocumented extensions
  26825. case 'ooo:': // ignore undocumented extensions
  26826. case 'chartooo:': // ignore undocumented extensions
  26827. case 'draw:': // TODO: drawing
  26828. case 'style:': // TODO: styles
  26829. case 'chart:': // TODO: charts
  26830. case 'form:': // TODO: forms
  26831. case 'uof:': // TODO: uof
  26832. case '表:': // TODO: uof
  26833. case '字:': // TODO: uof
  26834. break;
  26835. default: if(opts.WTF) throw new Error(Rn);
  26836. }
  26837. }
  26838. var out = ({
  26839. Sheets: Sheets,
  26840. SheetNames: SheetNames,
  26841. Workbook: WB
  26842. });
  26843. if(opts.bookSheets) delete out.Sheets;
  26844. return out;
  26845. };
  26846. })();
  26847. function parse_ods(zip, opts) {
  26848. opts = opts || ({});
  26849. var ods = !!safegetzipfile(zip, 'objectdata');
  26850. if(ods) parse_manifest(getzipdata(zip, 'META-INF/manifest.xml'), opts);
  26851. var content = getzipstr(zip, 'content.xml');
  26852. if(!content) throw new Error("Missing content.xml in " + (ods ? "ODS" : "UOF")+ " file");
  26853. var wb = parse_content_xml(ods ? content : utf8read(content), opts);
  26854. if(safegetzipfile(zip, 'meta.xml')) wb.Props = parse_core_props(getzipdata(zip, 'meta.xml'));
  26855. return wb;
  26856. }
  26857. function parse_fods(data, opts) {
  26858. return parse_content_xml(data, opts);
  26859. }
  26860. /* OpenDocument */
  26861. var write_styles_ods = (function() {
  26862. var payload = '<office:document-styles ' + wxt_helper({
  26863. 'xmlns:office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
  26864. 'xmlns:table': "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
  26865. 'xmlns:style': "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
  26866. 'xmlns:text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
  26867. 'xmlns:draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
  26868. 'xmlns:fo': "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
  26869. 'xmlns:xlink': "http://www.w3.org/1999/xlink",
  26870. 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
  26871. 'xmlns:number': "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
  26872. 'xmlns:svg': "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
  26873. 'xmlns:of': "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
  26874. 'office:version': "1.2"
  26875. }) + '></office:document-styles>';
  26876. return function wso() {
  26877. return XML_HEADER + payload;
  26878. };
  26879. })();
  26880. var write_content_ods = (function() {
  26881. /* 6.1.2 White Space Characters */
  26882. var write_text_p = function(text) {
  26883. return escapexml(text)
  26884. .replace(/ +/g, function($$){return '<text:s text:c="'+$$.length+'"/>';})
  26885. .replace(/\t/g, "<text:tab/>")
  26886. .replace(/\n/g, "<text:line-break/>")
  26887. .replace(/^ /, "<text:s/>").replace(/ $/, "<text:s/>");
  26888. };
  26889. var null_cell_xml = ' <table:table-cell />\n';
  26890. var covered_cell_xml = ' <table:covered-table-cell/>\n';
  26891. var write_ws = function(ws, wb, i) {
  26892. /* Section 9 Tables */
  26893. var o = [];
  26894. o.push(' <table:table table:name="' + escapexml(wb.SheetNames[i]) + '" table:style-name="ta1">\n');
  26895. var R=0,C=0, range = decode_range(ws['!ref']);
  26896. var marr = ws['!merges'] || [], mi = 0;
  26897. var dense = Array.isArray(ws);
  26898. for(R = 0; R < range.s.r; ++R) o.push(' <table:table-row></table:table-row>\n');
  26899. for(; R <= range.e.r; ++R) {
  26900. o.push(' <table:table-row>\n');
  26901. for(C=0; C < range.s.c; ++C) o.push(null_cell_xml);
  26902. for(; C <= range.e.c; ++C) {
  26903. var skip = false, ct = {}, textp = "";
  26904. for(mi = 0; mi != marr.length; ++mi) {
  26905. if(marr[mi].s.c > C) continue;
  26906. if(marr[mi].s.r > R) continue;
  26907. if(marr[mi].e.c < C) continue;
  26908. if(marr[mi].e.r < R) continue;
  26909. if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
  26910. ct['table:number-columns-spanned'] = (marr[mi].e.c - marr[mi].s.c + 1);
  26911. ct['table:number-rows-spanned'] = (marr[mi].e.r - marr[mi].s.r + 1);
  26912. break;
  26913. }
  26914. if(skip) { o.push(covered_cell_xml); continue; }
  26915. var ref = encode_cell({r:R, c:C}), cell = dense ? (ws[R]||[])[C]: ws[ref];
  26916. if(cell && cell.f) {
  26917. ct['table:formula'] = escapexml(csf_to_ods_formula(cell.f));
  26918. if(cell.F) {
  26919. if(cell.F.slice(0, ref.length) == ref) {
  26920. var _Fref = decode_range(cell.F);
  26921. ct['table:number-matrix-columns-spanned'] = (_Fref.e.c - _Fref.s.c + 1);
  26922. ct['table:number-matrix-rows-spanned'] = (_Fref.e.r - _Fref.s.r + 1);
  26923. }
  26924. }
  26925. }
  26926. if(!cell) { o.push(null_cell_xml); continue; }
  26927. switch(cell.t) {
  26928. case 'b':
  26929. textp = (cell.v ? 'TRUE' : 'FALSE');
  26930. ct['office:value-type'] = "boolean";
  26931. ct['office:boolean-value'] = (cell.v ? 'true' : 'false');
  26932. break;
  26933. case 'n':
  26934. textp = (cell.w||String(cell.v||0));
  26935. ct['office:value-type'] = "float";
  26936. ct['office:value'] = (cell.v||0);
  26937. break;
  26938. case 's': case 'str':
  26939. textp = cell.v == null ? "" : cell.v;
  26940. ct['office:value-type'] = "string";
  26941. break;
  26942. case 'd':
  26943. textp = (cell.w||(parseDate(cell.v).toISOString()));
  26944. ct['office:value-type'] = "date";
  26945. ct['office:date-value'] = (parseDate(cell.v).toISOString());
  26946. ct['table:style-name'] = "ce1";
  26947. break;
  26948. //case 'e':
  26949. default: o.push(null_cell_xml); continue;
  26950. }
  26951. var text_p = write_text_p(textp);
  26952. if(cell.l && cell.l.Target) {
  26953. var _tgt = cell.l.Target; _tgt = _tgt.charAt(0) == "#" ? "#" + csf_to_ods_3D(_tgt.slice(1)) : _tgt;
  26954. text_p = writextag('text:a', text_p, {'xlink:href': _tgt});
  26955. }
  26956. o.push(' ' + writextag('table:table-cell', writextag('text:p', text_p, {}), ct) + '\n');
  26957. }
  26958. o.push(' </table:table-row>\n');
  26959. }
  26960. o.push(' </table:table>\n');
  26961. return o.join("");
  26962. };
  26963. var write_automatic_styles_ods = function(o) {
  26964. o.push(' <office:automatic-styles>\n');
  26965. o.push(' <number:date-style style:name="N37" number:automatic-order="true">\n');
  26966. o.push(' <number:month number:style="long"/>\n');
  26967. o.push(' <number:text>/</number:text>\n');
  26968. o.push(' <number:day number:style="long"/>\n');
  26969. o.push(' <number:text>/</number:text>\n');
  26970. o.push(' <number:year/>\n');
  26971. o.push(' </number:date-style>\n');
  26972. /* table */
  26973. o.push(' <style:style style:name="ta1" style:family="table">\n'); // style:master-page-name="mp1">\n');
  26974. o.push(' <style:table-properties table:display="true" style:writing-mode="lr-tb"/>\n');
  26975. o.push(' </style:style>\n');
  26976. /* table cells, text */
  26977. o.push(' <style:style style:name="ce1" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N37"/>\n');
  26978. /* page-layout */
  26979. o.push(' </office:automatic-styles>\n');
  26980. };
  26981. return function wcx(wb, opts) {
  26982. var o = [XML_HEADER];
  26983. /* 3.1.3.2 */
  26984. var attr = wxt_helper({
  26985. 'xmlns:office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
  26986. 'xmlns:table': "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
  26987. 'xmlns:style': "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
  26988. 'xmlns:text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
  26989. 'xmlns:draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
  26990. 'xmlns:fo': "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
  26991. 'xmlns:xlink': "http://www.w3.org/1999/xlink",
  26992. 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
  26993. 'xmlns:meta': "urn:oasis:names:tc:opendocument:xmlns:meta:1.0",
  26994. 'xmlns:number': "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
  26995. 'xmlns:presentation': "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
  26996. 'xmlns:svg': "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
  26997. 'xmlns:chart': "urn:oasis:names:tc:opendocument:xmlns:chart:1.0",
  26998. 'xmlns:dr3d': "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0",
  26999. 'xmlns:math': "http://www.w3.org/1998/Math/MathML",
  27000. 'xmlns:form': "urn:oasis:names:tc:opendocument:xmlns:form:1.0",
  27001. 'xmlns:script': "urn:oasis:names:tc:opendocument:xmlns:script:1.0",
  27002. 'xmlns:ooo': "http://openoffice.org/2004/office",
  27003. 'xmlns:ooow': "http://openoffice.org/2004/writer",
  27004. 'xmlns:oooc': "http://openoffice.org/2004/calc",
  27005. 'xmlns:dom': "http://www.w3.org/2001/xml-events",
  27006. 'xmlns:xforms': "http://www.w3.org/2002/xforms",
  27007. 'xmlns:xsd': "http://www.w3.org/2001/XMLSchema",
  27008. 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance",
  27009. 'xmlns:sheet': "urn:oasis:names:tc:opendocument:sh33tjs:1.0",
  27010. 'xmlns:rpt': "http://openoffice.org/2005/report",
  27011. 'xmlns:of': "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
  27012. 'xmlns:xhtml': "http://www.w3.org/1999/xhtml",
  27013. 'xmlns:grddl': "http://www.w3.org/2003/g/data-view#",
  27014. 'xmlns:tableooo': "http://openoffice.org/2009/table",
  27015. 'xmlns:drawooo': "http://openoffice.org/2010/draw",
  27016. 'xmlns:calcext': "urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0",
  27017. 'xmlns:loext': "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0",
  27018. 'xmlns:field': "urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0",
  27019. 'xmlns:formx': "urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0",
  27020. 'xmlns:css3t': "http://www.w3.org/TR/css3-text/",
  27021. 'office:version': "1.2"
  27022. });
  27023. var fods = wxt_helper({
  27024. 'xmlns:config': "urn:oasis:names:tc:opendocument:xmlns:config:1.0",
  27025. 'office:mimetype': "application/vnd.oasis.opendocument.spreadsheet"
  27026. });
  27027. if(opts.bookType == "fods") o.push('<office:document' + attr + fods + '>\n');
  27028. else o.push('<office:document-content' + attr + '>\n');
  27029. write_automatic_styles_ods(o);
  27030. o.push(' <office:body>\n');
  27031. o.push(' <office:spreadsheet>\n');
  27032. for(var i = 0; i != wb.SheetNames.length; ++i) o.push(write_ws(wb.Sheets[wb.SheetNames[i]], wb, i, opts));
  27033. o.push(' </office:spreadsheet>\n');
  27034. o.push(' </office:body>\n');
  27035. if(opts.bookType == "fods") o.push('</office:document>');
  27036. else o.push('</office:document-content>');
  27037. return o.join("");
  27038. };
  27039. })();
  27040. function write_ods(wb, opts) {
  27041. if(opts.bookType == "fods") return write_content_ods(wb, opts);
  27042. var zip = zip_new();
  27043. var f = "";
  27044. var manifest = [];
  27045. var rdf = [];
  27046. /* Part 3 Section 3.3 MIME Media Type */
  27047. f = "mimetype";
  27048. zip_add_file(zip, f, "application/vnd.oasis.opendocument.spreadsheet");
  27049. /* Part 1 Section 2.2 Documents */
  27050. f = "content.xml";
  27051. zip_add_file(zip, f, write_content_ods(wb, opts));
  27052. manifest.push([f, "text/xml"]);
  27053. rdf.push([f, "ContentFile"]);
  27054. /* TODO: these are hard-coded styles to satiate excel */
  27055. f = "styles.xml";
  27056. zip_add_file(zip, f, write_styles_ods(wb, opts));
  27057. manifest.push([f, "text/xml"]);
  27058. rdf.push([f, "StylesFile"]);
  27059. /* TODO: this is hard-coded to satiate excel */
  27060. f = "meta.xml";
  27061. zip_add_file(zip, f, write_meta_ods());
  27062. manifest.push([f, "text/xml"]);
  27063. rdf.push([f, "MetadataFile"]);
  27064. /* Part 3 Section 6 Metadata Manifest File */
  27065. f = "manifest.rdf";
  27066. zip_add_file(zip, f, write_rdf(rdf/*, opts*/));
  27067. manifest.push([f, "application/rdf+xml"]);
  27068. /* Part 3 Section 4 Manifest File */
  27069. f = "META-INF/manifest.xml";
  27070. zip_add_file(zip, f, write_manifest(manifest/*, opts*/));
  27071. return zip;
  27072. }
  27073. function write_sheet_index(wb, sheet) {
  27074. if(!sheet) return 0;
  27075. var idx = wb.SheetNames.indexOf(sheet);
  27076. if(idx == -1) throw new Error("Sheet not found: " + sheet);
  27077. return idx;
  27078. }
  27079. function write_obj_str(factory) {
  27080. return function write_str(wb, o) {
  27081. var idx = write_sheet_index(wb, o.sheet);
  27082. return factory.from_sheet(wb.Sheets[wb.SheetNames[idx]], o, wb);
  27083. };
  27084. }
  27085. var write_htm_str = write_obj_str(HTML_);
  27086. var write_csv_str = write_obj_str({from_sheet:sheet_to_csv});
  27087. var write_slk_str = write_obj_str(typeof SYLK !== "undefined" ? SYLK : {});
  27088. var write_dif_str = write_obj_str(typeof DIF !== "undefined" ? DIF : {});
  27089. var write_prn_str = write_obj_str(typeof PRN !== "undefined" ? PRN : {});
  27090. var write_rtf_str = write_obj_str(typeof RTF !== "undefined" ? RTF : {});
  27091. var write_txt_str = write_obj_str({from_sheet:sheet_to_txt});
  27092. var write_dbf_buf = write_obj_str(typeof DBF !== "undefined" ? DBF : {});
  27093. var write_eth_str = write_obj_str(typeof ETH !== "undefined" ? ETH : {});
  27094. function fix_opts_func(defaults) {
  27095. return function fix_opts(opts) {
  27096. for(var i = 0; i != defaults.length; ++i) {
  27097. var d = defaults[i];
  27098. if(opts[d[0]] === undefined) opts[d[0]] = d[1];
  27099. if(d[2] === 'n') opts[d[0]] = Number(opts[d[0]]);
  27100. }
  27101. };
  27102. }
  27103. var fix_read_opts = function(opts) {
  27104. fix_opts_func([
  27105. ['cellNF', false], /* emit cell number format string as .z */
  27106. ['cellHTML', true], /* emit html string as .h */
  27107. ['cellFormula', true], /* emit formulae as .f */
  27108. ['cellStyles', false], /* emits style/theme as .s */
  27109. ['cellText', true], /* emit formatted text as .w */
  27110. ['cellDates', false], /* emit date cells with type `d` */
  27111. ['sheetStubs', false], /* emit empty cells */
  27112. ['sheetRows', 0, 'n'], /* read n rows (0 = read all rows) */
  27113. ['bookDeps', false], /* parse calculation chains */
  27114. ['bookSheets', false], /* only try to get sheet names (no Sheets) */
  27115. ['bookProps', false], /* only try to get properties (no Sheets) */
  27116. ['bookFiles', false], /* include raw file structure (keys, files, cfb) */
  27117. ['bookVBA', false], /* include vba raw data (vbaraw) */
  27118. ['password',''], /* password */
  27119. ['WTF', false] /* WTF mode (throws errors) */
  27120. ])(opts);
  27121. };
  27122. var fix_write_opts = fix_opts_func([
  27123. ['cellDates', false], /* write date cells with type `d` */
  27124. ['bookSST', false], /* Generate Shared String Table */
  27125. ['bookType', 'xlsx'], /* Type of workbook (xlsx/m/b) */
  27126. ['compression', false], /* Use file compression */
  27127. ['WTF', false] /* WTF mode (throws errors) */
  27128. ]);
  27129. function get_sheet_type(n) {
  27130. if(RELS.WS.indexOf(n) > -1) return "sheet";
  27131. if(RELS.CS && n == RELS.CS) return "chart";
  27132. if(RELS.DS && n == RELS.DS) return "dialog";
  27133. if(RELS.MS && n == RELS.MS) return "macro";
  27134. return (n && n.length) ? n : "sheet";
  27135. }
  27136. function safe_parse_wbrels(wbrels, sheets) {
  27137. if(!wbrels) return 0;
  27138. try {
  27139. wbrels = sheets.map(function pwbr(w) { if(!w.id) w.id = w.strRelID; return [w.name, wbrels['!id'][w.id].Target, get_sheet_type(wbrels['!id'][w.id].Type)]; });
  27140. } catch(e) { return null; }
  27141. return !wbrels || wbrels.length === 0 ? null : wbrels;
  27142. }
  27143. function safe_parse_sheet(zip, path, relsPath, sheet, idx, sheetRels, sheets, stype, opts, wb, themes, styles) {
  27144. try {
  27145. sheetRels[sheet]=parse_rels(getzipstr(zip, relsPath, true), path);
  27146. var data = getzipdata(zip, path);
  27147. var _ws;
  27148. switch(stype) {
  27149. case 'sheet': _ws = parse_ws(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  27150. case 'chart': _ws = parse_cs(data, path, idx, opts, sheetRels[sheet], wb, themes, styles);
  27151. if(!_ws || !_ws['!drawel']) break;
  27152. var dfile = resolve_path(_ws['!drawel'].Target, path);
  27153. var drelsp = get_rels_path(dfile);
  27154. var draw = parse_drawing(getzipstr(zip, dfile, true), parse_rels(getzipstr(zip, drelsp, true), dfile));
  27155. var chartp = resolve_path(draw, dfile);
  27156. var crelsp = get_rels_path(chartp);
  27157. _ws = parse_chart(getzipstr(zip, chartp, true), chartp, opts, parse_rels(getzipstr(zip, crelsp, true), chartp), wb, _ws);
  27158. break;
  27159. case 'macro': _ws = parse_ms(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  27160. case 'dialog': _ws = parse_ds(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  27161. default: throw new Error("Unrecognized sheet type " + stype);
  27162. }
  27163. sheets[sheet] = _ws;
  27164. /* scan rels for comments */
  27165. var comments = [];
  27166. if(sheetRels && sheetRels[sheet]) keys(sheetRels[sheet]).forEach(function(n) {
  27167. if(sheetRels[sheet][n].Type == RELS.CMNT) {
  27168. var dfile = resolve_path(sheetRels[sheet][n].Target, path);
  27169. comments = parse_cmnt(getzipdata(zip, dfile, true), dfile, opts);
  27170. if(!comments || !comments.length) return;
  27171. sheet_insert_comments(_ws, comments);
  27172. }
  27173. });
  27174. } catch(e) { if(opts.WTF) throw e; }
  27175. }
  27176. function strip_front_slash(x) { return x.charAt(0) == '/' ? x.slice(1) : x; }
  27177. function parse_zip(zip, opts) {
  27178. make_ssf(SSF);
  27179. opts = opts || {};
  27180. fix_read_opts(opts);
  27181. /* OpenDocument Part 3 Section 2.2.1 OpenDocument Package */
  27182. if(safegetzipfile(zip, 'META-INF/manifest.xml')) return parse_ods(zip, opts);
  27183. /* UOC */
  27184. if(safegetzipfile(zip, 'objectdata.xml')) return parse_ods(zip, opts);
  27185. /* Numbers */
  27186. if(safegetzipfile(zip, 'Index/Document.iwa')) throw new Error('Unsupported NUMBERS file');
  27187. var entries = zipentries(zip);
  27188. var dir = parse_ct((getzipstr(zip, '[Content_Types].xml')));
  27189. var xlsb = false;
  27190. var sheets, binname;
  27191. if(dir.workbooks.length === 0) {
  27192. binname = "xl/workbook.xml";
  27193. if(getzipdata(zip,binname, true)) dir.workbooks.push(binname);
  27194. }
  27195. if(dir.workbooks.length === 0) {
  27196. binname = "xl/workbook.bin";
  27197. if(!getzipdata(zip,binname,true)) throw new Error("Could not find workbook");
  27198. dir.workbooks.push(binname);
  27199. xlsb = true;
  27200. }
  27201. if(dir.workbooks[0].slice(-3) == "bin") xlsb = true;
  27202. var themes = ({});
  27203. var styles = ({});
  27204. if(!opts.bookSheets && !opts.bookProps) {
  27205. strs = [];
  27206. if(dir.sst) try { strs=parse_sst(getzipdata(zip, strip_front_slash(dir.sst)), dir.sst, opts); } catch(e) { if(opts.WTF) throw e; }
  27207. if(opts.cellStyles && dir.themes.length) themes = parse_theme(getzipstr(zip, dir.themes[0].replace(/^\//,''), true)||"",dir.themes[0], opts);
  27208. if(dir.style) styles = parse_sty(getzipdata(zip, strip_front_slash(dir.style)), dir.style, themes, opts);
  27209. }
  27210. /*var externbooks = */dir.links.map(function(link) {
  27211. try {
  27212. var rels = parse_rels(getzipstr(zip, get_rels_path(strip_front_slash(link))), link);
  27213. return parse_xlink(getzipdata(zip, strip_front_slash(link)), rels, link, opts);
  27214. } catch(e) {}
  27215. });
  27216. var wb = parse_wb(getzipdata(zip, strip_front_slash(dir.workbooks[0])), dir.workbooks[0], opts);
  27217. var props = {}, propdata = "";
  27218. if(dir.coreprops.length) {
  27219. propdata = getzipdata(zip, strip_front_slash(dir.coreprops[0]), true);
  27220. if(propdata) props = parse_core_props(propdata);
  27221. if(dir.extprops.length !== 0) {
  27222. propdata = getzipdata(zip, strip_front_slash(dir.extprops[0]), true);
  27223. if(propdata) parse_ext_props(propdata, props, opts);
  27224. }
  27225. }
  27226. var custprops = {};
  27227. if(!opts.bookSheets || opts.bookProps) {
  27228. if (dir.custprops.length !== 0) {
  27229. propdata = getzipstr(zip, strip_front_slash(dir.custprops[0]), true);
  27230. if(propdata) custprops = parse_cust_props(propdata, opts);
  27231. }
  27232. }
  27233. var out = ({});
  27234. if(opts.bookSheets || opts.bookProps) {
  27235. if(wb.Sheets) sheets = wb.Sheets.map(function pluck(x){ return x.name; });
  27236. else if(props.Worksheets && props.SheetNames.length > 0) sheets=props.SheetNames;
  27237. if(opts.bookProps) { out.Props = props; out.Custprops = custprops; }
  27238. if(opts.bookSheets && typeof sheets !== 'undefined') out.SheetNames = sheets;
  27239. if(opts.bookSheets ? out.SheetNames : opts.bookProps) return out;
  27240. }
  27241. sheets = {};
  27242. var deps = {};
  27243. if(opts.bookDeps && dir.calcchain) deps=parse_cc(getzipdata(zip, strip_front_slash(dir.calcchain)),dir.calcchain,opts);
  27244. var i=0;
  27245. var sheetRels = ({});
  27246. var path, relsPath;
  27247. {
  27248. var wbsheets = wb.Sheets;
  27249. props.Worksheets = wbsheets.length;
  27250. props.SheetNames = [];
  27251. for(var j = 0; j != wbsheets.length; ++j) {
  27252. props.SheetNames[j] = wbsheets[j].name;
  27253. }
  27254. }
  27255. var wbext = xlsb ? "bin" : "xml";
  27256. var wbrelsi = dir.workbooks[0].lastIndexOf("/");
  27257. var wbrelsfile = (dir.workbooks[0].slice(0, wbrelsi+1) + "_rels/" + dir.workbooks[0].slice(wbrelsi+1) + ".rels").replace(/^\//,"");
  27258. if(!safegetzipfile(zip, wbrelsfile)) wbrelsfile = 'xl/_rels/workbook.' + wbext + '.rels';
  27259. var wbrels = parse_rels(getzipstr(zip, wbrelsfile, true), wbrelsfile);
  27260. if(wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets);
  27261. /* Numbers iOS hack */
  27262. var nmode = (getzipdata(zip,"xl/worksheets/sheet.xml",true))?1:0;
  27263. wsloop: for(i = 0; i != props.Worksheets; ++i) {
  27264. var stype = "sheet";
  27265. if(wbrels && wbrels[i]) {
  27266. path = 'xl/' + (wbrels[i][1]).replace(/[\/]?xl\//, "");
  27267. if(!safegetzipfile(zip, path)) path = wbrels[i][1];
  27268. if(!safegetzipfile(zip, path)) path = wbrelsfile.replace(/_rels\/.*$/,"") + wbrels[i][1];
  27269. stype = wbrels[i][2];
  27270. } else {
  27271. path = 'xl/worksheets/sheet'+(i+1-nmode)+"." + wbext;
  27272. path = path.replace(/sheet0\./,"sheet.");
  27273. }
  27274. relsPath = path.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels");
  27275. if(opts && opts.sheets != null) switch(typeof opts.sheets) {
  27276. case "number": if(i != opts.sheets) continue wsloop; break;
  27277. case "string": if(props.SheetNames[i].toLowerCase() != opts.sheets.toLowerCase()) continue wsloop; break;
  27278. default: if(Array.isArray && Array.isArray(opts.sheets)) {
  27279. var snjseen = false;
  27280. for(var snj = 0; snj != opts.sheets.length; ++snj) {
  27281. if(typeof opts.sheets[snj] == "number" && opts.sheets[snj] == i) snjseen=1;
  27282. if(typeof opts.sheets[snj] == "string" && opts.sheets[snj].toLowerCase() == props.SheetNames[i].toLowerCase()) snjseen = 1;
  27283. }
  27284. if(!snjseen) continue wsloop;
  27285. }
  27286. }
  27287. safe_parse_sheet(zip, path, relsPath, props.SheetNames[i], i, sheetRels, sheets, stype, opts, wb, themes, styles);
  27288. }
  27289. out = ({
  27290. Directory: dir,
  27291. Workbook: wb,
  27292. Props: props,
  27293. Custprops: custprops,
  27294. Deps: deps,
  27295. Sheets: sheets,
  27296. SheetNames: props.SheetNames,
  27297. Strings: strs,
  27298. Styles: styles,
  27299. Themes: themes,
  27300. SSF: SSF.get_table()
  27301. });
  27302. if(opts && opts.bookFiles) {
  27303. out.keys = entries;
  27304. out.files = zip.files;
  27305. }
  27306. if(opts && opts.bookVBA) {
  27307. if(dir.vba.length > 0) out.vbaraw = getzipdata(zip,strip_front_slash(dir.vba[0]),true);
  27308. else if(dir.defaults && dir.defaults.bin === CT_VBA) out.vbaraw = getzipdata(zip, 'xl/vbaProject.bin',true);
  27309. }
  27310. return out;
  27311. }
  27312. /* [MS-OFFCRYPTO] 2.1.1 */
  27313. function parse_xlsxcfb(cfb, _opts) {
  27314. var opts = _opts || {};
  27315. var f = 'Workbook', data = CFB.find(cfb, f);
  27316. try {
  27317. f = '/!DataSpaces/Version';
  27318. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27319. /*var version = */parse_DataSpaceVersionInfo(data.content);
  27320. /* 2.3.4.1 */
  27321. f = '/!DataSpaces/DataSpaceMap';
  27322. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27323. var dsm = parse_DataSpaceMap(data.content);
  27324. if(dsm.length !== 1 || dsm[0].comps.length !== 1 || dsm[0].comps[0].t !== 0 || dsm[0].name !== "StrongEncryptionDataSpace" || dsm[0].comps[0].v !== "EncryptedPackage")
  27325. throw new Error("ECMA-376 Encrypted file bad " + f);
  27326. /* 2.3.4.2 */
  27327. f = '/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace';
  27328. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27329. var seds = parse_DataSpaceDefinition(data.content);
  27330. if(seds.length != 1 || seds[0] != "StrongEncryptionTransform")
  27331. throw new Error("ECMA-376 Encrypted file bad " + f);
  27332. /* 2.3.4.3 */
  27333. f = '/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary';
  27334. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27335. /*var hdr = */parse_Primary(data.content);
  27336. } catch(e) {}
  27337. f = '/EncryptionInfo';
  27338. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27339. var einfo = parse_EncryptionInfo(data.content);
  27340. /* 2.3.4.4 */
  27341. f = '/EncryptedPackage';
  27342. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27343. /*global decrypt_agile */
  27344. if(einfo[0] == 0x04 && typeof decrypt_agile !== 'undefined') return decrypt_agile(einfo[1], data.content, opts.password || "", opts);
  27345. /*global decrypt_std76 */
  27346. if(einfo[0] == 0x02 && typeof decrypt_std76 !== 'undefined') return decrypt_std76(einfo[1], data.content, opts.password || "", opts);
  27347. throw new Error("File is password-protected");
  27348. }
  27349. function write_zip(wb, opts) {
  27350. _shapeid = 1024;
  27351. if(opts.bookType == "ods") return write_ods(wb, opts);
  27352. if(wb && !wb.SSF) {
  27353. wb.SSF = SSF.get_table();
  27354. }
  27355. if(wb && wb.SSF) {
  27356. make_ssf(SSF); SSF.load_table(wb.SSF);
  27357. // $FlowIgnore
  27358. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  27359. opts.ssf = wb.SSF;
  27360. }
  27361. opts.rels = {}; opts.wbrels = {};
  27362. opts.Strings = []; opts.Strings.Count = 0; opts.Strings.Unique = 0;
  27363. if(browser_has_Map) opts.revStrings = new Map();
  27364. else { opts.revStrings = {}; opts.revStrings.foo = []; delete opts.revStrings.foo; }
  27365. var wbext = opts.bookType == "xlsb" ? "bin" : "xml";
  27366. var vbafmt = VBAFMTS.indexOf(opts.bookType) > -1;
  27367. var ct = new_ct();
  27368. fix_write_opts(opts = opts || {});
  27369. var zip = zip_new();
  27370. var f = "", rId = 0;
  27371. opts.cellXfs = [];
  27372. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  27373. if(!wb.Props) wb.Props = {};
  27374. f = "docProps/core.xml";
  27375. zip_add_file(zip, f, write_core_props(wb.Props, opts));
  27376. ct.coreprops.push(f);
  27377. add_rels(opts.rels, 2, f, RELS.CORE_PROPS);
  27378. f = "docProps/app.xml";
  27379. if(wb.Props && wb.Props.SheetNames){/* empty */}
  27380. else if(!wb.Workbook || !wb.Workbook.Sheets) wb.Props.SheetNames = wb.SheetNames;
  27381. else {
  27382. var _sn = [];
  27383. for(var _i = 0; _i < wb.SheetNames.length; ++_i)
  27384. if((wb.Workbook.Sheets[_i]||{}).Hidden != 2) _sn.push(wb.SheetNames[_i]);
  27385. wb.Props.SheetNames = _sn;
  27386. }
  27387. wb.Props.Worksheets = wb.Props.SheetNames.length;
  27388. zip_add_file(zip, f, write_ext_props(wb.Props, opts));
  27389. ct.extprops.push(f);
  27390. add_rels(opts.rels, 3, f, RELS.EXT_PROPS);
  27391. if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
  27392. f = "docProps/custom.xml";
  27393. zip_add_file(zip, f, write_cust_props(wb.Custprops, opts));
  27394. ct.custprops.push(f);
  27395. add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
  27396. }
  27397. for(rId=1;rId <= wb.SheetNames.length; ++rId) {
  27398. var wsrels = {'!id':{}};
  27399. var ws = wb.Sheets[wb.SheetNames[rId-1]];
  27400. var _type = (ws || {})["!type"] || "sheet";
  27401. switch(_type) {
  27402. case "chart":
  27403. /* falls through */
  27404. default:
  27405. f = "xl/worksheets/sheet" + rId + "." + wbext;
  27406. zip_add_file(zip, f, write_ws(rId-1, f, opts, wb, wsrels));
  27407. ct.sheets.push(f);
  27408. add_rels(opts.wbrels, -1, "worksheets/sheet" + rId + "." + wbext, RELS.WS[0]);
  27409. }
  27410. if(ws) {
  27411. var comments = ws['!comments'];
  27412. var need_vml = false;
  27413. if(comments && comments.length > 0) {
  27414. var cf = "xl/comments" + rId + "." + wbext;
  27415. zip_add_file(zip, cf, write_cmnt(comments, cf, opts));
  27416. ct.comments.push(cf);
  27417. add_rels(wsrels, -1, "../comments" + rId + "." + wbext, RELS.CMNT);
  27418. need_vml = true;
  27419. }
  27420. if(ws['!legacy']) {
  27421. if(need_vml) zip_add_file(zip, "xl/drawings/vmlDrawing" + (rId) + ".vml", write_comments_vml(rId, ws['!comments']));
  27422. }
  27423. delete ws['!comments'];
  27424. delete ws['!legacy'];
  27425. }
  27426. if(wsrels['!id'].rId1) zip_add_file(zip, get_rels_path(f), write_rels(wsrels));
  27427. }
  27428. if(opts.Strings != null && opts.Strings.length > 0) {
  27429. f = "xl/sharedStrings." + wbext;
  27430. zip_add_file(zip, f, write_sst(opts.Strings, f, opts));
  27431. ct.strs.push(f);
  27432. add_rels(opts.wbrels, -1, "sharedStrings." + wbext, RELS.SST);
  27433. }
  27434. f = "xl/workbook." + wbext;
  27435. zip_add_file(zip, f, write_wb(wb, f, opts));
  27436. ct.workbooks.push(f);
  27437. add_rels(opts.rels, 1, f, RELS.WB);
  27438. /* TODO: something more intelligent with themes */
  27439. f = "xl/theme/theme1.xml";
  27440. zip_add_file(zip, f, write_theme(wb.Themes, opts));
  27441. ct.themes.push(f);
  27442. add_rels(opts.wbrels, -1, "theme/theme1.xml", RELS.THEME);
  27443. /* TODO: something more intelligent with styles */
  27444. f = "xl/styles." + wbext;
  27445. zip_add_file(zip, f, write_sty(wb, f, opts));
  27446. ct.styles.push(f);
  27447. add_rels(opts.wbrels, -1, "styles." + wbext, RELS.STY);
  27448. if(wb.vbaraw && vbafmt) {
  27449. f = "xl/vbaProject.bin";
  27450. zip_add_file(zip, f, wb.vbaraw);
  27451. ct.vba.push(f);
  27452. add_rels(opts.wbrels, -1, "vbaProject.bin", RELS.VBA);
  27453. }
  27454. zip_add_file(zip, "[Content_Types].xml", write_ct(ct, opts));
  27455. zip_add_file(zip, '_rels/.rels', write_rels(opts.rels));
  27456. zip_add_file(zip, 'xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));
  27457. delete opts.revssf; delete opts.ssf;
  27458. return zip;
  27459. }
  27460. function firstbyte(f,o) {
  27461. var x = "";
  27462. switch((o||{}).type || "base64") {
  27463. case 'buffer': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  27464. case 'base64': x = Base64.decode(f.slice(0,12)); break;
  27465. case 'binary': x = f; break;
  27466. case 'array': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  27467. default: throw new Error("Unrecognized type " + (o && o.type || "undefined"));
  27468. }
  27469. return [x.charCodeAt(0), x.charCodeAt(1), x.charCodeAt(2), x.charCodeAt(3), x.charCodeAt(4), x.charCodeAt(5), x.charCodeAt(6), x.charCodeAt(7)];
  27470. }
  27471. function read_cfb(cfb, opts) {
  27472. if(CFB.find(cfb, "EncryptedPackage")) return parse_xlsxcfb(cfb, opts);
  27473. return parse_xlscfb(cfb, opts);
  27474. }
  27475. function read_zip(data, opts) {
  27476. var zip, d = data;
  27477. var o = opts||{};
  27478. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  27479. zip = zip_read(d, o);
  27480. return parse_zip(zip, o);
  27481. }
  27482. function read_plaintext(data, o) {
  27483. var i = 0;
  27484. main: while(i < data.length) switch(data.charCodeAt(i)) {
  27485. case 0x0A: case 0x0D: case 0x20: ++i; break;
  27486. case 0x3C: return parse_xlml(data.slice(i),o);
  27487. default: break main;
  27488. }
  27489. return PRN.to_workbook(data, o);
  27490. }
  27491. function read_plaintext_raw(data, o) {
  27492. var str = "", bytes = firstbyte(data, o);
  27493. switch(o.type) {
  27494. case 'base64': str = Base64.decode(data); break;
  27495. case 'binary': str = data; break;
  27496. case 'buffer': str = data.toString('binary'); break;
  27497. case 'array': str = cc2str(data); break;
  27498. default: throw new Error("Unrecognized type " + o.type);
  27499. }
  27500. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str);
  27501. return read_plaintext(str, o);
  27502. }
  27503. function read_utf16(data, o) {
  27504. var d = data;
  27505. if(o.type == 'base64') d = Base64.decode(d);
  27506. d = cptable.utils.decode(1200, d.slice(2), 'str');
  27507. o.type = "binary";
  27508. return read_plaintext(d, o);
  27509. }
  27510. function bstrify(data) {
  27511. return !data.match(/[^\x00-\x7F]/) ? data : utf8write(data);
  27512. }
  27513. function read_prn(data, d, o, str) {
  27514. if(str) { o.type = "string"; return PRN.to_workbook(data, o); }
  27515. return PRN.to_workbook(d, o);
  27516. }
  27517. function readSync(data, opts) {
  27518. reset_cp();
  27519. if(typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) return readSync(new Uint8Array(data), opts);
  27520. var d = data, n = [0,0,0,0], str = false;
  27521. var o = opts||{};
  27522. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  27523. _ssfopts = {};
  27524. if(o.dateNF) _ssfopts.dateNF = o.dateNF;
  27525. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  27526. if(o.type == "file") { o.type = has_buf ? "buffer" : "binary"; d = read_binary(data); }
  27527. if(o.type == "string") { str = true; o.type = "binary"; o.codepage = 65001; d = bstrify(data); }
  27528. if(o.type == 'array' && typeof Uint8Array !== 'undefined' && data instanceof Uint8Array && typeof ArrayBuffer !== 'undefined') {
  27529. // $FlowIgnore
  27530. var ab=new ArrayBuffer(3), vu=new Uint8Array(ab); vu.foo="bar";
  27531. // $FlowIgnore
  27532. if(!vu.foo) {o=dup(o); o.type='array'; return readSync(ab2a(d), o);}
  27533. }
  27534. switch((n = firstbyte(d, o))[0]) {
  27535. case 0xD0: if(n[1] === 0xCF && n[2] === 0x11 && n[3] === 0xE0 && n[4] === 0xA1 && n[5] === 0xB1 && n[6] === 0x1A && n[7] === 0xE1) return read_cfb(CFB.read(d, o), o); break;
  27536. case 0x09: if(n[1] <= 0x04) return parse_xlscfb(d, o); break;
  27537. case 0x3C: return parse_xlml(d, o);
  27538. case 0x49: if(n[1] === 0x44) return read_wb_ID(d, o); break;
  27539. case 0x54: if(n[1] === 0x41 && n[2] === 0x42 && n[3] === 0x4C) return DIF.to_workbook(d, o); break;
  27540. case 0x50: return (n[1] === 0x4B && n[2] < 0x09 && n[3] < 0x09) ? read_zip(d, o) : read_prn(data, d, o, str);
  27541. case 0xEF: return n[3] === 0x3C ? parse_xlml(d, o) : read_prn(data, d, o, str);
  27542. case 0xFF: if(n[1] === 0xFE) { return read_utf16(d, o); } break;
  27543. case 0x00: if(n[1] === 0x00 && n[2] >= 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o); break;
  27544. case 0x03: case 0x83: case 0x8B: case 0x8C: return DBF.to_workbook(d, o);
  27545. case 0x7B: if(n[1] === 0x5C && n[2] === 0x72 && n[3] === 0x74) return RTF.to_workbook(d, o); break;
  27546. case 0x0A: case 0x0D: case 0x20: return read_plaintext_raw(d, o);
  27547. }
  27548. if(DBF.versions.indexOf(n[0]) > -1 && n[2] <= 12 && n[3] <= 31) return DBF.to_workbook(d, o);
  27549. return read_prn(data, d, o, str);
  27550. }
  27551. function readFileSync(filename, opts) {
  27552. var o = opts||{}; o.type = 'file';
  27553. return readSync(filename, o);
  27554. }
  27555. function write_cfb_ctr(cfb, o) {
  27556. switch(o.type) {
  27557. case "base64": case "binary": break;
  27558. case "buffer": case "array": o.type = ""; break;
  27559. case "file": return write_dl(o.file, CFB.write(cfb, {type:has_buf ? 'buffer' : ""}));
  27560. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  27561. default: throw new Error("Unrecognized type " + o.type);
  27562. }
  27563. return CFB.write(cfb, o);
  27564. }
  27565. function write_zip_type(wb, opts) {
  27566. var o = opts||{};
  27567. var z = write_zip(wb, o);
  27568. var oopts = {};
  27569. if(o.compression) oopts.compression = 'DEFLATE';
  27570. if(o.password) oopts.type = has_buf ? "nodebuffer" : "string";
  27571. else switch(o.type) {
  27572. case "base64": oopts.type = "base64"; break;
  27573. case "binary": oopts.type = "string"; break;
  27574. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  27575. case "buffer":
  27576. case "file": oopts.type = has_buf ? "nodebuffer" : "string"; break;
  27577. default: throw new Error("Unrecognized type " + o.type);
  27578. }
  27579. var out = z.FullPaths ? CFB.write(z, {fileType:"zip", type: {"nodebuffer": "buffer", "string": "binary"}[oopts.type] || oopts.type}) : z.generate(oopts);
  27580. /*jshint -W083 */
  27581. if(o.password && typeof encrypt_agile !== 'undefined') return write_cfb_ctr(encrypt_agile(out, o.password), o); // eslint-disable-line no-undef
  27582. /*jshint +W083 */
  27583. if(o.type === "file") return write_dl(o.file, out);
  27584. return o.type == "string" ? utf8read(out) : out;
  27585. }
  27586. function write_cfb_type(wb, opts) {
  27587. var o = opts||{};
  27588. var cfb = write_xlscfb(wb, o);
  27589. return write_cfb_ctr(cfb, o);
  27590. }
  27591. function write_string_type(out, opts, bom) {
  27592. if(!bom) bom = "";
  27593. var o = bom + out;
  27594. switch(opts.type) {
  27595. case "base64": return Base64.encode(utf8write(o));
  27596. case "binary": return utf8write(o);
  27597. case "string": return out;
  27598. case "file": return write_dl(opts.file, o, 'utf8');
  27599. case "buffer": {
  27600. if(has_buf) return Buffer_from(o, 'utf8');
  27601. else return write_string_type(o, {type:'binary'}).split("").map(function(c) { return c.charCodeAt(0); });
  27602. }
  27603. }
  27604. throw new Error("Unrecognized type " + opts.type);
  27605. }
  27606. function write_stxt_type(out, opts) {
  27607. switch(opts.type) {
  27608. case "base64": return Base64.encode(out);
  27609. case "binary": return out;
  27610. case "string": return out; /* override in sheet_to_txt */
  27611. case "file": return write_dl(opts.file, out, 'binary');
  27612. case "buffer": {
  27613. if(has_buf) return Buffer_from(out, 'binary');
  27614. else return out.split("").map(function(c) { return c.charCodeAt(0); });
  27615. }
  27616. }
  27617. throw new Error("Unrecognized type " + opts.type);
  27618. }
  27619. /* TODO: test consistency */
  27620. function write_binary_type(out, opts) {
  27621. switch(opts.type) {
  27622. case "string":
  27623. case "base64":
  27624. case "binary":
  27625. var bstr = "";
  27626. // $FlowIgnore
  27627. for(var i = 0; i < out.length; ++i) bstr += String.fromCharCode(out[i]);
  27628. return opts.type == 'base64' ? Base64.encode(bstr) : opts.type == 'string' ? utf8read(bstr) : bstr;
  27629. case "file": return write_dl(opts.file, out);
  27630. case "buffer": return out;
  27631. default: throw new Error("Unrecognized type " + opts.type);
  27632. }
  27633. }
  27634. function writeSync(wb, opts) {
  27635. reset_cp();
  27636. check_wb(wb);
  27637. var o = opts||{};
  27638. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  27639. if(o.type == "array") { o.type = "binary"; var out = (writeSync(wb, o)); o.type = "array"; return s2ab(out); }
  27640. switch(o.bookType || 'xlsb') {
  27641. case 'xml':
  27642. case 'xlml': return write_string_type(write_xlml(wb, o), o);
  27643. case 'slk':
  27644. case 'sylk': return write_string_type(write_slk_str(wb, o), o);
  27645. case 'htm':
  27646. case 'html': return write_string_type(write_htm_str(wb, o), o);
  27647. case 'txt': return write_stxt_type(write_txt_str(wb, o), o);
  27648. case 'csv': return write_string_type(write_csv_str(wb, o), o, "\ufeff");
  27649. case 'dif': return write_string_type(write_dif_str(wb, o), o);
  27650. case 'dbf': return write_binary_type(write_dbf_buf(wb, o), o);
  27651. case 'prn': return write_string_type(write_prn_str(wb, o), o);
  27652. case 'rtf': return write_string_type(write_rtf_str(wb, o), o);
  27653. case 'eth': return write_string_type(write_eth_str(wb, o), o);
  27654. case 'fods': return write_string_type(write_ods(wb, o), o);
  27655. case 'biff2': if(!o.biff) o.biff = 2; /* falls through */
  27656. case 'biff3': if(!o.biff) o.biff = 3; /* falls through */
  27657. case 'biff4': if(!o.biff) o.biff = 4; return write_binary_type(write_biff_buf(wb, o), o);
  27658. case 'biff5': if(!o.biff) o.biff = 5; /* falls through */
  27659. case 'biff8':
  27660. case 'xla':
  27661. case 'xls': if(!o.biff) o.biff = 8; return write_cfb_type(wb, o);
  27662. case 'xlsx':
  27663. case 'xlsm':
  27664. case 'xlam':
  27665. case 'xlsb':
  27666. case 'ods': return write_zip_type(wb, o);
  27667. default: throw new Error ("Unrecognized bookType |" + o.bookType + "|");
  27668. }
  27669. }
  27670. function resolve_book_type(o) {
  27671. if(o.bookType) return;
  27672. var _BT = {
  27673. "xls": "biff8",
  27674. "htm": "html",
  27675. "slk": "sylk",
  27676. "socialcalc": "eth",
  27677. "Sh33tJS": "WTF"
  27678. };
  27679. var ext = o.file.slice(o.file.lastIndexOf(".")).toLowerCase();
  27680. if(ext.match(/^\.[a-z]+$/)) o.bookType = ext.slice(1);
  27681. o.bookType = _BT[o.bookType] || o.bookType;
  27682. }
  27683. function writeFileSync(wb, filename, opts) {
  27684. var o = opts||{}; o.type = 'file';
  27685. o.file = filename;
  27686. resolve_book_type(o);
  27687. return writeSync(wb, o);
  27688. }
  27689. function writeFileAsync(filename, wb, opts, cb) {
  27690. var o = opts||{}; o.type = 'file';
  27691. o.file = filename;
  27692. resolve_book_type(o);
  27693. o.type = 'buffer';
  27694. var _cb = cb; if(!(_cb instanceof Function)) _cb = (opts);
  27695. return _fs.writeFile(filename, writeSync(wb, o), _cb);
  27696. }
  27697. function make_json_row(sheet, r, R, cols, header, hdr, dense, o) {
  27698. var rr = encode_row(R);
  27699. var defval = o.defval, raw = o.raw || !Object.prototype.hasOwnProperty.call(o, "raw");
  27700. var isempty = true;
  27701. var row = (header === 1) ? [] : {};
  27702. if(header !== 1) {
  27703. if(Object.defineProperty) try { Object.defineProperty(row, '__rowNum__', {value:R, enumerable:false}); } catch(e) { row.__rowNum__ = R; }
  27704. else row.__rowNum__ = R;
  27705. }
  27706. if(!dense || sheet[R]) for (var C = r.s.c; C <= r.e.c; ++C) {
  27707. var val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  27708. if(val === undefined || val.t === undefined) {
  27709. if(defval === undefined) continue;
  27710. if(hdr[C] != null) { row[hdr[C]] = defval; }
  27711. continue;
  27712. }
  27713. var v = val.v;
  27714. switch(val.t){
  27715. case 'z': if(v == null) break; continue;
  27716. case 'e': v = void 0; break;
  27717. case 's': case 'd': case 'b': case 'n': break;
  27718. default: throw new Error('unrecognized type ' + val.t);
  27719. }
  27720. if(hdr[C] != null) {
  27721. if(v == null) {
  27722. if(defval !== undefined) row[hdr[C]] = defval;
  27723. else if(raw && v === null) row[hdr[C]] = null;
  27724. else continue;
  27725. } else {
  27726. row[hdr[C]] = raw || (o.rawNumbers && val.t == "n") ? v : format_cell(val,v,o);
  27727. }
  27728. if(v != null) isempty = false;
  27729. }
  27730. }
  27731. return { row: row, isempty: isempty };
  27732. }
  27733. function sheet_to_json(sheet, opts) {
  27734. if(sheet == null || sheet["!ref"] == null) return [];
  27735. var val = {t:'n',v:0}, header = 0, offset = 1, hdr = [], v=0, vv="";
  27736. var r = {s:{r:0,c:0},e:{r:0,c:0}};
  27737. var o = opts || {};
  27738. var range = o.range != null ? o.range : sheet["!ref"];
  27739. if(o.header === 1) header = 1;
  27740. else if(o.header === "A") header = 2;
  27741. else if(Array.isArray(o.header)) header = 3;
  27742. else if(o.header == null) header = 0;
  27743. switch(typeof range) {
  27744. case 'string': r = safe_decode_range(range); break;
  27745. case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
  27746. default: r = range;
  27747. }
  27748. if(header > 0) offset = 0;
  27749. var rr = encode_row(r.s.r);
  27750. var cols = [];
  27751. var out = [];
  27752. var outi = 0, counter = 0;
  27753. var dense = Array.isArray(sheet);
  27754. var R = r.s.r, C = 0, CC = 0;
  27755. if(dense && !sheet[R]) sheet[R] = [];
  27756. for(C = r.s.c; C <= r.e.c; ++C) {
  27757. cols[C] = encode_col(C);
  27758. val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  27759. switch(header) {
  27760. case 1: hdr[C] = C - r.s.c; break;
  27761. case 2: hdr[C] = cols[C]; break;
  27762. case 3: hdr[C] = o.header[C - r.s.c]; break;
  27763. default:
  27764. if(val == null) val = {w: "__EMPTY", t: "s"};
  27765. vv = v = format_cell(val, null, o);
  27766. counter = 0;
  27767. for(CC = 0; CC < hdr.length; ++CC) if(hdr[CC] == vv) vv = v + "_" + (++counter);
  27768. hdr[C] = vv;
  27769. }
  27770. }
  27771. for (R = r.s.r + offset; R <= r.e.r; ++R) {
  27772. var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
  27773. if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) out[outi++] = row.row;
  27774. }
  27775. out.length = outi;
  27776. return out;
  27777. }
  27778. var qreg = /"/g;
  27779. function make_csv_row(sheet, r, R, cols, fs, rs, FS, o) {
  27780. var isempty = true;
  27781. var row = [], txt = "", rr = encode_row(R);
  27782. for(var C = r.s.c; C <= r.e.c; ++C) {
  27783. if (!cols[C]) continue;
  27784. var val = o.dense ? (sheet[R]||[])[C]: sheet[cols[C] + rr];
  27785. if(val == null) txt = "";
  27786. else if(val.v != null) {
  27787. isempty = false;
  27788. txt = ''+(o.rawNumbers && val.t == "n" ? val.v : format_cell(val, null, o));
  27789. for(var i = 0, cc = 0; i !== txt.length; ++i) if((cc = txt.charCodeAt(i)) === fs || cc === rs || cc === 34 || o.forceQuotes) {txt = "\"" + txt.replace(qreg, '""') + "\""; break; }
  27790. if(txt == "ID") txt = '"ID"';
  27791. } else if(val.f != null && !val.F) {
  27792. isempty = false;
  27793. txt = '=' + val.f; if(txt.indexOf(",") >= 0) txt = '"' + txt.replace(qreg, '""') + '"';
  27794. } else txt = "";
  27795. /* NOTE: Excel CSV does not support array formulae */
  27796. row.push(txt);
  27797. }
  27798. if(o.blankrows === false && isempty) return null;
  27799. return row.join(FS);
  27800. }
  27801. function sheet_to_csv(sheet, opts) {
  27802. var out = [];
  27803. var o = opts == null ? {} : opts;
  27804. if(sheet == null || sheet["!ref"] == null) return "";
  27805. var r = safe_decode_range(sheet["!ref"]);
  27806. var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
  27807. var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
  27808. var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
  27809. var row = "", cols = [];
  27810. o.dense = Array.isArray(sheet);
  27811. var colinfo = o.skipHidden && sheet["!cols"] || [];
  27812. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  27813. for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
  27814. for(var R = r.s.r; R <= r.e.r; ++R) {
  27815. if ((rowinfo[R]||{}).hidden) continue;
  27816. row = make_csv_row(sheet, r, R, cols, fs, rs, FS, o);
  27817. if(row == null) { continue; }
  27818. if(o.strip) row = row.replace(endregex,"");
  27819. out.push(row + RS);
  27820. }
  27821. delete o.dense;
  27822. return out.join("");
  27823. }
  27824. function sheet_to_txt(sheet, opts) {
  27825. if(!opts) opts = {}; opts.FS = "\t"; opts.RS = "\n";
  27826. var s = sheet_to_csv(sheet, opts);
  27827. if(typeof cptable == 'undefined' || opts.type == 'string') return s;
  27828. var o = cptable.utils.encode(1200, s, 'str');
  27829. return String.fromCharCode(255) + String.fromCharCode(254) + o;
  27830. }
  27831. function sheet_to_formulae(sheet) {
  27832. var y = "", x, val="";
  27833. if(sheet == null || sheet["!ref"] == null) return [];
  27834. var r = safe_decode_range(sheet['!ref']), rr = "", cols = [], C;
  27835. var cmds = [];
  27836. var dense = Array.isArray(sheet);
  27837. for(C = r.s.c; C <= r.e.c; ++C) cols[C] = encode_col(C);
  27838. for(var R = r.s.r; R <= r.e.r; ++R) {
  27839. rr = encode_row(R);
  27840. for(C = r.s.c; C <= r.e.c; ++C) {
  27841. y = cols[C] + rr;
  27842. x = dense ? (sheet[R]||[])[C] : sheet[y];
  27843. val = "";
  27844. if(x === undefined) continue;
  27845. else if(x.F != null) {
  27846. y = x.F;
  27847. if(!x.f) continue;
  27848. val = x.f;
  27849. if(y.indexOf(":") == -1) y = y + ":" + y;
  27850. }
  27851. if(x.f != null) val = x.f;
  27852. else if(x.t == 'z') continue;
  27853. else if(x.t == 'n' && x.v != null) val = "" + x.v;
  27854. else if(x.t == 'b') val = x.v ? "TRUE" : "FALSE";
  27855. else if(x.w !== undefined) val = "'" + x.w;
  27856. else if(x.v === undefined) continue;
  27857. else if(x.t == 's') val = "'" + x.v;
  27858. else val = ""+x.v;
  27859. cmds[cmds.length] = y + "=" + val;
  27860. }
  27861. }
  27862. return cmds;
  27863. }
  27864. function sheet_add_json(_ws, js, opts) {
  27865. var o = opts || {};
  27866. var offset = +!o.skipHeader;
  27867. var ws = _ws || ({});
  27868. var _R = 0, _C = 0;
  27869. if(ws && o.origin != null) {
  27870. if(typeof o.origin == 'number') _R = o.origin;
  27871. else {
  27872. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  27873. _R = _origin.r; _C = _origin.c;
  27874. }
  27875. }
  27876. var cell;
  27877. var range = ({s: {c:0, r:0}, e: {c:_C, r:_R + js.length - 1 + offset}});
  27878. if(ws['!ref']) {
  27879. var _range = safe_decode_range(ws['!ref']);
  27880. range.e.c = Math.max(range.e.c, _range.e.c);
  27881. range.e.r = Math.max(range.e.r, _range.e.r);
  27882. if(_R == -1) { _R = _range.e.r + 1; range.e.r = _R + js.length - 1 + offset; }
  27883. } else {
  27884. if(_R == -1) { _R = 0; range.e.r = js.length - 1 + offset; }
  27885. }
  27886. var hdr = o.header || [], C = 0;
  27887. js.forEach(function (JS, R) {
  27888. keys(JS).forEach(function(k) {
  27889. if((C=hdr.indexOf(k)) == -1) hdr[C=hdr.length] = k;
  27890. var v = JS[k];
  27891. var t = 'z';
  27892. var z = "";
  27893. var ref = encode_cell({c:_C + C,r:_R + R + offset});
  27894. cell = utils.sheet_get_cell(ws, ref);
  27895. if(v && typeof v === 'object' && !(v instanceof Date)){
  27896. ws[ref] = v;
  27897. } else {
  27898. if(typeof v == 'number') t = 'n';
  27899. else if(typeof v == 'boolean') t = 'b';
  27900. else if(typeof v == 'string') t = 's';
  27901. else if(v instanceof Date) {
  27902. t = 'd';
  27903. if(!o.cellDates) { t = 'n'; v = datenum(v); }
  27904. z = (o.dateNF || SSF._table[14]);
  27905. }
  27906. if(!cell) ws[ref] = cell = ({t:t, v:v});
  27907. else {
  27908. cell.t = t; cell.v = v;
  27909. delete cell.w; delete cell.R;
  27910. if(z) cell.z = z;
  27911. }
  27912. if(z) cell.z = z;
  27913. }
  27914. });
  27915. });
  27916. range.e.c = Math.max(range.e.c, _C + hdr.length - 1);
  27917. var __R = encode_row(_R);
  27918. if(offset) for(C = 0; C < hdr.length; ++C) ws[encode_col(C + _C) + __R] = {t:'s', v:hdr[C]};
  27919. ws['!ref'] = encode_range(range);
  27920. return ws;
  27921. }
  27922. function json_to_sheet(js, opts) { return sheet_add_json(null, js, opts); }
  27923. var utils = {
  27924. encode_col: encode_col,
  27925. encode_row: encode_row,
  27926. encode_cell: encode_cell,
  27927. encode_range: encode_range,
  27928. decode_col: decode_col,
  27929. decode_row: decode_row,
  27930. split_cell: split_cell,
  27931. decode_cell: decode_cell,
  27932. decode_range: decode_range,
  27933. format_cell: format_cell,
  27934. get_formulae: sheet_to_formulae,
  27935. make_csv: sheet_to_csv,
  27936. make_json: sheet_to_json,
  27937. make_formulae: sheet_to_formulae,
  27938. sheet_add_aoa: sheet_add_aoa,
  27939. sheet_add_json: sheet_add_json,
  27940. sheet_add_dom: sheet_add_dom,
  27941. aoa_to_sheet: aoa_to_sheet,
  27942. json_to_sheet: json_to_sheet,
  27943. table_to_sheet: parse_dom_table,
  27944. table_to_book: table_to_book,
  27945. sheet_to_csv: sheet_to_csv,
  27946. sheet_to_txt: sheet_to_txt,
  27947. sheet_to_json: sheet_to_json,
  27948. sheet_to_html: HTML_.from_sheet,
  27949. sheet_to_formulae: sheet_to_formulae,
  27950. sheet_to_row_object_array: sheet_to_json
  27951. };
  27952. (function(utils) {
  27953. utils.consts = utils.consts || {};
  27954. function add_consts(R/*Array<any>*/) { R.forEach(function(a){ utils.consts[a[0]] = a[1]; }); }
  27955. function get_default(x, y, z) { return x[y] != null ? x[y] : (x[y] = z); }
  27956. /* get cell, creating a stub if necessary */
  27957. function ws_get_cell_stub(ws, R, C) {
  27958. /* A1 cell address */
  27959. if(typeof R == "string") {
  27960. /* dense */
  27961. if(Array.isArray(ws)) {
  27962. var RC = decode_cell(R);
  27963. if(!ws[RC.r]) ws[RC.r] = [];
  27964. return ws[RC.r][RC.c] || (ws[RC.r][RC.c] = {t:'z'});
  27965. }
  27966. return ws[R] || (ws[R] = {t:'z'});
  27967. }
  27968. /* cell address object */
  27969. if(typeof R != "number") return ws_get_cell_stub(ws, encode_cell(R));
  27970. /* R and C are 0-based indices */
  27971. return ws_get_cell_stub(ws, encode_cell({r:R,c:C||0}));
  27972. }
  27973. utils.sheet_get_cell = ws_get_cell_stub;
  27974. /* find sheet index for given name / validate index */
  27975. function wb_sheet_idx(wb, sh) {
  27976. if(typeof sh == "number") {
  27977. if(sh >= 0 && wb.SheetNames.length > sh) return sh;
  27978. throw new Error("Cannot find sheet # " + sh);
  27979. } else if(typeof sh == "string") {
  27980. var idx = wb.SheetNames.indexOf(sh);
  27981. if(idx > -1) return idx;
  27982. throw new Error("Cannot find sheet name |" + sh + "|");
  27983. } else throw new Error("Cannot find sheet |" + sh + "|");
  27984. }
  27985. /* simple blank workbook object */
  27986. utils.book_new = function() {
  27987. return { SheetNames: [], Sheets: {} };
  27988. };
  27989. /* add a worksheet to the end of a given workbook */
  27990. utils.book_append_sheet = function(wb, ws, name) {
  27991. if(!name) for(var i = 1; i <= 0xFFFF; ++i, name = undefined) if(wb.SheetNames.indexOf(name = "Sheet" + i) == -1) break;
  27992. if(!name || wb.SheetNames.length >= 0xFFFF) throw new Error("Too many worksheets");
  27993. check_ws_name(name);
  27994. if(wb.SheetNames.indexOf(name) >= 0) throw new Error("Worksheet with name |" + name + "| already exists!");
  27995. wb.SheetNames.push(name);
  27996. wb.Sheets[name] = ws;
  27997. };
  27998. /* set sheet visibility (visible/hidden/very hidden) */
  27999. utils.book_set_sheet_visibility = function(wb, sh, vis) {
  28000. get_default(wb,"Workbook",{});
  28001. get_default(wb.Workbook,"Sheets",[]);
  28002. var idx = wb_sheet_idx(wb, sh);
  28003. // $FlowIgnore
  28004. get_default(wb.Workbook.Sheets,idx, {});
  28005. switch(vis) {
  28006. case 0: case 1: case 2: break;
  28007. default: throw new Error("Bad sheet visibility setting " + vis);
  28008. }
  28009. // $FlowIgnore
  28010. wb.Workbook.Sheets[idx].Hidden = vis;
  28011. };
  28012. add_consts([
  28013. ["SHEET_VISIBLE", 0],
  28014. ["SHEET_HIDDEN", 1],
  28015. ["SHEET_VERY_HIDDEN", 2]
  28016. ]);
  28017. /* set number format */
  28018. utils.cell_set_number_format = function(cell, fmt) {
  28019. cell.z = fmt;
  28020. return cell;
  28021. };
  28022. /* set cell hyperlink */
  28023. utils.cell_set_hyperlink = function(cell, target, tooltip) {
  28024. if(!target) {
  28025. delete cell.l;
  28026. } else {
  28027. cell.l = ({ Target: target });
  28028. if(tooltip) cell.l.Tooltip = tooltip;
  28029. }
  28030. return cell;
  28031. };
  28032. utils.cell_set_internal_link = function(cell, range, tooltip) { return utils.cell_set_hyperlink(cell, "#" + range, tooltip); };
  28033. /* add to cell comments */
  28034. utils.cell_add_comment = function(cell, text, author) {
  28035. if(!cell.c) cell.c = [];
  28036. cell.c.push({t:text, a:author||"SheetJS"});
  28037. };
  28038. /* set array formula and flush related cells */
  28039. utils.sheet_set_array_formula = function(ws, range, formula) {
  28040. var rng = typeof range != "string" ? range : safe_decode_range(range);
  28041. var rngstr = typeof range == "string" ? range : encode_range(range);
  28042. for(var R = rng.s.r; R <= rng.e.r; ++R) for(var C = rng.s.c; C <= rng.e.c; ++C) {
  28043. var cell = ws_get_cell_stub(ws, R, C);
  28044. cell.t = 'n';
  28045. cell.F = rngstr;
  28046. delete cell.v;
  28047. if(R == rng.s.r && C == rng.s.c) cell.f = formula;
  28048. }
  28049. return ws;
  28050. };
  28051. return utils;
  28052. })(utils);
  28053. if(has_buf && typeof require != 'undefined') (function() {
  28054. var Readable = {}.Readable;
  28055. var write_csv_stream = function(sheet, opts) {
  28056. var stream = Readable();
  28057. var o = opts == null ? {} : opts;
  28058. if(sheet == null || sheet["!ref"] == null) { stream.push(null); return stream; }
  28059. var r = safe_decode_range(sheet["!ref"]);
  28060. var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
  28061. var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
  28062. var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
  28063. var row = "", cols = [];
  28064. o.dense = Array.isArray(sheet);
  28065. var colinfo = o.skipHidden && sheet["!cols"] || [];
  28066. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  28067. for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
  28068. var R = r.s.r;
  28069. var BOM = false;
  28070. stream._read = function() {
  28071. if(!BOM) { BOM = true; return stream.push("\uFEFF"); }
  28072. while(R <= r.e.r) {
  28073. ++R;
  28074. if ((rowinfo[R-1]||{}).hidden) continue;
  28075. row = make_csv_row(sheet, r, R-1, cols, fs, rs, FS, o);
  28076. if(row != null) {
  28077. if(o.strip) row = row.replace(endregex,"");
  28078. stream.push(row + RS);
  28079. break;
  28080. }
  28081. }
  28082. if(R > r.e.r) return stream.push(null);
  28083. };
  28084. return stream;
  28085. };
  28086. var write_html_stream = function(ws, opts) {
  28087. var stream = Readable();
  28088. var o = opts || {};
  28089. var header = o.header != null ? o.header : HTML_.BEGIN;
  28090. var footer = o.footer != null ? o.footer : HTML_.END;
  28091. stream.push(header);
  28092. var r = decode_range(ws['!ref']);
  28093. o.dense = Array.isArray(ws);
  28094. stream.push(HTML_._preamble(ws, r, o));
  28095. var R = r.s.r;
  28096. var end = false;
  28097. stream._read = function() {
  28098. if(R > r.e.r) {
  28099. if(!end) { end = true; stream.push("</table>" + footer); }
  28100. return stream.push(null);
  28101. }
  28102. while(R <= r.e.r) {
  28103. stream.push(HTML_._row(ws, r, R, o));
  28104. ++R;
  28105. break;
  28106. }
  28107. };
  28108. return stream;
  28109. };
  28110. var write_json_stream = function(sheet, opts) {
  28111. var stream = Readable({objectMode:true});
  28112. if(sheet == null || sheet["!ref"] == null) { stream.push(null); return stream; }
  28113. var val = {t:'n',v:0}, header = 0, offset = 1, hdr = [], v=0, vv="";
  28114. var r = {s:{r:0,c:0},e:{r:0,c:0}};
  28115. var o = opts || {};
  28116. var range = o.range != null ? o.range : sheet["!ref"];
  28117. if(o.header === 1) header = 1;
  28118. else if(o.header === "A") header = 2;
  28119. else if(Array.isArray(o.header)) header = 3;
  28120. switch(typeof range) {
  28121. case 'string': r = safe_decode_range(range); break;
  28122. case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
  28123. default: r = range;
  28124. }
  28125. if(header > 0) offset = 0;
  28126. var rr = encode_row(r.s.r);
  28127. var cols = [];
  28128. var counter = 0;
  28129. var dense = Array.isArray(sheet);
  28130. var R = r.s.r, C = 0, CC = 0;
  28131. if(dense && !sheet[R]) sheet[R] = [];
  28132. for(C = r.s.c; C <= r.e.c; ++C) {
  28133. cols[C] = encode_col(C);
  28134. val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  28135. switch(header) {
  28136. case 1: hdr[C] = C - r.s.c; break;
  28137. case 2: hdr[C] = cols[C]; break;
  28138. case 3: hdr[C] = o.header[C - r.s.c]; break;
  28139. default:
  28140. if(val == null) val = {w: "__EMPTY", t: "s"};
  28141. vv = v = format_cell(val, null, o);
  28142. counter = 0;
  28143. for(CC = 0; CC < hdr.length; ++CC) if(hdr[CC] == vv) vv = v + "_" + (++counter);
  28144. hdr[C] = vv;
  28145. }
  28146. }
  28147. R = r.s.r + offset;
  28148. stream._read = function() {
  28149. if(R > r.e.r) return stream.push(null);
  28150. while(R <= r.e.r) {
  28151. //if ((rowinfo[R-1]||{}).hidden) continue;
  28152. var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
  28153. ++R;
  28154. if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) {
  28155. stream.push(row.row);
  28156. break;
  28157. }
  28158. }
  28159. };
  28160. return stream;
  28161. };
  28162. XLSX.stream = {
  28163. to_json: write_json_stream,
  28164. to_html: write_html_stream,
  28165. to_csv: write_csv_stream
  28166. };
  28167. })();
  28168. if(typeof parse_xlscfb !== "undefined") XLSX.parse_xlscfb = parse_xlscfb;
  28169. XLSX.parse_zip = parse_zip;
  28170. XLSX.read = readSync; //xlsread
  28171. XLSX.readFile = readFileSync; //readFile
  28172. XLSX.readFileSync = readFileSync;
  28173. XLSX.write = writeSync;
  28174. XLSX.writeFile = writeFileSync;
  28175. XLSX.writeFileSync = writeFileSync;
  28176. XLSX.writeFileAsync = writeFileAsync;
  28177. XLSX.utils = utils;
  28178. XLSX.SSF = SSF;
  28179. if(typeof CFB !== "undefined") XLSX.CFB = CFB;
  28180. }
  28181. /*global define */
  28182. if(typeof exports !== 'undefined') make_xlsx_lib(exports);
  28183. else if(typeof module !== 'undefined' && module.exports) make_xlsx_lib(module.exports);
  28184. else if(typeof define === 'function' && define.amd) define(function() { if(!XLSX.version) make_xlsx_lib(XLSX); return XLSX; });
  28185. else make_xlsx_lib(XLSX);
  28186. /*exported XLS, ODS */
  28187. var XLS = XLSX, ODS = XLSX;