xlscfb.flow.js 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  1. var DO_NOT_EXPORT_CFB = true;
  2. /*::
  3. declare var Base64:any;
  4. declare var ReadShift:any;
  5. declare var CheckField:any;
  6. declare var prep_blob:any;
  7. declare var __readUInt32LE:any;
  8. declare var __readInt32LE:any;
  9. declare var __toBuffer:any;
  10. declare var __utf16le:any;
  11. declare var bconcat:any;
  12. declare var s2a:any;
  13. declare var chr0:any;
  14. declare var chr1:any;
  15. declare var has_buf:boolean;
  16. declare var new_buf:any;
  17. declare var new_raw_buf:any;
  18. declare var new_unsafe_buf:any;
  19. declare var Buffer_from:any;
  20. */
  21. /* cfb.js (C) 2013-present SheetJS -- http://sheetjs.com */
  22. /* vim: set ts=2: */
  23. /*jshint eqnull:true */
  24. /*exported CFB */
  25. /*global module, require:false, process:false, Buffer:false, Uint8Array:false, Uint16Array:false */
  26. /*::
  27. declare var DO_NOT_EXPORT_CFB:?boolean;
  28. type SectorEntry = {
  29. name?:string;
  30. nodes?:Array<number>;
  31. data:RawBytes;
  32. };
  33. type SectorList = {
  34. [k:string|number]:SectorEntry;
  35. name:?string;
  36. fat_addrs:Array<number>;
  37. ssz:number;
  38. }
  39. type CFBFiles = {[n:string]:CFBEntry};
  40. */
  41. /* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
  42. /* vim: set ts=2: */
  43. /*exported CRC32 */
  44. var CRC32;
  45. (function (factory) {
  46. /*jshint ignore:start */
  47. /*eslint-disable */
  48. factory(CRC32 = {});
  49. /*eslint-enable */
  50. /*jshint ignore:end */
  51. }(function(CRC32) {
  52. CRC32.version = '1.2.0';
  53. /* see perf/crc32table.js */
  54. /*global Int32Array */
  55. function signed_crc_table()/*:any*/ {
  56. var c = 0, table/*:Array<number>*/ = new Array(256);
  57. for(var n =0; n != 256; ++n){
  58. c = n;
  59. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  60. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  61. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  62. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  63. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  64. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  65. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  66. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  67. table[n] = c;
  68. }
  69. return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;
  70. }
  71. var T = signed_crc_table();
  72. function crc32_bstr(bstr/*:string*/, seed/*:number*/)/*:number*/ {
  73. var C = seed ^ -1, L = bstr.length - 1;
  74. for(var i = 0; i < L;) {
  75. C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
  76. C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
  77. }
  78. if(i === L) C = (C>>>8) ^ T[(C ^ bstr.charCodeAt(i))&0xFF];
  79. return C ^ -1;
  80. }
  81. function crc32_buf(buf/*:Uint8Array|Array<number>*/, seed/*:number*/)/*:number*/ {
  82. if(buf.length > 10000) return crc32_buf_8(buf, seed);
  83. var C = seed ^ -1, L = buf.length - 3;
  84. for(var i = 0; i < L;) {
  85. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  86. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  87. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  88. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  89. }
  90. while(i < L+3) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  91. return C ^ -1;
  92. }
  93. function crc32_buf_8(buf/*:Uint8Array|Array<number>*/, seed/*:number*/)/*:number*/ {
  94. var C = seed ^ -1, L = buf.length - 7;
  95. for(var i = 0; i < L;) {
  96. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  97. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  98. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  99. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  100. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  101. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  102. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  103. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  104. }
  105. while(i < L+7) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  106. return C ^ -1;
  107. }
  108. function crc32_str(str/*:string*/, seed/*:number*/)/*:number*/ {
  109. var C = seed ^ -1;
  110. for(var i = 0, L=str.length, c, d; i < L;) {
  111. c = str.charCodeAt(i++);
  112. if(c < 0x80) {
  113. C = (C>>>8) ^ T[(C ^ c)&0xFF];
  114. } else if(c < 0x800) {
  115. C = (C>>>8) ^ T[(C ^ (192|((c>>6)&31)))&0xFF];
  116. C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
  117. } else if(c >= 0xD800 && c < 0xE000) {
  118. c = (c&1023)+64; d = str.charCodeAt(i++)&1023;
  119. C = (C>>>8) ^ T[(C ^ (240|((c>>8)&7)))&0xFF];
  120. C = (C>>>8) ^ T[(C ^ (128|((c>>2)&63)))&0xFF];
  121. C = (C>>>8) ^ T[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF];
  122. C = (C>>>8) ^ T[(C ^ (128|(d&63)))&0xFF];
  123. } else {
  124. C = (C>>>8) ^ T[(C ^ (224|((c>>12)&15)))&0xFF];
  125. C = (C>>>8) ^ T[(C ^ (128|((c>>6)&63)))&0xFF];
  126. C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
  127. }
  128. }
  129. return C ^ -1;
  130. }
  131. CRC32.table = T;
  132. CRC32.bstr = crc32_bstr;
  133. CRC32.buf = crc32_buf;
  134. CRC32.str = crc32_str;
  135. }));
  136. /* [MS-CFB] v20171201 */
  137. var CFB = (function _CFB(){
  138. var exports/*:CFBModule*/ = /*::(*/{}/*:: :any)*/;
  139. exports.version = '1.2.1';
  140. /* [MS-CFB] 2.6.4 */
  141. function namecmp(l/*:string*/, r/*:string*/)/*:number*/ {
  142. var L = l.split("/"), R = r.split("/");
  143. for(var i = 0, c = 0, Z = Math.min(L.length, R.length); i < Z; ++i) {
  144. if((c = L[i].length - R[i].length)) return c;
  145. if(L[i] != R[i]) return L[i] < R[i] ? -1 : 1;
  146. }
  147. return L.length - R.length;
  148. }
  149. function dirname(p/*:string*/)/*:string*/ {
  150. if(p.charAt(p.length - 1) == "/") return (p.slice(0,-1).indexOf("/") === -1) ? p : dirname(p.slice(0, -1));
  151. var c = p.lastIndexOf("/");
  152. return (c === -1) ? p : p.slice(0, c+1);
  153. }
  154. function filename(p/*:string*/)/*:string*/ {
  155. if(p.charAt(p.length - 1) == "/") return filename(p.slice(0, -1));
  156. var c = p.lastIndexOf("/");
  157. return (c === -1) ? p : p.slice(c+1);
  158. }
  159. /* -------------------------------------------------------------------------- */
  160. /* DOS Date format:
  161. high|YYYYYYYm.mmmddddd.HHHHHMMM.MMMSSSSS|low
  162. add 1980 to stored year
  163. stored second should be doubled
  164. */
  165. /* write JS date to buf as a DOS date */
  166. function write_dos_date(buf/*:CFBlob*/, date/*:Date|string*/) {
  167. if(typeof date === "string") date = new Date(date);
  168. var hms/*:number*/ = date.getHours();
  169. hms = hms << 6 | date.getMinutes();
  170. hms = hms << 5 | (date.getSeconds()>>>1);
  171. buf.write_shift(2, hms);
  172. var ymd/*:number*/ = (date.getFullYear() - 1980);
  173. ymd = ymd << 4 | (date.getMonth()+1);
  174. ymd = ymd << 5 | date.getDate();
  175. buf.write_shift(2, ymd);
  176. }
  177. /* read four bytes from buf and interpret as a DOS date */
  178. function parse_dos_date(buf/*:CFBlob*/)/*:Date*/ {
  179. var hms = buf.read_shift(2) & 0xFFFF;
  180. var ymd = buf.read_shift(2) & 0xFFFF;
  181. var val = new Date();
  182. var d = ymd & 0x1F; ymd >>>= 5;
  183. var m = ymd & 0x0F; ymd >>>= 4;
  184. val.setMilliseconds(0);
  185. val.setFullYear(ymd + 1980);
  186. val.setMonth(m-1);
  187. val.setDate(d);
  188. var S = hms & 0x1F; hms >>>= 5;
  189. var M = hms & 0x3F; hms >>>= 6;
  190. val.setHours(hms);
  191. val.setMinutes(M);
  192. val.setSeconds(S<<1);
  193. return val;
  194. }
  195. function parse_extra_field(blob/*:CFBlob*/)/*:any*/ {
  196. prep_blob(blob, 0);
  197. var o = /*::(*/{}/*:: :any)*/;
  198. var flags = 0;
  199. while(blob.l <= blob.length - 4) {
  200. var type = blob.read_shift(2);
  201. var sz = blob.read_shift(2), tgt = blob.l + sz;
  202. var p = {};
  203. switch(type) {
  204. /* UNIX-style Timestamps */
  205. case 0x5455: {
  206. flags = blob.read_shift(1);
  207. if(flags & 1) p.mtime = blob.read_shift(4);
  208. /* for some reason, CD flag corresponds to LFH */
  209. if(sz > 5) {
  210. if(flags & 2) p.atime = blob.read_shift(4);
  211. if(flags & 4) p.ctime = blob.read_shift(4);
  212. }
  213. if(p.mtime) p.mt = new Date(p.mtime*1000);
  214. }
  215. break;
  216. }
  217. blob.l = tgt;
  218. o[type] = p;
  219. }
  220. return o;
  221. }
  222. var fs/*:: = require('fs'); */;
  223. function get_fs() { return fs || (fs = require('fs')); }
  224. function parse(file/*:RawBytes*/, options/*:CFBReadOpts*/)/*:CFBContainer*/ {
  225. if(file[0] == 0x50 && file[1] == 0x4b) return parse_zip(file, options);
  226. if((file[0] | 0x20) == 0x6d && (file[1]|0x20) == 0x69) return parse_mad(file, options);
  227. if(file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
  228. var mver = 3;
  229. var ssz = 512;
  230. var nmfs = 0; // number of mini FAT sectors
  231. var difat_sec_cnt = 0;
  232. var dir_start = 0;
  233. var minifat_start = 0;
  234. var difat_start = 0;
  235. var fat_addrs/*:Array<number>*/ = []; // locations of FAT sectors
  236. /* [MS-CFB] 2.2 Compound File Header */
  237. var blob/*:CFBlob*/ = /*::(*/file.slice(0,512)/*:: :any)*/;
  238. prep_blob(blob, 0);
  239. /* major version */
  240. var mv = check_get_mver(blob);
  241. mver = mv[0];
  242. switch(mver) {
  243. case 3: ssz = 512; break; case 4: ssz = 4096; break;
  244. case 0: if(mv[1] == 0) return parse_zip(file, options);
  245. /* falls through */
  246. default: throw new Error("Major Version: Expected 3 or 4 saw " + mver);
  247. }
  248. /* reprocess header */
  249. if(ssz !== 512) { blob = /*::(*/file.slice(0,ssz)/*:: :any)*/; prep_blob(blob, 28 /* blob.l */); }
  250. /* Save header for final object */
  251. var header/*:RawBytes*/ = file.slice(0,ssz);
  252. check_shifts(blob, mver);
  253. // Number of Directory Sectors
  254. var dir_cnt/*:number*/ = blob.read_shift(4, 'i');
  255. if(mver === 3 && dir_cnt !== 0) throw new Error('# Directory Sectors: Expected 0 saw ' + dir_cnt);
  256. // Number of FAT Sectors
  257. blob.l += 4;
  258. // First Directory Sector Location
  259. dir_start = blob.read_shift(4, 'i');
  260. // Transaction Signature
  261. blob.l += 4;
  262. // Mini Stream Cutoff Size
  263. blob.chk('00100000', 'Mini Stream Cutoff Size: ');
  264. // First Mini FAT Sector Location
  265. minifat_start = blob.read_shift(4, 'i');
  266. // Number of Mini FAT Sectors
  267. nmfs = blob.read_shift(4, 'i');
  268. // First DIFAT sector location
  269. difat_start = blob.read_shift(4, 'i');
  270. // Number of DIFAT Sectors
  271. difat_sec_cnt = blob.read_shift(4, 'i');
  272. // Grab FAT Sector Locations
  273. for(var q = -1, j = 0; j < 109; ++j) { /* 109 = (512 - blob.l)>>>2; */
  274. q = blob.read_shift(4, 'i');
  275. if(q<0) break;
  276. fat_addrs[j] = q;
  277. }
  278. /** Break the file up into sectors */
  279. var sectors/*:Array<RawBytes>*/ = sectorify(file, ssz);
  280. sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);
  281. /** Chains */
  282. var sector_list/*:SectorList*/ = make_sector_list(sectors, dir_start, fat_addrs, ssz);
  283. sector_list[dir_start].name = "!Directory";
  284. if(nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
  285. sector_list[fat_addrs[0]].name = "!FAT";
  286. sector_list.fat_addrs = fat_addrs;
  287. sector_list.ssz = ssz;
  288. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  289. var files/*:CFBFiles*/ = {}, Paths/*:Array<string>*/ = [], FileIndex/*:CFBFileIndex*/ = [], FullPaths/*:Array<string>*/ = [];
  290. read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);
  291. build_full_paths(FileIndex, FullPaths, Paths);
  292. Paths.shift();
  293. var o = {
  294. FileIndex: FileIndex,
  295. FullPaths: FullPaths
  296. };
  297. // $FlowIgnore
  298. if(options && options.raw) o.raw = {header: header, sectors: sectors};
  299. return o;
  300. } // parse
  301. /* [MS-CFB] 2.2 Compound File Header -- read up to major version */
  302. function check_get_mver(blob/*:CFBlob*/)/*:[number, number]*/ {
  303. if(blob[blob.l] == 0x50 && blob[blob.l + 1] == 0x4b) return [0, 0];
  304. // header signature 8
  305. blob.chk(HEADER_SIGNATURE, 'Header Signature: ');
  306. // clsid 16
  307. //blob.chk(HEADER_CLSID, 'CLSID: ');
  308. blob.l += 16;
  309. // minor version 2
  310. var mver/*:number*/ = blob.read_shift(2, 'u');
  311. return [blob.read_shift(2,'u'), mver];
  312. }
  313. function check_shifts(blob/*:CFBlob*/, mver/*:number*/)/*:void*/ {
  314. var shift = 0x09;
  315. // Byte Order
  316. //blob.chk('feff', 'Byte Order: '); // note: some writers put 0xffff
  317. blob.l += 2;
  318. // Sector Shift
  319. switch((shift = blob.read_shift(2))) {
  320. case 0x09: if(mver != 3) throw new Error('Sector Shift: Expected 9 saw ' + shift); break;
  321. case 0x0c: if(mver != 4) throw new Error('Sector Shift: Expected 12 saw ' + shift); break;
  322. default: throw new Error('Sector Shift: Expected 9 or 12 saw ' + shift);
  323. }
  324. // Mini Sector Shift
  325. blob.chk('0600', 'Mini Sector Shift: ');
  326. // Reserved
  327. blob.chk('000000000000', 'Reserved: ');
  328. }
  329. /** Break the file up into sectors */
  330. function sectorify(file/*:RawBytes*/, ssz/*:number*/)/*:Array<RawBytes>*/ {
  331. var nsectors = Math.ceil(file.length/ssz)-1;
  332. var sectors/*:Array<RawBytes>*/ = [];
  333. for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz);
  334. sectors[nsectors-1] = file.slice(nsectors*ssz);
  335. return sectors;
  336. }
  337. /* [MS-CFB] 2.6.4 Red-Black Tree */
  338. function build_full_paths(FI/*:CFBFileIndex*/, FP/*:Array<string>*/, Paths/*:Array<string>*/)/*:void*/ {
  339. var i = 0, L = 0, R = 0, C = 0, j = 0, pl = Paths.length;
  340. var dad/*:Array<number>*/ = [], q/*:Array<number>*/ = [];
  341. for(; i < pl; ++i) { dad[i]=q[i]=i; FP[i]=Paths[i]; }
  342. for(; j < q.length; ++j) {
  343. i = q[j];
  344. L = FI[i].L; R = FI[i].R; C = FI[i].C;
  345. if(dad[i] === i) {
  346. if(L !== -1 /*NOSTREAM*/ && dad[L] !== L) dad[i] = dad[L];
  347. if(R !== -1 && dad[R] !== R) dad[i] = dad[R];
  348. }
  349. if(C !== -1 /*NOSTREAM*/) dad[C] = i;
  350. if(L !== -1 && i != dad[i]) { dad[L] = dad[i]; if(q.lastIndexOf(L) < j) q.push(L); }
  351. if(R !== -1 && i != dad[i]) { dad[R] = dad[i]; if(q.lastIndexOf(R) < j) q.push(R); }
  352. }
  353. for(i=1; i < pl; ++i) if(dad[i] === i) {
  354. if(R !== -1 /*NOSTREAM*/ && dad[R] !== R) dad[i] = dad[R];
  355. else if(L !== -1 && dad[L] !== L) dad[i] = dad[L];
  356. }
  357. for(i=1; i < pl; ++i) {
  358. if(FI[i].type === 0 /* unknown */) continue;
  359. j = i;
  360. if(j != dad[j]) do {
  361. j = dad[j];
  362. FP[i] = FP[j] + "/" + FP[i];
  363. } while (j !== 0 && -1 !== dad[j] && j != dad[j]);
  364. dad[i] = -1;
  365. }
  366. FP[0] += "/";
  367. for(i=1; i < pl; ++i) {
  368. if(FI[i].type !== 2 /* stream */) FP[i] += "/";
  369. }
  370. }
  371. function get_mfat_entry(entry/*:CFBEntry*/, payload/*:RawBytes*/, mini/*:?RawBytes*/)/*:CFBlob*/ {
  372. var start = entry.start, size = entry.size;
  373. //return (payload.slice(start*MSSZ, start*MSSZ + size)/*:any*/);
  374. var o = [];
  375. var idx = start;
  376. while(mini && size > 0 && idx >= 0) {
  377. o.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
  378. size -= MSSZ;
  379. idx = __readInt32LE(mini, idx * 4);
  380. }
  381. if(o.length === 0) return (new_buf(0)/*:any*/);
  382. return (bconcat(o).slice(0, entry.size)/*:any*/);
  383. }
  384. /** Chase down the rest of the DIFAT chain to build a comprehensive list
  385. DIFAT chains by storing the next sector number as the last 32 bits */
  386. function sleuth_fat(idx/*:number*/, cnt/*:number*/, sectors/*:Array<RawBytes>*/, ssz/*:number*/, fat_addrs)/*:void*/ {
  387. var q/*:number*/ = ENDOFCHAIN;
  388. if(idx === ENDOFCHAIN) {
  389. if(cnt !== 0) throw new Error("DIFAT chain shorter than expected");
  390. } else if(idx !== -1 /*FREESECT*/) {
  391. var sector = sectors[idx], m = (ssz>>>2)-1;
  392. if(!sector) return;
  393. for(var i = 0; i < m; ++i) {
  394. if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break;
  395. fat_addrs.push(q);
  396. }
  397. sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs);
  398. }
  399. }
  400. /** Follow the linked list of sectors for a given starting point */
  401. function get_sector_list(sectors/*:Array<RawBytes>*/, start/*:number*/, fat_addrs/*:Array<number>*/, ssz/*:number*/, chkd/*:?Array<boolean>*/)/*:SectorEntry*/ {
  402. var buf/*:Array<number>*/ = [], buf_chain/*:Array<any>*/ = [];
  403. if(!chkd) chkd = [];
  404. var modulus = ssz - 1, j = 0, jj = 0;
  405. for(j=start; j>=0;) {
  406. chkd[j] = true;
  407. buf[buf.length] = j;
  408. buf_chain.push(sectors[j]);
  409. var addr = fat_addrs[Math.floor(j*4/ssz)];
  410. jj = ((j*4) & modulus);
  411. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  412. if(!sectors[addr]) break;
  413. j = __readInt32LE(sectors[addr], jj);
  414. }
  415. return {nodes: buf, data:__toBuffer([buf_chain])};
  416. }
  417. /** Chase down the sector linked lists */
  418. function make_sector_list(sectors/*:Array<RawBytes>*/, dir_start/*:number*/, fat_addrs/*:Array<number>*/, ssz/*:number*/)/*:SectorList*/ {
  419. var sl = sectors.length, sector_list/*:SectorList*/ = ([]/*:any*/);
  420. var chkd/*:Array<boolean>*/ = [], buf/*:Array<number>*/ = [], buf_chain/*:Array<RawBytes>*/ = [];
  421. var modulus = ssz - 1, i=0, j=0, k=0, jj=0;
  422. for(i=0; i < sl; ++i) {
  423. buf = ([]/*:Array<number>*/);
  424. k = (i + dir_start); if(k >= sl) k-=sl;
  425. if(chkd[k]) continue;
  426. buf_chain = [];
  427. var seen = [];
  428. for(j=k; j>=0;) {
  429. seen[j] = true;
  430. chkd[j] = true;
  431. buf[buf.length] = j;
  432. buf_chain.push(sectors[j]);
  433. var addr/*:number*/ = fat_addrs[Math.floor(j*4/ssz)];
  434. jj = ((j*4) & modulus);
  435. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  436. if(!sectors[addr]) break;
  437. j = __readInt32LE(sectors[addr], jj);
  438. if(seen[j]) break;
  439. }
  440. sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])}/*:SectorEntry*/);
  441. }
  442. return sector_list;
  443. }
  444. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  445. function read_directory(dir_start/*:number*/, sector_list/*:SectorList*/, sectors/*:Array<RawBytes>*/, Paths/*:Array<string>*/, nmfs, files, FileIndex, mini) {
  446. var minifat_store = 0, pl = (Paths.length?2:0);
  447. var sector = sector_list[dir_start].data;
  448. var i = 0, namelen = 0, name;
  449. for(; i < sector.length; i+= 128) {
  450. var blob/*:CFBlob*/ = /*::(*/sector.slice(i, i+128)/*:: :any)*/;
  451. prep_blob(blob, 64);
  452. namelen = blob.read_shift(2);
  453. name = __utf16le(blob,0,namelen-pl);
  454. Paths.push(name);
  455. var o/*:CFBEntry*/ = ({
  456. name: name,
  457. type: blob.read_shift(1),
  458. color: blob.read_shift(1),
  459. L: blob.read_shift(4, 'i'),
  460. R: blob.read_shift(4, 'i'),
  461. C: blob.read_shift(4, 'i'),
  462. clsid: blob.read_shift(16),
  463. state: blob.read_shift(4, 'i'),
  464. start: 0,
  465. size: 0
  466. });
  467. var ctime/*:number*/ = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  468. if(ctime !== 0) o.ct = read_date(blob, blob.l-8);
  469. var mtime/*:number*/ = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  470. if(mtime !== 0) o.mt = read_date(blob, blob.l-8);
  471. o.start = blob.read_shift(4, 'i');
  472. o.size = blob.read_shift(4, 'i');
  473. if(o.size < 0 && o.start < 0) { o.size = o.type = 0; o.start = ENDOFCHAIN; o.name = ""; }
  474. if(o.type === 5) { /* root */
  475. minifat_store = o.start;
  476. if(nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
  477. /*minifat_size = o.size;*/
  478. } else if(o.size >= 4096 /* MSCSZ */) {
  479. o.storage = 'fat';
  480. if(sector_list[o.start] === undefined) sector_list[o.start] = get_sector_list(sectors, o.start, sector_list.fat_addrs, sector_list.ssz);
  481. sector_list[o.start].name = o.name;
  482. o.content = (sector_list[o.start].data.slice(0,o.size)/*:any*/);
  483. } else {
  484. o.storage = 'minifat';
  485. if(o.size < 0) o.size = 0;
  486. else if(minifat_store !== ENDOFCHAIN && o.start !== ENDOFCHAIN && sector_list[minifat_store]) {
  487. o.content = get_mfat_entry(o, sector_list[minifat_store].data, (sector_list[mini]||{}).data);
  488. }
  489. }
  490. if(o.content) prep_blob(o.content, 0);
  491. files[name] = o;
  492. FileIndex.push(o);
  493. }
  494. }
  495. function read_date(blob/*:RawBytes|CFBlob*/, offset/*:number*/)/*:Date*/ {
  496. return new Date(( ( (__readUInt32LE(blob,offset+4)/1e7)*Math.pow(2,32)+__readUInt32LE(blob,offset)/1e7 ) - 11644473600)*1000);
  497. }
  498. function read_file(filename/*:string*/, options/*:CFBReadOpts*/) {
  499. get_fs();
  500. return parse(fs.readFileSync(filename), options);
  501. }
  502. function read(blob/*:RawBytes|string*/, options/*:CFBReadOpts*/) {
  503. var type = options && options.type;
  504. if(!type) {
  505. if(has_buf && Buffer.isBuffer(blob)) type = "buffer";
  506. }
  507. switch(type || "base64") {
  508. case "file": /*:: if(typeof blob !== 'string') throw "Must pass a filename when type='file'"; */return read_file(blob, options);
  509. case "base64": /*:: if(typeof blob !== 'string') throw "Must pass a base64-encoded binary string when type='file'"; */return parse(s2a(Base64.decode(blob)), options);
  510. case "binary": /*:: if(typeof blob !== 'string') throw "Must pass a binary string when type='file'"; */return parse(s2a(blob), options);
  511. }
  512. return parse(/*::typeof blob == 'string' ? new Buffer(blob, 'utf-8') : */blob, options);
  513. }
  514. function init_cfb(cfb/*:CFBContainer*/, opts/*:?any*/)/*:void*/ {
  515. var o = opts || {}, root = o.root || "Root Entry";
  516. if(!cfb.FullPaths) cfb.FullPaths = [];
  517. if(!cfb.FileIndex) cfb.FileIndex = [];
  518. if(cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
  519. if(cfb.FullPaths.length === 0) {
  520. cfb.FullPaths[0] = root + "/";
  521. cfb.FileIndex[0] = ({ name: root, type: 5 }/*:any*/);
  522. }
  523. if(o.CLSID) cfb.FileIndex[0].clsid = o.CLSID;
  524. seed_cfb(cfb);
  525. }
  526. function seed_cfb(cfb/*:CFBContainer*/)/*:void*/ {
  527. var nm = "\u0001Sh33tJ5";
  528. if(CFB.find(cfb, "/" + nm)) return;
  529. var p = new_buf(4); p[0] = 55; p[1] = p[3] = 50; p[2] = 54;
  530. cfb.FileIndex.push(({ name: nm, type: 2, content:p, size:4, L:69, R:69, C:69 }/*:any*/));
  531. cfb.FullPaths.push(cfb.FullPaths[0] + nm);
  532. rebuild_cfb(cfb);
  533. }
  534. function rebuild_cfb(cfb/*:CFBContainer*/, f/*:?boolean*/)/*:void*/ {
  535. init_cfb(cfb);
  536. var gc = false, s = false;
  537. for(var i = cfb.FullPaths.length - 1; i >= 0; --i) {
  538. var _file = cfb.FileIndex[i];
  539. switch(_file.type) {
  540. case 0:
  541. if(s) gc = true;
  542. else { cfb.FileIndex.pop(); cfb.FullPaths.pop(); }
  543. break;
  544. case 1: case 2: case 5:
  545. s = true;
  546. if(isNaN(_file.R * _file.L * _file.C)) gc = true;
  547. if(_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
  548. break;
  549. default: gc = true; break;
  550. }
  551. }
  552. if(!gc && !f) return;
  553. var now = new Date(1987, 1, 19), j = 0;
  554. // Track which names exist
  555. var fullPaths = Object.create ? Object.create(null) : {};
  556. var data/*:Array<[string, CFBEntry]>*/ = [];
  557. for(i = 0; i < cfb.FullPaths.length; ++i) {
  558. fullPaths[cfb.FullPaths[i]] = true;
  559. if(cfb.FileIndex[i].type === 0) continue;
  560. data.push([cfb.FullPaths[i], cfb.FileIndex[i]]);
  561. }
  562. for(i = 0; i < data.length; ++i) {
  563. var dad = dirname(data[i][0]);
  564. s = fullPaths[dad];
  565. if(!s) {
  566. data.push([dad, ({
  567. name: filename(dad).replace("/",""),
  568. type: 1,
  569. clsid: HEADER_CLSID,
  570. ct: now, mt: now,
  571. content: null
  572. }/*:any*/)]);
  573. // Add name to set
  574. fullPaths[dad] = true;
  575. }
  576. }
  577. data.sort(function(x,y) { return namecmp(x[0], y[0]); });
  578. cfb.FullPaths = []; cfb.FileIndex = [];
  579. for(i = 0; i < data.length; ++i) { cfb.FullPaths[i] = data[i][0]; cfb.FileIndex[i] = data[i][1]; }
  580. for(i = 0; i < data.length; ++i) {
  581. var elt = cfb.FileIndex[i];
  582. var nm = cfb.FullPaths[i];
  583. elt.name = filename(nm).replace("/","");
  584. elt.L = elt.R = elt.C = -(elt.color = 1);
  585. elt.size = elt.content ? elt.content.length : 0;
  586. elt.start = 0;
  587. elt.clsid = (elt.clsid || HEADER_CLSID);
  588. if(i === 0) {
  589. elt.C = data.length > 1 ? 1 : -1;
  590. elt.size = 0;
  591. elt.type = 5;
  592. } else if(nm.slice(-1) == "/") {
  593. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==nm) break;
  594. elt.C = j >= data.length ? -1 : j;
  595. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==dirname(nm)) break;
  596. elt.R = j >= data.length ? -1 : j;
  597. elt.type = 1;
  598. } else {
  599. if(dirname(cfb.FullPaths[i+1]||"") == dirname(nm)) elt.R = i + 1;
  600. elt.type = 2;
  601. }
  602. }
  603. }
  604. function _write(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:RawBytes|string*/ {
  605. var _opts = options || {};
  606. /* MAD is order-sensitive, skip rebuild and sort */
  607. if(_opts.fileType == 'mad') return write_mad(cfb, _opts);
  608. rebuild_cfb(cfb);
  609. switch(_opts.fileType) {
  610. case 'zip': return write_zip(cfb, _opts);
  611. //case 'mad': return write_mad(cfb, _opts);
  612. }
  613. var L = (function(cfb/*:CFBContainer*/)/*:Array<number>*/{
  614. var mini_size = 0, fat_size = 0;
  615. for(var i = 0; i < cfb.FileIndex.length; ++i) {
  616. var file = cfb.FileIndex[i];
  617. if(!file.content) continue;
  618. /*:: if(file.content == null) throw new Error("unreachable"); */
  619. var flen = file.content.length;
  620. if(flen > 0){
  621. if(flen < 0x1000) mini_size += (flen + 0x3F) >> 6;
  622. else fat_size += (flen + 0x01FF) >> 9;
  623. }
  624. }
  625. var dir_cnt = (cfb.FullPaths.length +3) >> 2;
  626. var mini_cnt = (mini_size + 7) >> 3;
  627. var mfat_cnt = (mini_size + 0x7F) >> 7;
  628. var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
  629. var fat_cnt = (fat_base + 0x7F) >> 7;
  630. var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  631. while(((fat_base + fat_cnt + difat_cnt + 0x7F) >> 7) > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  632. var L = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
  633. cfb.FileIndex[0].size = mini_size << 6;
  634. L[7] = (cfb.FileIndex[0].start=L[0]+L[1]+L[2]+L[3]+L[4]+L[5])+((L[6]+7) >> 3);
  635. return L;
  636. })(cfb);
  637. var o = new_buf(L[7] << 9);
  638. var i = 0, T = 0;
  639. {
  640. for(i = 0; i < 8; ++i) o.write_shift(1, HEADER_SIG[i]);
  641. for(i = 0; i < 8; ++i) o.write_shift(2, 0);
  642. o.write_shift(2, 0x003E);
  643. o.write_shift(2, 0x0003);
  644. o.write_shift(2, 0xFFFE);
  645. o.write_shift(2, 0x0009);
  646. o.write_shift(2, 0x0006);
  647. for(i = 0; i < 3; ++i) o.write_shift(2, 0);
  648. o.write_shift(4, 0);
  649. o.write_shift(4, L[2]);
  650. o.write_shift(4, L[0] + L[1] + L[2] + L[3] - 1);
  651. o.write_shift(4, 0);
  652. o.write_shift(4, 1<<12);
  653. o.write_shift(4, L[3] ? L[0] + L[1] + L[2] - 1: ENDOFCHAIN);
  654. o.write_shift(4, L[3]);
  655. o.write_shift(-4, L[1] ? L[0] - 1: ENDOFCHAIN);
  656. o.write_shift(4, L[1]);
  657. for(i = 0; i < 109; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  658. }
  659. if(L[1]) {
  660. for(T = 0; T < L[1]; ++T) {
  661. for(; i < 236 + T * 127; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  662. o.write_shift(-4, T === L[1] - 1 ? ENDOFCHAIN : T + 1);
  663. }
  664. }
  665. var chainit = function(w/*:number*/)/*:void*/ {
  666. for(T += w; i<T-1; ++i) o.write_shift(-4, i+1);
  667. if(w) { ++i; o.write_shift(-4, ENDOFCHAIN); }
  668. };
  669. T = i = 0;
  670. for(T+=L[1]; i<T; ++i) o.write_shift(-4, consts.DIFSECT);
  671. for(T+=L[2]; i<T; ++i) o.write_shift(-4, consts.FATSECT);
  672. chainit(L[3]);
  673. chainit(L[4]);
  674. var j/*:number*/ = 0, flen/*:number*/ = 0;
  675. var file/*:CFBEntry*/ = cfb.FileIndex[0];
  676. for(; j < cfb.FileIndex.length; ++j) {
  677. file = cfb.FileIndex[j];
  678. if(!file.content) continue;
  679. /*:: if(file.content == null) throw new Error("unreachable"); */
  680. flen = file.content.length;
  681. if(flen < 0x1000) continue;
  682. file.start = T;
  683. chainit((flen + 0x01FF) >> 9);
  684. }
  685. chainit((L[6] + 7) >> 3);
  686. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  687. T = i = 0;
  688. for(j = 0; j < cfb.FileIndex.length; ++j) {
  689. file = cfb.FileIndex[j];
  690. if(!file.content) continue;
  691. /*:: if(file.content == null) throw new Error("unreachable"); */
  692. flen = file.content.length;
  693. if(!flen || flen >= 0x1000) continue;
  694. file.start = T;
  695. chainit((flen + 0x3F) >> 6);
  696. }
  697. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  698. for(i = 0; i < L[4]<<2; ++i) {
  699. var nm = cfb.FullPaths[i];
  700. if(!nm || nm.length === 0) {
  701. for(j = 0; j < 17; ++j) o.write_shift(4, 0);
  702. for(j = 0; j < 3; ++j) o.write_shift(4, -1);
  703. for(j = 0; j < 12; ++j) o.write_shift(4, 0);
  704. continue;
  705. }
  706. file = cfb.FileIndex[i];
  707. if(i === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
  708. var _nm/*:string*/ = (i === 0 && _opts.root) || file.name;
  709. flen = 2*(_nm.length+1);
  710. o.write_shift(64, _nm, "utf16le");
  711. o.write_shift(2, flen);
  712. o.write_shift(1, file.type);
  713. o.write_shift(1, file.color);
  714. o.write_shift(-4, file.L);
  715. o.write_shift(-4, file.R);
  716. o.write_shift(-4, file.C);
  717. if(!file.clsid) for(j = 0; j < 4; ++j) o.write_shift(4, 0);
  718. else o.write_shift(16, file.clsid, "hex");
  719. o.write_shift(4, file.state || 0);
  720. o.write_shift(4, 0); o.write_shift(4, 0);
  721. o.write_shift(4, 0); o.write_shift(4, 0);
  722. o.write_shift(4, file.start);
  723. o.write_shift(4, file.size); o.write_shift(4, 0);
  724. }
  725. for(i = 1; i < cfb.FileIndex.length; ++i) {
  726. file = cfb.FileIndex[i];
  727. /*:: if(!file.content) throw new Error("unreachable"); */
  728. if(file.size >= 0x1000) {
  729. o.l = (file.start+1) << 9;
  730. if (has_buf && Buffer.isBuffer(file.content)) {
  731. file.content.copy(o, o.l, 0, file.size);
  732. // o is a 0-filled Buffer so just set next offset
  733. o.l += (file.size + 511) & -512;
  734. } else {
  735. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  736. for(; j & 0x1FF; ++j) o.write_shift(1, 0);
  737. }
  738. }
  739. }
  740. for(i = 1; i < cfb.FileIndex.length; ++i) {
  741. file = cfb.FileIndex[i];
  742. /*:: if(!file.content) throw new Error("unreachable"); */
  743. if(file.size > 0 && file.size < 0x1000) {
  744. if (has_buf && Buffer.isBuffer(file.content)) {
  745. file.content.copy(o, o.l, 0, file.size);
  746. // o is a 0-filled Buffer so just set next offset
  747. o.l += (file.size + 63) & -64;
  748. } else {
  749. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  750. for(; j & 0x3F; ++j) o.write_shift(1, 0);
  751. }
  752. }
  753. }
  754. if (has_buf) {
  755. o.l = o.length;
  756. } else {
  757. // When using Buffer, already 0-filled
  758. while(o.l < o.length) o.write_shift(1, 0);
  759. }
  760. return o;
  761. }
  762. /* [MS-CFB] 2.6.4 (Unicode 3.0.1 case conversion) */
  763. function find(cfb/*:CFBContainer*/, path/*:string*/)/*:?CFBEntry*/ {
  764. var UCFullPaths/*:Array<string>*/ = cfb.FullPaths.map(function(x) { return x.toUpperCase(); });
  765. var UCPaths/*:Array<string>*/ = UCFullPaths.map(function(x) { var y = x.split("/"); return y[y.length - (x.slice(-1) == "/" ? 2 : 1)]; });
  766. var k/*:boolean*/ = false;
  767. if(path.charCodeAt(0) === 47 /* "/" */) { k = true; path = UCFullPaths[0].slice(0, -1) + path; }
  768. else k = path.indexOf("/") !== -1;
  769. var UCPath/*:string*/ = path.toUpperCase();
  770. var w/*:number*/ = k === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
  771. if(w !== -1) return cfb.FileIndex[w];
  772. var m = !UCPath.match(chr1);
  773. UCPath = UCPath.replace(chr0,'');
  774. if(m) UCPath = UCPath.replace(chr1,'!');
  775. for(w = 0; w < UCFullPaths.length; ++w) {
  776. if((m ? UCFullPaths[w].replace(chr1,'!') : UCFullPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  777. if((m ? UCPaths[w].replace(chr1,'!') : UCPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  778. }
  779. return null;
  780. }
  781. /** CFB Constants */
  782. var MSSZ = 64; /* Mini Sector Size = 1<<6 */
  783. //var MSCSZ = 4096; /* Mini Stream Cutoff Size */
  784. /* 2.1 Compound File Sector Numbers and Types */
  785. var ENDOFCHAIN = -2;
  786. /* 2.2 Compound File Header */
  787. var HEADER_SIGNATURE = 'd0cf11e0a1b11ae1';
  788. var HEADER_SIG = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
  789. var HEADER_CLSID = '00000000000000000000000000000000';
  790. var consts = {
  791. /* 2.1 Compund File Sector Numbers and Types */
  792. MAXREGSECT: -6,
  793. DIFSECT: -4,
  794. FATSECT: -3,
  795. ENDOFCHAIN: ENDOFCHAIN,
  796. FREESECT: -1,
  797. /* 2.2 Compound File Header */
  798. HEADER_SIGNATURE: HEADER_SIGNATURE,
  799. HEADER_MINOR_VERSION: '3e00',
  800. MAXREGSID: -6,
  801. NOSTREAM: -1,
  802. HEADER_CLSID: HEADER_CLSID,
  803. /* 2.6.1 Compound File Directory Entry */
  804. EntryTypes: ['unknown','storage','stream','lockbytes','property','root']
  805. };
  806. function write_file(cfb/*:CFBContainer*/, filename/*:string*/, options/*:CFBWriteOpts*/)/*:void*/ {
  807. get_fs();
  808. var o = _write(cfb, options);
  809. /*:: if(typeof Buffer == 'undefined' || !Buffer.isBuffer(o) || !(o instanceof Buffer)) throw new Error("unreachable"); */
  810. fs.writeFileSync(filename, o);
  811. }
  812. function a2s(o/*:RawBytes*/)/*:string*/ {
  813. var out = new Array(o.length);
  814. for(var i = 0; i < o.length; ++i) out[i] = String.fromCharCode(o[i]);
  815. return out.join("");
  816. }
  817. function write(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:RawBytes|string*/ {
  818. var o = _write(cfb, options);
  819. switch(options && options.type || "buffer") {
  820. case "file": get_fs(); fs.writeFileSync(options.filename, (o/*:any*/)); return o;
  821. case "binary": return typeof o == "string" ? o : a2s(o);
  822. case "base64": return Base64.encode(typeof o == "string" ? o : a2s(o));
  823. case "buffer": if(has_buf) return Buffer.isBuffer(o) ? o : Buffer_from(o);
  824. /* falls through */
  825. case "array": return typeof o == "string" ? s2a(o) : o;
  826. }
  827. return o;
  828. }
  829. /* node < 8.1 zlib does not expose bytesRead, so default to pure JS */
  830. var _zlib;
  831. function use_zlib(zlib) { try {
  832. var InflateRaw = zlib.InflateRaw;
  833. var InflRaw = new InflateRaw();
  834. InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
  835. if(InflRaw.bytesRead) _zlib = zlib;
  836. else throw new Error("zlib does not expose bytesRead");
  837. } catch(e) {console.error("cannot use native zlib: " + (e.message || e)); } }
  838. function _inflateRawSync(payload, usz) {
  839. if(!_zlib) return _inflate(payload, usz);
  840. var InflateRaw = _zlib.InflateRaw;
  841. var InflRaw = new InflateRaw();
  842. var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
  843. payload.l += InflRaw.bytesRead;
  844. return out;
  845. }
  846. function _deflateRawSync(payload) {
  847. return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
  848. }
  849. var CLEN_ORDER = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  850. /* 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 ]; */
  851. 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 ];
  852. /* 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 ]; */
  853. 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 ];
  854. function bit_swap_8(n) { var t = (((((n<<1)|(n<<11)) & 0x22110) | (((n<<5)|(n<<15)) & 0x88440))); return ((t>>16) | (t>>8) |t)&0xFF; }
  855. var use_typed_arrays = typeof Uint8Array !== 'undefined';
  856. var bitswap8 = use_typed_arrays ? new Uint8Array(1<<8) : [];
  857. for(var q = 0; q < (1<<8); ++q) bitswap8[q] = bit_swap_8(q);
  858. function bit_swap_n(n, b) {
  859. var rev = bitswap8[n & 0xFF];
  860. if(b <= 8) return rev >>> (8-b);
  861. rev = (rev << 8) | bitswap8[(n>>8)&0xFF];
  862. if(b <= 16) return rev >>> (16-b);
  863. rev = (rev << 8) | bitswap8[(n>>16)&0xFF];
  864. return rev >>> (24-b);
  865. }
  866. /* helpers for unaligned bit reads */
  867. 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; }
  868. 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; }
  869. 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; }
  870. 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; }
  871. 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; }
  872. /* works up to n = 3 * 8 + 1 = 25 */
  873. function read_bits_n(buf, bl, n) {
  874. var w = (bl&7), h = (bl>>>3), f = ((1<<n)-1);
  875. var v = buf[h] >>> w;
  876. if(n < 8 - w) return v & f;
  877. v |= buf[h+1]<<(8-w);
  878. if(n < 16 - w) return v & f;
  879. v |= buf[h+2]<<(16-w);
  880. if(n < 24 - w) return v & f;
  881. v |= buf[h+3]<<(24-w);
  882. return v & f;
  883. }
  884. /* helpers for unaligned bit writes */
  885. function write_bits_3(buf, bl, v) { var w = bl & 7, h = bl >>> 3;
  886. if(w <= 5) buf[h] |= (v & 7) << w;
  887. else {
  888. buf[h] |= (v << w) & 0xFF;
  889. buf[h+1] = (v&7) >> (8-w);
  890. }
  891. return bl + 3;
  892. }
  893. function write_bits_1(buf, bl, v) {
  894. var w = bl & 7, h = bl >>> 3;
  895. v = (v&1) << w;
  896. buf[h] |= v;
  897. return bl + 1;
  898. }
  899. function write_bits_8(buf, bl, v) {
  900. var w = bl & 7, h = bl >>> 3;
  901. v <<= w;
  902. buf[h] |= v & 0xFF; v >>>= 8;
  903. buf[h+1] = v;
  904. return bl + 8;
  905. }
  906. function write_bits_16(buf, bl, v) {
  907. var w = bl & 7, h = bl >>> 3;
  908. v <<= w;
  909. buf[h] |= v & 0xFF; v >>>= 8;
  910. buf[h+1] = v & 0xFF;
  911. buf[h+2] = v >>> 8;
  912. return bl + 16;
  913. }
  914. /* until ArrayBuffer#realloc is a thing, fake a realloc */
  915. function realloc(b, sz/*:number*/) {
  916. var L = b.length, M = 2*L > sz ? 2*L : sz + 5, i = 0;
  917. if(L >= sz) return b;
  918. if(has_buf) {
  919. var o = new_unsafe_buf(M);
  920. // $FlowIgnore
  921. if(b.copy) b.copy(o);
  922. else for(; i < b.length; ++i) o[i] = b[i];
  923. return o;
  924. } else if(use_typed_arrays) {
  925. var a = new Uint8Array(M);
  926. if(a.set) a.set(b);
  927. else for(; i < L; ++i) a[i] = b[i];
  928. return a;
  929. }
  930. b.length = M;
  931. return b;
  932. }
  933. /* zero-filled arrays for older browsers */
  934. function zero_fill_array(n) {
  935. var o = new Array(n);
  936. for(var i = 0; i < n; ++i) o[i] = 0;
  937. return o;
  938. }
  939. /* build tree (used for literals and lengths) */
  940. function build_tree(clens, cmap, MAX/*:number*/)/*:number*/ {
  941. var maxlen = 1, w = 0, i = 0, j = 0, ccode = 0, L = clens.length;
  942. var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  943. for(i = 0; i < 32; ++i) bl_count[i] = 0;
  944. for(i = L; i < MAX; ++i) clens[i] = 0;
  945. L = clens.length;
  946. var ctree = use_typed_arrays ? new Uint16Array(L) : zero_fill_array(L); // []
  947. /* build code tree */
  948. for(i = 0; i < L; ++i) {
  949. bl_count[(w = clens[i])]++;
  950. if(maxlen < w) maxlen = w;
  951. ctree[i] = 0;
  952. }
  953. bl_count[0] = 0;
  954. for(i = 1; i <= maxlen; ++i) bl_count[i+16] = (ccode = (ccode + bl_count[i-1])<<1);
  955. for(i = 0; i < L; ++i) {
  956. ccode = clens[i];
  957. if(ccode != 0) ctree[i] = bl_count[ccode+16]++;
  958. }
  959. /* cmap[maxlen + 4 bits] = (off&15) + (lit<<4) reverse mapping */
  960. var cleni = 0;
  961. for(i = 0; i < L; ++i) {
  962. cleni = clens[i];
  963. if(cleni != 0) {
  964. ccode = bit_swap_n(ctree[i], maxlen)>>(maxlen-cleni);
  965. for(j = (1<<(maxlen + 4 - cleni)) - 1; j>=0; --j)
  966. cmap[ccode|(j<<cleni)] = (cleni&15) | (i<<4);
  967. }
  968. }
  969. return maxlen;
  970. }
  971. /* Fixed Huffman */
  972. var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
  973. var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  974. if(!use_typed_arrays) {
  975. for(var i = 0; i < 512; ++i) fix_lmap[i] = 0;
  976. for(i = 0; i < 32; ++i) fix_dmap[i] = 0;
  977. }
  978. (function() {
  979. var dlens/*:Array<number>*/ = [];
  980. var i = 0;
  981. for(;i<32; i++) dlens.push(5);
  982. build_tree(dlens, fix_dmap, 32);
  983. var clens/*:Array<number>*/ = [];
  984. i = 0;
  985. for(; i<=143; i++) clens.push(8);
  986. for(; i<=255; i++) clens.push(9);
  987. for(; i<=279; i++) clens.push(7);
  988. for(; i<=287; i++) clens.push(8);
  989. build_tree(clens, fix_lmap, 288);
  990. })();var _deflateRaw = (function() {
  991. var DST_LN_RE = use_typed_arrays ? new Uint8Array(0x8000) : [];
  992. for(var j = 0, k = 0; j < DST_LN.length; ++j) {
  993. for(; k < DST_LN[j+1]; ++k) DST_LN_RE[k] = j;
  994. }
  995. for(;k < 32768; ++k) DST_LN_RE[k] = 29;
  996. var LEN_LN_RE = use_typed_arrays ? new Uint8Array(0x102) : [];
  997. for(j = 0, k = 0; j < LEN_LN.length; ++j) {
  998. for(; k < LEN_LN[j+1]; ++k) LEN_LN_RE[k] = j;
  999. }
  1000. function write_stored(data, out) {
  1001. var boff = 0;
  1002. while(boff < data.length) {
  1003. var L = Math.min(0xFFFF, data.length - boff);
  1004. var h = boff + L == data.length;
  1005. out.write_shift(1, +h);
  1006. out.write_shift(2, L);
  1007. out.write_shift(2, (~L) & 0xFFFF);
  1008. while(L-- > 0) out[out.l++] = data[boff++];
  1009. }
  1010. return out.l;
  1011. }
  1012. /* Fixed Huffman */
  1013. function write_huff_fixed(data, out) {
  1014. var bl = 0;
  1015. var boff = 0;
  1016. var addrs = use_typed_arrays ? new Uint16Array(0x8000) : [];
  1017. while(boff < data.length) {
  1018. var L = /* data.length - boff; */ Math.min(0xFFFF, data.length - boff);
  1019. /* write a stored block for short data */
  1020. if(L < 10) {
  1021. bl = write_bits_3(out, bl, +!!(boff + L == data.length)); // jshint ignore:line
  1022. if(bl & 7) bl += 8 - (bl & 7);
  1023. out.l = (bl / 8) | 0;
  1024. out.write_shift(2, L);
  1025. out.write_shift(2, (~L) & 0xFFFF);
  1026. while(L-- > 0) out[out.l++] = data[boff++];
  1027. bl = out.l * 8;
  1028. continue;
  1029. }
  1030. bl = write_bits_3(out, bl, +!!(boff + L == data.length) + 2); // jshint ignore:line
  1031. var hash = 0;
  1032. while(L-- > 0) {
  1033. var d = data[boff];
  1034. hash = ((hash << 5) ^ d) & 0x7FFF;
  1035. var match = -1, mlen = 0;
  1036. if((match = addrs[hash])) {
  1037. match |= boff & ~0x7FFF;
  1038. if(match > boff) match -= 0x8000;
  1039. if(match < boff) while(data[match + mlen] == data[boff + mlen] && mlen < 250) ++mlen;
  1040. }
  1041. if(mlen > 2) {
  1042. /* Copy Token */
  1043. d = LEN_LN_RE[mlen];
  1044. if(d <= 22) bl = write_bits_8(out, bl, bitswap8[d+1]>>1) - 1;
  1045. else {
  1046. write_bits_8(out, bl, 3);
  1047. bl += 5;
  1048. write_bits_8(out, bl, bitswap8[d-23]>>5);
  1049. bl += 3;
  1050. }
  1051. var len_eb = (d < 8) ? 0 : ((d - 4)>>2);
  1052. if(len_eb > 0) {
  1053. write_bits_16(out, bl, mlen - LEN_LN[d]);
  1054. bl += len_eb;
  1055. }
  1056. d = DST_LN_RE[boff - match];
  1057. bl = write_bits_8(out, bl, bitswap8[d]>>3);
  1058. bl -= 3;
  1059. var dst_eb = d < 4 ? 0 : (d-2)>>1;
  1060. if(dst_eb > 0) {
  1061. write_bits_16(out, bl, boff - match - DST_LN[d]);
  1062. bl += dst_eb;
  1063. }
  1064. for(var q = 0; q < mlen; ++q) {
  1065. addrs[hash] = boff & 0x7FFF;
  1066. hash = ((hash << 5) ^ data[boff]) & 0x7FFF;
  1067. ++boff;
  1068. }
  1069. L-= mlen - 1;
  1070. } else {
  1071. /* Literal Token */
  1072. if(d <= 143) d = d + 48;
  1073. else bl = write_bits_1(out, bl, 1);
  1074. bl = write_bits_8(out, bl, bitswap8[d]);
  1075. addrs[hash] = boff & 0x7FFF;
  1076. ++boff;
  1077. }
  1078. }
  1079. bl = write_bits_8(out, bl, 0) - 1;
  1080. }
  1081. out.l = ((bl + 7)/8)|0;
  1082. return out.l;
  1083. }
  1084. return function _deflateRaw(data, out) {
  1085. if(data.length < 8) return write_stored(data, out);
  1086. return write_huff_fixed(data, out);
  1087. };
  1088. })();
  1089. function _deflate(data) {
  1090. var buf = new_buf(50+Math.floor(data.length*1.1));
  1091. var off = _deflateRaw(data, buf);
  1092. return buf.slice(0, off);
  1093. }
  1094. /* modified inflate function also moves original read head */
  1095. var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  1096. var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  1097. var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128);
  1098. var dyn_len_1 = 1, dyn_len_2 = 1;
  1099. /* 5.5.3 Expanding Huffman Codes */
  1100. function dyn(data, boff/*:number*/) {
  1101. /* nomenclature from RFC1951 refers to bit values; these are offset by the implicit constant */
  1102. var _HLIT = read_bits_5(data, boff) + 257; boff += 5;
  1103. var _HDIST = read_bits_5(data, boff) + 1; boff += 5;
  1104. var _HCLEN = read_bits_4(data, boff) + 4; boff += 4;
  1105. var w = 0;
  1106. /* grab and store code lengths */
  1107. var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
  1108. var ctree = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
  1109. var maxlen = 1;
  1110. var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  1111. var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  1112. var L = clens.length; /* 19 */
  1113. for(var i = 0; i < _HCLEN; ++i) {
  1114. clens[CLEN_ORDER[i]] = w = read_bits_3(data, boff);
  1115. if(maxlen < w) maxlen = w;
  1116. bl_count[w]++;
  1117. boff += 3;
  1118. }
  1119. /* build code tree */
  1120. var ccode = 0;
  1121. bl_count[0] = 0;
  1122. for(i = 1; i <= maxlen; ++i) next_code[i] = ccode = (ccode + bl_count[i-1])<<1;
  1123. for(i = 0; i < L; ++i) if((ccode = clens[i]) != 0) ctree[i] = next_code[ccode]++;
  1124. /* cmap[7 bits from stream] = (off&7) + (lit<<3) */
  1125. var cleni = 0;
  1126. for(i = 0; i < L; ++i) {
  1127. cleni = clens[i];
  1128. if(cleni != 0) {
  1129. ccode = bitswap8[ctree[i]]>>(8-cleni);
  1130. for(var j = (1<<(7-cleni))-1; j>=0; --j) dyn_cmap[ccode|(j<<cleni)] = (cleni&7) | (i<<3);
  1131. }
  1132. }
  1133. /* read literal and dist codes at once */
  1134. var hcodes/*:Array<number>*/ = [];
  1135. maxlen = 1;
  1136. for(; hcodes.length < _HLIT + _HDIST;) {
  1137. ccode = dyn_cmap[read_bits_7(data, boff)];
  1138. boff += ccode & 7;
  1139. switch((ccode >>>= 3)) {
  1140. case 16:
  1141. w = 3 + read_bits_2(data, boff); boff += 2;
  1142. ccode = hcodes[hcodes.length - 1];
  1143. while(w-- > 0) hcodes.push(ccode);
  1144. break;
  1145. case 17:
  1146. w = 3 + read_bits_3(data, boff); boff += 3;
  1147. while(w-- > 0) hcodes.push(0);
  1148. break;
  1149. case 18:
  1150. w = 11 + read_bits_7(data, boff); boff += 7;
  1151. while(w -- > 0) hcodes.push(0);
  1152. break;
  1153. default:
  1154. hcodes.push(ccode);
  1155. if(maxlen < ccode) maxlen = ccode;
  1156. break;
  1157. }
  1158. }
  1159. /* build literal / length trees */
  1160. var h1 = hcodes.slice(0, _HLIT), h2 = hcodes.slice(_HLIT);
  1161. for(i = _HLIT; i < 286; ++i) h1[i] = 0;
  1162. for(i = _HDIST; i < 30; ++i) h2[i] = 0;
  1163. dyn_len_1 = build_tree(h1, dyn_lmap, 286);
  1164. dyn_len_2 = build_tree(h2, dyn_dmap, 30);
  1165. return boff;
  1166. }
  1167. /* return [ data, bytesRead ] */
  1168. function inflate(data, usz/*:number*/) {
  1169. /* shortcircuit for empty buffer [0x03, 0x00] */
  1170. if(data[0] == 3 && !(data[1] & 0x3)) { return [new_raw_buf(usz), 2]; }
  1171. /* bit offset */
  1172. var boff = 0;
  1173. /* header includes final bit and type bits */
  1174. var header = 0;
  1175. var outbuf = new_unsafe_buf(usz ? usz : (1<<18));
  1176. var woff = 0;
  1177. var OL = outbuf.length>>>0;
  1178. var max_len_1 = 0, max_len_2 = 0;
  1179. while((header&1) == 0) {
  1180. header = read_bits_3(data, boff); boff += 3;
  1181. if((header >>> 1) == 0) {
  1182. /* Stored block */
  1183. if(boff & 7) boff += 8 - (boff&7);
  1184. /* 2 bytes sz, 2 bytes bit inverse */
  1185. var sz = data[boff>>>3] | data[(boff>>>3)+1]<<8;
  1186. boff += 32;
  1187. /* push sz bytes */
  1188. if(!usz && OL < woff + sz) { outbuf = realloc(outbuf, woff + sz); OL = outbuf.length; }
  1189. if(typeof data.copy === 'function') {
  1190. // $FlowIgnore
  1191. data.copy(outbuf, woff, boff>>>3, (boff>>>3)+sz);
  1192. woff += sz; boff += 8*sz;
  1193. } else while(sz-- > 0) { outbuf[woff++] = data[boff>>>3]; boff += 8; }
  1194. continue;
  1195. } else if((header >>> 1) == 1) {
  1196. /* Fixed Huffman */
  1197. max_len_1 = 9; max_len_2 = 5;
  1198. } else {
  1199. /* Dynamic Huffman */
  1200. boff = dyn(data, boff);
  1201. max_len_1 = dyn_len_1; max_len_2 = dyn_len_2;
  1202. }
  1203. for(;;) { // while(true) is apparently out of vogue in modern JS circles
  1204. if(!usz && (OL < woff + 32767)) { outbuf = realloc(outbuf, woff + 32767); OL = outbuf.length; }
  1205. /* ingest code and move read head */
  1206. var bits = read_bits_n(data, boff, max_len_1);
  1207. var code = (header>>>1) == 1 ? fix_lmap[bits] : dyn_lmap[bits];
  1208. boff += code & 15; code >>>= 4;
  1209. /* 0-255 are literals, 256 is end of block token, 257+ are copy tokens */
  1210. if(((code>>>8)&0xFF) === 0) outbuf[woff++] = code;
  1211. else if(code == 256) break;
  1212. else {
  1213. code -= 257;
  1214. var len_eb = (code < 8) ? 0 : ((code-4)>>2); if(len_eb > 5) len_eb = 0;
  1215. var tgt = woff + LEN_LN[code];
  1216. /* length extra bits */
  1217. if(len_eb > 0) {
  1218. tgt += read_bits_n(data, boff, len_eb);
  1219. boff += len_eb;
  1220. }
  1221. /* dist code */
  1222. bits = read_bits_n(data, boff, max_len_2);
  1223. code = (header>>>1) == 1 ? fix_dmap[bits] : dyn_dmap[bits];
  1224. boff += code & 15; code >>>= 4;
  1225. var dst_eb = (code < 4 ? 0 : (code-2)>>1);
  1226. var dst = DST_LN[code];
  1227. /* dist extra bits */
  1228. if(dst_eb > 0) {
  1229. dst += read_bits_n(data, boff, dst_eb);
  1230. boff += dst_eb;
  1231. }
  1232. /* in the common case, manual byte copy is faster than TA set / Buffer copy */
  1233. if(!usz && OL < tgt) { outbuf = realloc(outbuf, tgt + 100); OL = outbuf.length; }
  1234. while(woff < tgt) { outbuf[woff] = outbuf[woff - dst]; ++woff; }
  1235. }
  1236. }
  1237. }
  1238. return [usz ? outbuf : outbuf.slice(0, woff), (boff+7)>>>3];
  1239. }
  1240. function _inflate(payload, usz) {
  1241. var data = payload.slice(payload.l||0);
  1242. var out = inflate(data, usz);
  1243. payload.l += out[1];
  1244. return out[0];
  1245. }
  1246. function warn_or_throw(wrn, msg) {
  1247. if(wrn) { if(typeof console !== 'undefined') console.error(msg); }
  1248. else throw new Error(msg);
  1249. }
  1250. function parse_zip(file/*:RawBytes*/, options/*:CFBReadOpts*/)/*:CFBContainer*/ {
  1251. var blob/*:CFBlob*/ = /*::(*/file/*:: :any)*/;
  1252. prep_blob(blob, 0);
  1253. var FileIndex/*:CFBFileIndex*/ = [], FullPaths/*:Array<string>*/ = [];
  1254. var o = {
  1255. FileIndex: FileIndex,
  1256. FullPaths: FullPaths
  1257. };
  1258. init_cfb(o, { root: options.root });
  1259. /* find end of central directory, start just after signature */
  1260. var i = blob.length - 4;
  1261. while((blob[i] != 0x50 || blob[i+1] != 0x4b || blob[i+2] != 0x05 || blob[i+3] != 0x06) && i >= 0) --i;
  1262. blob.l = i + 4;
  1263. /* parse end of central directory */
  1264. blob.l += 4;
  1265. var fcnt = blob.read_shift(2);
  1266. blob.l += 6;
  1267. var start_cd = blob.read_shift(4);
  1268. /* parse central directory */
  1269. blob.l = start_cd;
  1270. for(i = 0; i < fcnt; ++i) {
  1271. /* trust local file header instead of CD entry */
  1272. blob.l += 20;
  1273. var csz = blob.read_shift(4);
  1274. var usz = blob.read_shift(4);
  1275. var namelen = blob.read_shift(2);
  1276. var efsz = blob.read_shift(2);
  1277. var fcsz = blob.read_shift(2);
  1278. blob.l += 8;
  1279. var offset = blob.read_shift(4);
  1280. var EF = parse_extra_field(/*::(*/blob.slice(blob.l+namelen, blob.l+namelen+efsz)/*:: :any)*/);
  1281. blob.l += namelen + efsz + fcsz;
  1282. var L = blob.l;
  1283. blob.l = offset + 4;
  1284. parse_local_file(blob, csz, usz, o, EF);
  1285. blob.l = L;
  1286. }
  1287. return o;
  1288. }
  1289. /* head starts just after local file header signature */
  1290. function parse_local_file(blob/*:CFBlob*/, csz/*:number*/, usz/*:number*/, o/*:CFBContainer*/, EF) {
  1291. /* [local file header] */
  1292. blob.l += 2;
  1293. var flags = blob.read_shift(2);
  1294. var meth = blob.read_shift(2);
  1295. var date = parse_dos_date(blob);
  1296. if(flags & 0x2041) throw new Error("Unsupported ZIP encryption");
  1297. var crc32 = blob.read_shift(4);
  1298. var _csz = blob.read_shift(4);
  1299. var _usz = blob.read_shift(4);
  1300. var namelen = blob.read_shift(2);
  1301. var efsz = blob.read_shift(2);
  1302. // TODO: flags & (1<<11) // UTF8
  1303. var name = ""; for(var i = 0; i < namelen; ++i) name += String.fromCharCode(blob[blob.l++]);
  1304. if(efsz) {
  1305. var ef = parse_extra_field(/*::(*/blob.slice(blob.l, blob.l + efsz)/*:: :any)*/);
  1306. if((ef[0x5455]||{}).mt) date = ef[0x5455].mt;
  1307. if(((EF||{})[0x5455]||{}).mt) date = EF[0x5455].mt;
  1308. }
  1309. blob.l += efsz;
  1310. /* [encryption header] */
  1311. /* [file data] */
  1312. var data = blob.slice(blob.l, blob.l + _csz);
  1313. switch(meth) {
  1314. case 8: data = _inflateRawSync(blob, _usz); break;
  1315. case 0: break; // TODO: scan for magic number
  1316. default: throw new Error("Unsupported ZIP Compression method " + meth);
  1317. }
  1318. /* [data descriptor] */
  1319. var wrn = false;
  1320. if(flags & 8) {
  1321. crc32 = blob.read_shift(4);
  1322. if(crc32 == 0x08074b50) { crc32 = blob.read_shift(4); wrn = true; }
  1323. _csz = blob.read_shift(4);
  1324. _usz = blob.read_shift(4);
  1325. }
  1326. if(_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
  1327. if(_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
  1328. var _crc32 = CRC32.buf(data, 0);
  1329. if((crc32>>0) != (_crc32>>0)) warn_or_throw(wrn, "Bad CRC32 checksum: " + crc32 + " != " + _crc32);
  1330. cfb_add(o, name, data, {unsafe: true, mt: date});
  1331. }
  1332. function write_zip(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:RawBytes*/ {
  1333. var _opts = options || {};
  1334. var out = [], cdirs = [];
  1335. var o/*:CFBlob*/ = new_buf(1);
  1336. var method = (_opts.compression ? 8 : 0), flags = 0;
  1337. var desc = false;
  1338. if(desc) flags |= 8;
  1339. var i = 0, j = 0;
  1340. var start_cd = 0, fcnt = 0;
  1341. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  1342. var crcs = [];
  1343. var sz_cd = 0;
  1344. for(i = 1; i < cfb.FullPaths.length; ++i) {
  1345. fp = cfb.FullPaths[i].slice(root.length); fi = cfb.FileIndex[i];
  1346. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  1347. var start = start_cd;
  1348. /* TODO: CP437 filename */
  1349. var namebuf = new_buf(fp.length);
  1350. for(j = 0; j < fp.length; ++j) namebuf.write_shift(1, fp.charCodeAt(j) & 0x7F);
  1351. namebuf = namebuf.slice(0, namebuf.l);
  1352. crcs[fcnt] = CRC32.buf(/*::((*/fi.content/*::||[]):any)*/, 0);
  1353. var outbuf = fi.content/*::||[]*/;
  1354. if(method == 8) outbuf = _deflateRawSync(outbuf);
  1355. /* local file header */
  1356. o = new_buf(30);
  1357. o.write_shift(4, 0x04034b50);
  1358. o.write_shift(2, 20);
  1359. o.write_shift(2, flags);
  1360. o.write_shift(2, method);
  1361. /* TODO: last mod file time/date */
  1362. if(fi.mt) write_dos_date(o, fi.mt);
  1363. else o.write_shift(4, 0);
  1364. o.write_shift(-4, (flags & 8) ? 0 : crcs[fcnt]);
  1365. o.write_shift(4, (flags & 8) ? 0 : outbuf.length);
  1366. o.write_shift(4, (flags & 8) ? 0 : /*::(*/fi.content/*::||[])*/.length);
  1367. o.write_shift(2, namebuf.length);
  1368. o.write_shift(2, 0);
  1369. start_cd += o.length;
  1370. out.push(o);
  1371. start_cd += namebuf.length;
  1372. out.push(namebuf);
  1373. /* TODO: extra fields? */
  1374. /* TODO: encryption header ? */
  1375. start_cd += outbuf.length;
  1376. out.push(outbuf);
  1377. /* data descriptor */
  1378. if(flags & 8) {
  1379. o = new_buf(12);
  1380. o.write_shift(-4, crcs[fcnt]);
  1381. o.write_shift(4, outbuf.length);
  1382. o.write_shift(4, /*::(*/fi.content/*::||[])*/.length);
  1383. start_cd += o.l;
  1384. out.push(o);
  1385. }
  1386. /* central directory */
  1387. o = new_buf(46);
  1388. o.write_shift(4, 0x02014b50);
  1389. o.write_shift(2, 0);
  1390. o.write_shift(2, 20);
  1391. o.write_shift(2, flags);
  1392. o.write_shift(2, method);
  1393. o.write_shift(4, 0); /* TODO: last mod file time/date */
  1394. o.write_shift(-4, crcs[fcnt]);
  1395. o.write_shift(4, outbuf.length);
  1396. o.write_shift(4, /*::(*/fi.content/*::||[])*/.length);
  1397. o.write_shift(2, namebuf.length);
  1398. o.write_shift(2, 0);
  1399. o.write_shift(2, 0);
  1400. o.write_shift(2, 0);
  1401. o.write_shift(2, 0);
  1402. o.write_shift(4, 0);
  1403. o.write_shift(4, start);
  1404. sz_cd += o.l;
  1405. cdirs.push(o);
  1406. sz_cd += namebuf.length;
  1407. cdirs.push(namebuf);
  1408. ++fcnt;
  1409. }
  1410. /* end of central directory */
  1411. o = new_buf(22);
  1412. o.write_shift(4, 0x06054b50);
  1413. o.write_shift(2, 0);
  1414. o.write_shift(2, 0);
  1415. o.write_shift(2, fcnt);
  1416. o.write_shift(2, fcnt);
  1417. o.write_shift(4, sz_cd);
  1418. o.write_shift(4, start_cd);
  1419. o.write_shift(2, 0);
  1420. return bconcat(([bconcat((out/*:any*/)), bconcat(cdirs), o]/*:any*/));
  1421. }
  1422. var ContentTypeMap = ({
  1423. "htm": "text/html",
  1424. "xml": "text/xml",
  1425. "gif": "image/gif",
  1426. "jpg": "image/jpeg",
  1427. "png": "image/png",
  1428. "mso": "application/x-mso",
  1429. "thmx": "application/vnd.ms-officetheme",
  1430. "sh33tj5": "application/octet-stream"
  1431. }/*:any*/);
  1432. function get_content_type(fi/*:CFBEntry*/, fp/*:string*/)/*:string*/ {
  1433. if(fi.ctype) return fi.ctype;
  1434. var ext = fi.name || "", m = ext.match(/\.([^\.]+)$/);
  1435. if(m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
  1436. if(fp) {
  1437. m = (ext = fp).match(/[\.\\]([^\.\\])+$/);
  1438. if(m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
  1439. }
  1440. return "application/octet-stream";
  1441. }
  1442. /* 76 character chunks TODO: intertwine encoding */
  1443. function write_base64_76(bstr/*:string*/)/*:string*/ {
  1444. var data = Base64.encode(bstr);
  1445. var o = [];
  1446. for(var i = 0; i < data.length; i+= 76) o.push(data.slice(i, i+76));
  1447. return o.join("\r\n") + "\r\n";
  1448. }
  1449. /*
  1450. Rules for QP:
  1451. - escape =## applies for all non-display characters and literal "="
  1452. - space or tab at end of line must be encoded
  1453. - \r\n newlines can be preserved, but bare \r and \n must be escaped
  1454. - lines must not exceed 76 characters, use soft breaks =\r\n
  1455. TODO: Some files from word appear to write line extensions with bare equals:
  1456. ```
  1457. <table class=3DMsoTableGrid border=3D1 cellspacing=3D0 cellpadding=3D0 width=
  1458. ="70%"
  1459. ```
  1460. */
  1461. function write_quoted_printable(text/*:string*/)/*:string*/ {
  1462. var encoded = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF=]/g, function(c) {
  1463. var w = c.charCodeAt(0).toString(16).toUpperCase();
  1464. return "=" + (w.length == 1 ? "0" + w : w);
  1465. });
  1466. encoded = encoded.replace(/ $/mg, "=20").replace(/\t$/mg, "=09");
  1467. if(encoded.charAt(0) == "\n") encoded = "=0D" + encoded.slice(1);
  1468. encoded = encoded.replace(/\r(?!\n)/mg, "=0D").replace(/\n\n/mg, "\n=0A").replace(/([^\r\n])\n/mg, "$1=0A");
  1469. var o/*:Array<string>*/ = [], split = encoded.split("\r\n");
  1470. for(var si = 0; si < split.length; ++si) {
  1471. var str = split[si];
  1472. if(str.length == 0) { o.push(""); continue; }
  1473. for(var i = 0; i < str.length;) {
  1474. var end = 76;
  1475. var tmp = str.slice(i, i + end);
  1476. if(tmp.charAt(end - 1) == "=") end --;
  1477. else if(tmp.charAt(end - 2) == "=") end -= 2;
  1478. else if(tmp.charAt(end - 3) == "=") end -= 3;
  1479. tmp = str.slice(i, i + end);
  1480. i += end;
  1481. if(i < str.length) tmp += "=";
  1482. o.push(tmp);
  1483. }
  1484. }
  1485. return o.join("\r\n");
  1486. }
  1487. function parse_quoted_printable(data/*:Array<string>*/)/*:RawBytes*/ {
  1488. var o = [];
  1489. /* unify long lines */
  1490. for(var di = 0; di < data.length; ++di) {
  1491. var line = data[di];
  1492. while(di <= data.length && line.charAt(line.length - 1) == "=") line = line.slice(0, line.length - 1) + data[++di];
  1493. o.push(line);
  1494. }
  1495. /* decode */
  1496. for(var oi = 0; oi < o.length; ++oi) o[oi] = o[oi].replace(/=[0-9A-Fa-f]{2}/g, function($$) { return String.fromCharCode(parseInt($$.slice(1), 16)); });
  1497. return s2a(o.join("\r\n"));
  1498. }
  1499. function parse_mime(cfb/*:CFBContainer*/, data/*:Array<string>*/, root/*:string*/)/*:void*/ {
  1500. var fname = "", cte = "", ctype = "", fdata;
  1501. var di = 0;
  1502. for(;di < 10; ++di) {
  1503. var line = data[di];
  1504. if(!line || line.match(/^\s*$/)) break;
  1505. var m = line.match(/^(.*?):\s*([^\s].*)$/);
  1506. if(m) switch(m[1].toLowerCase()) {
  1507. case "content-location": fname = m[2].trim(); break;
  1508. case "content-type": ctype = m[2].trim(); break;
  1509. case "content-transfer-encoding": cte = m[2].trim(); break;
  1510. }
  1511. }
  1512. ++di;
  1513. switch(cte.toLowerCase()) {
  1514. case 'base64': fdata = s2a(Base64.decode(data.slice(di).join(""))); break;
  1515. case 'quoted-printable': fdata = parse_quoted_printable(data.slice(di)); break;
  1516. default: throw new Error("Unsupported Content-Transfer-Encoding " + cte);
  1517. }
  1518. var file = cfb_add(cfb, fname.slice(root.length), fdata, {unsafe: true});
  1519. if(ctype) file.ctype = ctype;
  1520. }
  1521. function parse_mad(file/*:RawBytes*/, options/*:CFBReadOpts*/)/*:CFBContainer*/ {
  1522. if(a2s(file.slice(0,13)).toLowerCase() != "mime-version:") throw new Error("Unsupported MAD header");
  1523. var root = (options && options.root || "");
  1524. // $FlowIgnore
  1525. var data = (has_buf && Buffer.isBuffer(file) ? file.toString("binary") : a2s(file)).split("\r\n");
  1526. var di = 0, row = "";
  1527. /* if root is not specified, scan for the common prefix */
  1528. for(di = 0; di < data.length; ++di) {
  1529. row = data[di];
  1530. if(!/^Content-Location:/i.test(row)) continue;
  1531. row = row.slice(row.indexOf("file"));
  1532. if(!root) root = row.slice(0, row.lastIndexOf("/") + 1);
  1533. if(row.slice(0, root.length) == root) continue;
  1534. while(root.length > 0) {
  1535. root = root.slice(0, root.length - 1);
  1536. root = root.slice(0, root.lastIndexOf("/") + 1);
  1537. if(row.slice(0,root.length) == root) break;
  1538. }
  1539. }
  1540. var mboundary = (data[1] || "").match(/boundary="(.*?)"/);
  1541. if(!mboundary) throw new Error("MAD cannot find boundary");
  1542. var boundary = "--" + (mboundary[1] || "");
  1543. var FileIndex/*:CFBFileIndex*/ = [], FullPaths/*:Array<string>*/ = [];
  1544. var o = {
  1545. FileIndex: FileIndex,
  1546. FullPaths: FullPaths
  1547. };
  1548. init_cfb(o);
  1549. var start_di, fcnt = 0;
  1550. for(di = 0; di < data.length; ++di) {
  1551. var line = data[di];
  1552. if(line !== boundary && line !== boundary + "--") continue;
  1553. if(fcnt++) parse_mime(o, data.slice(start_di, di), root);
  1554. start_di = di;
  1555. }
  1556. return o;
  1557. }
  1558. function write_mad(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:string*/ {
  1559. var opts = options || {};
  1560. var boundary = opts.boundary || "SheetJS";
  1561. boundary = '------=' + boundary;
  1562. var out = [
  1563. 'MIME-Version: 1.0',
  1564. 'Content-Type: multipart/related; boundary="' + boundary.slice(2) + '"',
  1565. '',
  1566. '',
  1567. ''
  1568. ];
  1569. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  1570. for(var i = 1; i < cfb.FullPaths.length; ++i) {
  1571. fp = cfb.FullPaths[i].slice(root.length);
  1572. fi = cfb.FileIndex[i];
  1573. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  1574. /* Normalize filename */
  1575. fp = fp.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF]/g, function(c) {
  1576. return "_x" + c.charCodeAt(0).toString(16) + "_";
  1577. }).replace(/[\u0080-\uFFFF]/g, function(u) {
  1578. return "_u" + u.charCodeAt(0).toString(16) + "_";
  1579. });
  1580. /* Extract content as binary string */
  1581. var ca = fi.content;
  1582. // $FlowIgnore
  1583. var cstr = has_buf && Buffer.isBuffer(ca) ? ca.toString("binary") : a2s(ca);
  1584. /* 4/5 of first 1024 chars ascii -> quoted printable, else base64 */
  1585. var dispcnt = 0, L = Math.min(1024, cstr.length), cc = 0;
  1586. for(var csl = 0; csl <= L; ++csl) if((cc=cstr.charCodeAt(csl)) >= 0x20 && cc < 0x80) ++dispcnt;
  1587. var qp = dispcnt >= L * 4 / 5;
  1588. out.push(boundary);
  1589. out.push('Content-Location: ' + (opts.root || 'file:///C:/SheetJS/') + fp);
  1590. out.push('Content-Transfer-Encoding: ' + (qp ? 'quoted-printable' : 'base64'));
  1591. out.push('Content-Type: ' + get_content_type(fi, fp));
  1592. out.push('');
  1593. out.push(qp ? write_quoted_printable(cstr) : write_base64_76(cstr));
  1594. }
  1595. out.push(boundary + '--\r\n');
  1596. return out.join("\r\n");
  1597. }
  1598. function cfb_new(opts/*:?any*/)/*:CFBContainer*/ {
  1599. var o/*:CFBContainer*/ = ({}/*:any*/);
  1600. init_cfb(o, opts);
  1601. return o;
  1602. }
  1603. function cfb_add(cfb/*:CFBContainer*/, name/*:string*/, content/*:?RawBytes*/, opts/*:?any*/)/*:CFBEntry*/ {
  1604. var unsafe = opts && opts.unsafe;
  1605. if(!unsafe) init_cfb(cfb);
  1606. var file = !unsafe && CFB.find(cfb, name);
  1607. if(!file) {
  1608. var fpath/*:string*/ = cfb.FullPaths[0];
  1609. if(name.slice(0, fpath.length) == fpath) fpath = name;
  1610. else {
  1611. if(fpath.slice(-1) != "/") fpath += "/";
  1612. fpath = (fpath + name).replace("//","/");
  1613. }
  1614. file = ({name: filename(name), type: 2}/*:any*/);
  1615. cfb.FileIndex.push(file);
  1616. cfb.FullPaths.push(fpath);
  1617. if(!unsafe) CFB.utils.cfb_gc(cfb);
  1618. }
  1619. /*:: if(!file) throw new Error("unreachable"); */
  1620. file.content = (content/*:any*/);
  1621. file.size = content ? content.length : 0;
  1622. if(opts) {
  1623. if(opts.CLSID) file.clsid = opts.CLSID;
  1624. if(opts.mt) file.mt = opts.mt;
  1625. if(opts.ct) file.ct = opts.ct;
  1626. }
  1627. return file;
  1628. }
  1629. function cfb_del(cfb/*:CFBContainer*/, name/*:string*/)/*:boolean*/ {
  1630. init_cfb(cfb);
  1631. var file = CFB.find(cfb, name);
  1632. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  1633. cfb.FileIndex.splice(j, 1);
  1634. cfb.FullPaths.splice(j, 1);
  1635. return true;
  1636. }
  1637. return false;
  1638. }
  1639. function cfb_mov(cfb/*:CFBContainer*/, old_name/*:string*/, new_name/*:string*/)/*:boolean*/ {
  1640. init_cfb(cfb);
  1641. var file = CFB.find(cfb, old_name);
  1642. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  1643. cfb.FileIndex[j].name = filename(new_name);
  1644. cfb.FullPaths[j] = new_name;
  1645. return true;
  1646. }
  1647. return false;
  1648. }
  1649. function cfb_gc(cfb/*:CFBContainer*/)/*:void*/ { rebuild_cfb(cfb, true); }
  1650. exports.find = find;
  1651. exports.read = read;
  1652. exports.parse = parse;
  1653. exports.write = write;
  1654. exports.writeFile = write_file;
  1655. exports.utils = {
  1656. cfb_new: cfb_new,
  1657. cfb_add: cfb_add,
  1658. cfb_del: cfb_del,
  1659. cfb_mov: cfb_mov,
  1660. cfb_gc: cfb_gc,
  1661. ReadShift: ReadShift,
  1662. CheckField: CheckField,
  1663. prep_blob: prep_blob,
  1664. bconcat: bconcat,
  1665. use_zlib: use_zlib,
  1666. _deflateRaw: _deflate,
  1667. _inflateRaw: _inflate,
  1668. consts: consts
  1669. };
  1670. return exports;
  1671. })();
  1672. if(typeof require !== 'undefined' && typeof module !== 'undefined' && typeof DO_NOT_EXPORT_CFB === 'undefined') { module.exports = CFB; }