xlscfb.js 59 KB

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