完成签约之后直接添加人员,录入下发凭证
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

15385 lines
523 KiB

  1. webpackJsonp([14],{
  2. /***/ "+php":
  3. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4. "use strict";
  5. // CONCATENATED MODULE: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/contractTemplate/contractTemplate.vue
  6. //
  7. //
  8. //
  9. //
  10. //
  11. //
  12. //
  13. //
  14. //
  15. //
  16. //
  17. //
  18. //
  19. //
  20. //
  21. //
  22. //
  23. //
  24. //
  25. //
  26. //
  27. //
  28. //
  29. //
  30. //
  31. //
  32. //
  33. //
  34. //
  35. //
  36. //
  37. //
  38. //
  39. //
  40. //
  41. //
  42. //
  43. //
  44. //
  45. //
  46. //
  47. //
  48. //
  49. //
  50. //
  51. //
  52. //
  53. //
  54. //
  55. //
  56. //
  57. //
  58. //
  59. //
  60. //
  61. //
  62. //
  63. //
  64. //
  65. //
  66. //
  67. //
  68. //
  69. //
  70. //
  71. //
  72. //
  73. //
  74. //
  75. //
  76. //
  77. //
  78. //
  79. //
  80. //
  81. //
  82. //
  83. //
  84. //
  85. //
  86. //
  87. //
  88. //
  89. //
  90. //
  91. //
  92. //
  93. //
  94. //
  95. //
  96. //
  97. //
  98. //
  99. //
  100. //
  101. //
  102. //
  103. //
  104. //
  105. //
  106. //
  107. //
  108. //
  109. //
  110. //
  111. //
  112. //
  113. //
  114. //
  115. //
  116. //
  117. //
  118. //
  119. //
  120. //
  121. //
  122. //
  123. //
  124. /* harmony default export */ var contractTemplate = ({
  125. name: "contractTemplate",
  126. data: function data() {
  127. return {};
  128. },
  129. components: {},
  130. props: {
  131. data: {
  132. type: Object,
  133. default: {}
  134. }
  135. },
  136. mounted: function mounted() {}
  137. });
  138. // CONCATENATED MODULE: ./node_modules/vue-loader/lib/template-compiler?{"id":"data-v-2f0d34eb","hasScoped":true,"transformToRequire":{"video":["src","poster"],"source":"src","img":"src","image":"xlink:href"},"buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/components/contractTemplate/contractTemplate.vue
  139. var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticStyle:{"font-family":"仿宋","width":"80%","margin":"0 auto","border":"1px solid #f2f3f5","padding":"20px","line-height":"2"},attrs:{"id":"question_doc"}},[_c('p',{staticStyle:{"margin-left":"4px","font-size":"30px","text-align":"center","line-height":"150%"}},[_vm._v("房屋租赁合同")]),_vm._v(" "),_vm._m(0),_vm._v(" "),_vm._m(1),_vm._v(" "),_vm._m(2),_vm._v(" "),_vm._m(3),_vm._v(" "),_c('p',{staticStyle:{"letter-spacing":"0","margin-top":"10px","font-size":"14px","line-height":"150%"}},[_c('span',{staticStyle:{"font-weight":"600"}},[_vm._v("乙方(承租方):")]),_vm._v(" "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("              "+_vm._s(_vm.data.name)+"                    ")])])]),_vm._v(" "),_c('p',{staticStyle:{"letter-spacing":"0","margin-top":"10px","font-size":"14px","line-height":"150%"}},[_c('span',{staticStyle:{"font-weight":"600"}},[_vm._v("身份证号码:")]),_vm._v(" "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("               "+_vm._s(_vm.data.number)+"                   ")])])]),_vm._v(" "),_c('p',{staticStyle:{"letter-spacing":"0","margin-top":"10px","font-size":"14px","line-height":"150%"}},[_c('span',{staticStyle:{"font-weight":"600"}},[_vm._v("联系电话:")]),_vm._v(" "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("                 "+_vm._s(_vm.data.phone)+"                 ")])])]),_vm._v(" "),_c('p',{staticStyle:{"margin-top":"40px","line-height":"1.5"}},[_vm._v("\n 据《民法典》及有关法律、法规的规定,甲方、乙方在平等、自愿的基础上,就房屋租赁有关事宜达成协议如下:\n ")]),_vm._v(" "),_c('p',{staticStyle:{"font-weight":"600","font-size":"16px"}},[_vm._v("第一条、房屋基本情况")]),_vm._v(" "),_vm._m(4),_vm._v(" "),_c('p',{staticStyle:{"text-indent":"20px"}},[_vm._v("2、乙方在此确认,其对所租赁的房屋性质以及其所享有的租赁空间已经有了充分的认识,并依据该协议约定接受该租赁房 屋状况并遵守相关房屋管理规定。")]),_vm._v(" "),_c('p',{staticStyle:{"font-weight":"600","font-size":"16px"}},[_vm._v("第二条 、房屋租赁期限")]),_vm._v(" "),_c('p',{staticStyle:{"text-indent":"20px"}},[_vm._v("1、房屋租赁期:自 "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("   "+_vm._s(_vm.data.signingTime)+" 至 "+_vm._s(_vm.data.contractTime)+"         ")]),_vm._v("止")]),_vm._v(",共 "),_vm._m(5),_vm._v("月。甲乙双方依据《房屋交割清单》完成房屋交验,乙\n 方 于本合同签订之日并办理完毕房屋租金、押金、其它费用(物业使用费、水费)支付及房屋验收、设施设备接收等手续后,且 甲方 向乙方交付租赁房屋钥匙或密码锁密码后,视为甲乙双方完成房屋的交付。")]),_vm._v(" "),_c('p',{staticStyle:{"font-weight":"600","font-size":"16px"}},[_vm._v("第三条 、房屋使用费用收取标准")]),_vm._v(" "),_c('p',{staticStyle:{"text-indent":"20px"}},[_vm._v("1、该房屋租金定价为人民币 "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("    "+_vm._s(_vm.data.rent)+"        ")])]),_vm._v(" 元/月,活动价(仅限本次签约周期)为 "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("     "+_vm._s(_vm.data.rent)+"      ")])]),_vm._v(" 元/月(人民币大写:     "+_vm._s(_vm.data.upperCase)),_c('u',[_vm._v("      ")]),_vm._v(")。房屋使用费到期前 10 天支付下一周期租金至甲方指定账户,乙方支付房租须在公众号中选择自助服务-在线支付,支付成功后,密码自动发送乙方。")]),_vm._v(" "),_vm._m(6),_vm._v(" "),_vm._m(7),_vm._v(" "),_vm._m(8),_vm._v(" "),_c('p',{staticStyle:{"text-indent":"20px"}},[_vm._v("5乙方退租且出租屋内电器设施等无人为
  140. var staticRenderFns = [function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('p',{staticStyle:{"letter-spacing":"0","font-size":"14px","line-height":"150%"}},[_c('span',{staticStyle:{"font-weight":"600"}},[_vm._v("合同编号:")]),_vm._v(" "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("                                  ")])])])},function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('p',{staticStyle:{"letter-spacing":"0","margin-top":"10px","font-size":"14px","line-height":"150%"}},[_c('span',{staticStyle:{"font-weight":"600"}},[_vm._v("甲方(出租方):")]),_vm._v(" "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("                                 ")])])])},function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('p',{staticStyle:{"letter-spacing":"0","margin-top":"10px","font-size":"14px","line-height":"150%"}},[_c('span',{staticStyle:{"font-weight":"600"}},[_vm._v("身份证号码:")]),_vm._v(" "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("                                 ")])])])},function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('p',{staticStyle:{"letter-spacing":"0","margin-top":"10px","font-size":"14px","line-height":"150%"}},[_c('span',{staticStyle:{"font-weight":"600"}},[_vm._v("联系电话:")]),_vm._v(" "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("                                 ")])])])},function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('p',{staticStyle:{"text-indent":"20px"}},[_vm._v("1、甲方将位于"),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("        ")])]),_vm._v("省"),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("        ")])]),_vm._v("市"),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("        ")])]),_vm._v("房屋的"),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("        ")])]),_vm._v("号房间出租予乙方。(以下简称该房屋)代房东转租给乙方使用,乙方仅对该房间内的特定空间享有专项租赁及使用权利,而对于该房屋除其他房间以外的公共空间,乙方仅享有共同使 用权利。\n ")])},function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("       ")]),_vm._v("个")])},function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('p',{staticStyle:{"text-indent":"20px"}},[_vm._v("2、服务管理费:"),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("           ")])]),_vm._v(" 个月,合计金额 "),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("           ")])]),_vm._v(" 元。 不足一月,按一月收取,违约不退。")])},function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('p',{staticStyle:{"text-indent":"20px"}},[_vm._v("3、该房屋押金为人民币"),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("           ")])]),_vm._v(" 元(人民币大写:"),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("           ")])]),_vm._v(" );")])},function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('p',{staticStyle:{"text-indent":"20px"}},[_vm._v("4、物业费:"),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("           ")])]),_vm._v(" 元/月。 总打款金额:"),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("           ")])]),_vm._v(" 一次性付款1个月,总金额:"),_c('span',{staticStyle:{"text-decoration":"underline"}},[_c('u',[_vm._v("           ")]
  141. var esExports = { render: render, staticRenderFns: staticRenderFns }
  142. /* harmony default export */ var contractTemplate_contractTemplate = (esExports);
  143. // CONCATENATED MODULE: ./src/components/contractTemplate/contractTemplate.vue
  144. function injectStyle (ssrContext) {
  145. __webpack_require__("SiUS")
  146. }
  147. var normalizeComponent = __webpack_require__("VU/8")
  148. /* script */
  149. /* template */
  150. /* template functional */
  151. var __vue_template_functional__ = false
  152. /* styles */
  153. var __vue_styles__ = injectStyle
  154. /* scopeId */
  155. var __vue_scopeId__ = "data-v-2f0d34eb"
  156. /* moduleIdentifier (server only) */
  157. var __vue_module_identifier__ = null
  158. var Component = normalizeComponent(
  159. contractTemplate,
  160. contractTemplate_contractTemplate,
  161. __vue_template_functional__,
  162. __vue_styles__,
  163. __vue_scopeId__,
  164. __vue_module_identifier__
  165. )
  166. /* harmony default export */ var components_contractTemplate_contractTemplate = __webpack_exports__["a"] = (Component.exports);
  167. /***/ }),
  168. /***/ "7qU6":
  169. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  170. "use strict";
  171. var validateIdent = {
  172. aIdentityCode_City: { // 城市代码列表
  173. 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林",
  174. 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西",
  175. 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南",
  176. 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃",
  177. 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 "
  178. },
  179. IdentityCode_isCardNo: function IdentityCode_isCardNo(card) {
  180. //检查号码是否符合规范,包括长度,类型
  181. var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/; //身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X
  182. if (reg.test(card) === false) {
  183. return false;
  184. }
  185. return true;
  186. },
  187. IdentityCode_checkProvince: function IdentityCode_checkProvince(card) {
  188. //取身份证前两位,校验省份
  189. var province = card.substr(0, 2);
  190. if (validateIdent.aIdentityCode_City[province] == undefined) {
  191. return false;
  192. }
  193. return true;
  194. },
  195. IdentityCode_checkBirthday: function IdentityCode_checkBirthday(card) {
  196. //检查生日是否正确,15位以'19'年份来进行补齐。
  197. var len = card.length;
  198. //身份证15位时,次序为省(3位)市(3位)年(2位)月(2位)日(2位)校验位(3位),皆为数字
  199. if (len == '15') {
  200. var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
  201. var arr_data = card.match(re_fifteen); // 正则取号码内所含出年月日数据
  202. var year = arr_data[2];
  203. var month = arr_data[3];
  204. var day = arr_data[4];
  205. var birthday = new Date('19' + year + '/' + month + '/' + day);
  206. return validateIdent.IdentityCode_verifyBirthday('19' + year, month, day, birthday);
  207. }
  208. //身份证18位时,次序为省(3位)市(3位)年(4位)月(2位)日(2位)校验位(4位),校验位末尾可能为X
  209. if (len == '18') {
  210. var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
  211. var arr_data = card.match(re_eighteen); // 正则取号码内所含出年月日数据
  212. var year = arr_data[2];
  213. var month = arr_data[3];
  214. var day = arr_data[4];
  215. var birthday = new Date(year + '/' + month + '/' + day);
  216. return validateIdent.IdentityCode_verifyBirthday(year, month, day, birthday);
  217. }
  218. return false;
  219. },
  220. IdentityCode_verifyBirthday: function IdentityCode_verifyBirthday(year, month, day, birthday) {
  221. //校验日期 ,15位以'19'年份来进行补齐。
  222. var now = new Date();
  223. var now_year = now.getFullYear();
  224. //年月日是否合理
  225. if (birthday.getFullYear() == year && birthday.getMonth() + 1 == month && birthday.getDate() == day) {
  226. //判断年份的范围(3岁到150岁之间)
  227. var time = now_year - year;
  228. if (time >= 3 && time <= 150) {
  229. return true;
  230. }
  231. return false;
  232. }
  233. return false;
  234. },
  235. IdentityCode_checkParity: function IdentityCode_checkParity(card) {
  236. //校验位的检测
  237. card = validateIdent.IdentityCode_changeFivteenToEighteen(card); // 15位转18位
  238. var len = card.length;
  239. if (len == '18') {
  240. var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
  241. var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
  242. var cardTemp = 0,
  243. i,
  244. valnum;
  245. for (i = 0; i < 17; i++) {
  246. cardTemp += card.substr(i, 1) * arrInt[i];
  247. }
  248. valnum = arrCh[cardTemp % 11];
  249. if (valnum == card.substr(17, 1)) {
  250. return true;
  251. }
  252. return false;
  253. }
  254. return false;
  255. },
  256. IdentityCode_changeFivteenToEighteen: function IdentityCode_changeFivteenToEighteen(card) {
  257. //15位转18位身份证号
  258. if (card.length == '15') {
  259. var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
  260. var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
  261. var cardTemp = 0,
  262. i;
  263. card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
  264. for (i = 0; i < 17; i++) {
  265. cardTemp += card.substr(i, 1) * arrInt[i];
  266. }
  267. card += arrCh[cardTemp % 11];
  268. return card;
  269. }
  270. return card;
  271. },
  272. IdentityCodeValid: function IdentityCodeValid(card) {
  273. // 身份证号码检验主入口
  274. var pass = true;
  275. var sex = '';
  276. //是否为空
  277. if (pass && card === '') pass = false;
  278. //校验长度,类型
  279. if (pass && validateIdent.IdentityCode_isCardNo(card) === false) pass = false;
  280. //检查省份
  281. if (pass && validateIdent.IdentityCode_checkProvince(card) === false) pass = false;
  282. //校验生日
  283. if (pass && validateIdent.IdentityCode_checkBirthday(card) === false) pass = false;
  284. //检验位的检测
  285. if (pass && validateIdent.IdentityCode_checkParity(card) === false) pass = false;
  286. if (pass) {
  287. var iCard = validateIdent.IdentityCode_changeFivteenToEighteen(card);
  288. if (parseInt(iCard.charAt(16)) % 2 == 0) {
  289. sex = "0"; // 女生
  290. } else {
  291. sex = "1"; // 男生
  292. }
  293. return true;
  294. } else {
  295. return false;
  296. }
  297. }
  298. };
  299. /* harmony default export */ __webpack_exports__["a"] = (validateIdent.IdentityCodeValid); //导出
  300. /***/ }),
  301. /***/ "BR/S":
  302. /***/ (function(module, exports) {
  303. // removed by extract-text-webpack-plugin
  304. /***/ }),
  305. /***/ "CQIJ":
  306. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  307. "use strict";
  308. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  309. // EXTERNAL MODULE: ./node_modules/babel-runtime/core-js/promise.js
  310. var promise = __webpack_require__("//Fk");
  311. var promise_default = /*#__PURE__*/__webpack_require__.n(promise);
  312. // EXTERNAL MODULE: ./node_modules/babel-runtime/regenerator/index.js
  313. var regenerator = __webpack_require__("Xxa5");
  314. var regenerator_default = /*#__PURE__*/__webpack_require__.n(regenerator);
  315. // EXTERNAL MODULE: ./node_modules/babel-runtime/helpers/asyncToGenerator.js
  316. var asyncToGenerator = __webpack_require__("exGp");
  317. var asyncToGenerator_default = /*#__PURE__*/__webpack_require__.n(asyncToGenerator);
  318. // EXTERNAL MODULE: ./node_modules/babel-runtime/core-js/json/stringify.js
  319. var stringify = __webpack_require__("mvHQ");
  320. var stringify_default = /*#__PURE__*/__webpack_require__.n(stringify);
  321. // EXTERNAL MODULE: ./node_modules/babel-runtime/helpers/toConsumableArray.js
  322. var toConsumableArray = __webpack_require__("Gu7T");
  323. var toConsumableArray_default = /*#__PURE__*/__webpack_require__.n(toConsumableArray);
  324. // EXTERNAL MODULE: ./src/api/index.js + 5 modules
  325. var api = __webpack_require__("gyMJ");
  326. // EXTERNAL MODULE: ./src/utils/index.js
  327. var utils = __webpack_require__("0xDb");
  328. // EXTERNAL MODULE: ./src/utils/util.js
  329. var util = __webpack_require__("oFuF");
  330. // EXTERNAL MODULE: ./src/utils/verification.js
  331. var verification = __webpack_require__("7qU6");
  332. // EXTERNAL MODULE: ./src/api/allFun.js
  333. var allFun = __webpack_require__("mprh");
  334. // EXTERNAL MODULE: ./src/utils/equipment.js
  335. var equipment = __webpack_require__("ObZk");
  336. // EXTERNAL MODULE: ./node_modules/moment/moment.js
  337. var moment = __webpack_require__("PJh5");
  338. var moment_default = /*#__PURE__*/__webpack_require__.n(moment);
  339. // EXTERNAL MODULE: ./src/components/visualizcomponent/NumberGrow.vue + 2 modules
  340. var NumberGrow = __webpack_require__("eVaK");
  341. // EXTERNAL MODULE: ./src/components/contractTemplate/contractTemplate.vue + 2 modules
  342. var contractTemplate = __webpack_require__("+php");
  343. // EXTERNAL MODULE: ./node_modules/file-saver/dist/FileSaver.min.js
  344. var FileSaver_min = __webpack_require__("t4zo");
  345. var FileSaver_min_default = /*#__PURE__*/__webpack_require__.n(FileSaver_min);
  346. // EXTERNAL MODULE: ./node_modules/html-docx-js/dist/html-docx.js
  347. var html_docx = __webpack_require__("U3YJ");
  348. var html_docx_default = /*#__PURE__*/__webpack_require__.n(html_docx);
  349. // CONCATENATED MODULE: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/views/agreement.vue
  350. //
  351. //
  352. //
  353. //
  354. //
  355. //
  356. //
  357. //
  358. //
  359. //
  360. //
  361. //
  362. //
  363. //
  364. //
  365. //
  366. //
  367. //
  368. //
  369. //
  370. //
  371. //
  372. //
  373. //
  374. //
  375. //
  376. //
  377. //
  378. //
  379. //
  380. //
  381. //
  382. //
  383. //
  384. //
  385. //
  386. //
  387. //
  388. //
  389. //
  390. //
  391. //
  392. //
  393. //
  394. //
  395. //
  396. //
  397. //
  398. //
  399. //
  400. //
  401. //
  402. //
  403. //
  404. //
  405. //
  406. //
  407. //
  408. //
  409. //
  410. //
  411. //
  412. //
  413. //
  414. //
  415. //
  416. //
  417. //
  418. //
  419. //
  420. //
  421. //
  422. //
  423. //
  424. //
  425. //
  426. //
  427. //
  428. //
  429. //
  430. //
  431. //
  432. //
  433. //
  434. //
  435. //
  436. //
  437. //
  438. //
  439. //
  440. //
  441. //
  442. //
  443. //
  444. //
  445. //
  446. //
  447. //
  448. //
  449. //
  450. //
  451. //
  452. //
  453. //
  454. //
  455. //
  456. //
  457. //
  458. //
  459. //
  460. //
  461. //
  462. //
  463. //
  464. //
  465. //
  466. //
  467. //
  468. //
  469. //
  470. //
  471. //
  472. //
  473. //
  474. //
  475. //
  476. //
  477. //
  478. //
  479. //
  480. //
  481. //
  482. //
  483. //
  484. //
  485. //
  486. //
  487. //
  488. //
  489. //
  490. //
  491. //
  492. //
  493. //
  494. //
  495. //
  496. //
  497. //
  498. //
  499. //
  500. //
  501. //
  502. //
  503. //
  504. //
  505. //
  506. //
  507. //
  508. //
  509. //
  510. //
  511. //
  512. //
  513. //
  514. //
  515. //
  516. //
  517. //
  518. //
  519. //
  520. //
  521. //
  522. //
  523. //
  524. //
  525. //
  526. //
  527. //
  528. //
  529. //
  530. //
  531. //
  532. //
  533. //
  534. //
  535. //
  536. //
  537. //
  538. //
  539. //
  540. //
  541. //
  542. //
  543. //
  544. //
  545. //
  546. //
  547. //
  548. //
  549. //
  550. //
  551. //
  552. //
  553. //
  554. //
  555. //
  556. //
  557. //
  558. //
  559. //
  560. //
  561. //
  562. //
  563. //
  564. //
  565. //
  566. //
  567. //
  568. //
  569. //
  570. //
  571. //
  572. //
  573. //
  574. //
  575. //
  576. //
  577. //
  578. //
  579. //
  580. //
  581. //
  582. //
  583. //
  584. //
  585. //
  586. //
  587. //
  588. //
  589. //
  590. //
  591. //
  592. //
  593. //
  594. //
  595. //
  596. //
  597. //
  598. //
  599. //
  600. //
  601. //
  602. //
  603. //
  604. //
  605. //
  606. //
  607. //
  608. //
  609. //
  610. //
  611. //
  612. //
  613. //
  614. //
  615. //
  616. //
  617. //
  618. //
  619. //
  620. //
  621. //
  622. //
  623. //
  624. //
  625. //
  626. //
  627. //
  628. //
  629. //
  630. //
  631. //
  632. //
  633. //
  634. //
  635. //
  636. //
  637. //
  638. //
  639. //
  640. //
  641. //
  642. //
  643. //
  644. //
  645. //
  646. //
  647. //
  648. //
  649. //
  650. //
  651. //
  652. //
  653. //
  654. //
  655. //
  656. //
  657. //
  658. //
  659. //
  660. //
  661. //
  662. //
  663. //
  664. //
  665. //
  666. //
  667. //
  668. //
  669. //
  670. //
  671. //
  672. //
  673. //
  674. //
  675. //
  676. //
  677. //
  678. //
  679. //
  680. //
  681. //
  682. //
  683. //
  684. //
  685. //
  686. //
  687. //
  688. //
  689. //
  690. //
  691. //
  692. //
  693. //
  694. //
  695. //
  696. //
  697. //
  698. //
  699. //
  700. //
  701. //
  702. //
  703. //
  704. //
  705. //
  706. //
  707. //
  708. //
  709. //
  710. //
  711. //
  712. //
  713. //
  714. //
  715. //
  716. //
  717. //
  718. //
  719. //
  720. //
  721. //
  722. //
  723. //
  724. //
  725. //
  726. //
  727. //
  728. //
  729. //
  730. //
  731. //
  732. //
  733. //
  734. //
  735. //
  736. //
  737. //
  738. //
  739. //
  740. //
  741. //
  742. //
  743. //
  744. //
  745. //
  746. //
  747. //
  748. //
  749. //
  750. //
  751. //
  752. //
  753. //
  754. //
  755. //
  756. //
  757. //
  758. //
  759. //
  760. //
  761. //
  762. //
  763. //
  764. //
  765. //
  766. //
  767. //
  768. //
  769. //
  770. //
  771. //
  772. //
  773. //
  774. //
  775. //
  776. //
  777. //
  778. //
  779. //
  780. //
  781. //
  782. //
  783. //
  784. //
  785. //
  786. //
  787. //
  788. //
  789. //
  790. //
  791. //
  792. //
  793. //
  794. //
  795. //
  796. //
  797. //
  798. //
  799. //
  800. //
  801. //
  802. //
  803. //
  804. //
  805. //
  806. /* harmony default export */ var agreement = ({
  807. name: "agreement",
  808. data: function data() {
  809. return {
  810. roomlistZNodes: [],
  811. contractStatus: {
  812. total: 0,
  813. signed: 0,
  814. expired: 0,
  815. arrears: 0,
  816. toBeSigned: 0
  817. },
  818. dialogVisibleExport: false,
  819. exportRow: {},
  820. pickerOptions: {
  821. shortcuts: [{
  822. text: '最近一周',
  823. onClick: function onClick(picker) {
  824. var end = new Date();
  825. var start = new Date();
  826. start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
  827. picker.$emit('pick', [start, end]);
  828. }
  829. }, {
  830. text: '最近一个月',
  831. onClick: function onClick(picker) {
  832. var end = new Date();
  833. var start = new Date();
  834. start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
  835. picker.$emit('pick', [start, end]);
  836. }
  837. }, {
  838. text: '最近三个月',
  839. onClick: function onClick(picker) {
  840. var end = new Date();
  841. var start = new Date();
  842. start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
  843. picker.$emit('pick', [start, end]);
  844. }
  845. }]
  846. },
  847. sendTemporaryPasswordStatus: '否',
  848. multipleSelection: [],
  849. modifyIndex: '',
  850. updateDialogStatus: false,
  851. updateAgreementRow: {},
  852. activeNames: '1',
  853. payOptions: [{ label: '现金', value: 1 }, { label: '刷卡', value: 2 }, { label: '支付宝', value: 3 }, { label: '微信', value: 4 }],
  854. roomList: [],
  855. tableDataRom: [],
  856. subsidyOptions: [{ label: '一次性补贴', value: 1 }, { label: '按月补贴', value: 2 }, { label: '一次性补贴+按月基本补贴', value: 3 }],
  857. tenantOptions: [{ label: '中国大陆', value: 1 }, { label: '港澳台同胞', value: 2 }, { label: '国际友人', value: 3 }],
  858. IdCardOptions: [{ label: '身份证', value: 1 }, { label: '护照', value: 2 }],
  859. sexOptions: [{ label: '男', value: 1 }, { label: '女', value: 2 }],
  860. tableList: [],
  861. search: {
  862. name: '',
  863. phone: '',
  864. status: '',
  865. signingTime: '',
  866. contractTime: '',
  867. roomName: '',
  868. minRent: '',
  869. maxRent: '',
  870. siteIds: ''
  871. },
  872. form: {
  873. tenant: [{
  874. id: '',
  875. name: '',
  876. phone: '',
  877. number: '',
  878. cardType: 1,
  879. sex: '',
  880. place: '',
  881. address: '',
  882. tenantType: '',
  883. subsidy: '',
  884. userTelephone: '',
  885. userPassword: '',
  886. userId: '',
  887. keyId: ''
  888. }],
  889. manufactureId: '',
  890. rent: '',
  891. pay: '',
  892. id: '',
  893. signingTime: '',
  894. contractTime: '',
  895. dueDate: '',
  896. remark: '',
  897. roomId: '',
  898. roomName: '',
  899. deviceNum: '',
  900. imei: '',
  901. roomNum: '',
  902. roomNameSearch: '',
  903. acreage: '',
  904. layout: ''
  905. },
  906. dialogVisible: false,
  907. checkNodeId: '',
  908. pageNum: 1,
  909. pageSize: 10,
  910. pageTotal: 0,
  911. leasesId: '',
  912. paginationConfig: 'total, sizes, prev, pager, next, jumper'
  913. };
  914. },
  915. components: {
  916. NumberGrow: NumberGrow["a" /* default */], contractTemplate: contractTemplate["a" /* default */]
  917. },
  918. created: function created() {
  919. if (this.$route.params.status) {
  920. this.search.status = this.$route.params.status;
  921. }
  922. this.getLeasesList();
  923. this.getLeasesStatus();
  924. if (document.documentElement.clientWidth < 1080) {
  925. this.paginationConfig = 'total, prev, pager, next';
  926. } else {
  927. this.paginationConfig = 'total, sizes, prev, pager, next, jumper';
  928. }
  929. },
  930. mounted: function mounted() {
  931. document.addEventListener('keydown', this.keyDown);
  932. this.getAllTree();
  933. },
  934. methods: {
  935. checkNodeSearch: function checkNodeSearch(e) {
  936. var selectRow = [];
  937. console.log(e);
  938. e.map(function (li) {
  939. selectRow.push.apply(selectRow, toConsumableArray_default()(li));
  940. });
  941. console.log(selectRow);
  942. this.search.siteIds = stringify_default()(selectRow);
  943. // this.bindSelectedList = selectRow
  944. },
  945. // 导出合同
  946. exportHtmlWord: function exportHtmlWord(index, row) {
  947. row.signingTime = moment_default()(row.signingTime).format('YYYY-MM-DD');
  948. row.contractTime = moment_default()(row.contractTime).format('YYYY-MM-DD');
  949. row['upperCase'] = Object(utils["l" /* smallToBig */])(row.rent);
  950. this.exportRow = row;
  951. this.dialogVisibleExport = true;
  952. },
  953. exportWord: function exportWord() {
  954. var arr = document.querySelector('#question_doc'); //获取dom
  955. var html = arr.innerHTML; //获取html的内容
  956. var htmlStr = "\n <!DOCTYPE html>\n <html lang=\"en\">\n <body style=\"font-family:\u65B9\u6B63\u4EFF\u5B8B_GBK;mso-ascii-font-family:'Times New Roman';\">\n " + html + "\n </body>\n </html>"; //把获取到的html放入到原生的html中
  957. Object(FileSaver_min["saveAs"])(html_docx_default.a.asBlob(htmlStr, { orientation: 'landscape' }), '房屋租赁合同.doc'); // 导出为word
  958. },
  959. keyDown: function keyDown(e) {
  960. //如果是回车则执行登录方法
  961. if (e.keyCode == 13) {
  962. if (this.$route.name == 'Login') {
  963. this.handleSearch();
  964. }
  965. }
  966. },
  967. // 选择搜索人员
  968. handleSelectPerson: function handleSelectPerson(index, item) {
  969. var personInfo = JSON.parse(item.info);
  970. this.form.tenant[index].id = item.id;
  971. this.form.tenant[index].phone = item.phone;
  972. this.form.tenant[index].number = item.number;
  973. this.form.tenant[index].sex = item.sex;
  974. this.form.tenant[index].name = item.name;
  975. this.form.tenant[index].userTelephone = personInfo.userTelephone;
  976. this.form.tenant[index].userPassword = personInfo.userPassword;
  977. this.form.tenant[index].userId = personInfo.userId;
  978. this.form.tenant[index].keyId = personInfo.keyId;
  979. },
  980. // 获取人员
  981. querySearchAsync: function querySearchAsync(queryString, cb) {
  982. var _this2 = this;
  983. var q = {
  984. name: queryString
  985. };
  986. var data = {
  987. pageSize: 10,
  988. pageNum: 1,
  989. q: stringify_default()(q)
  990. };
  991. var personInfo = [];
  992. this.loading = true;
  993. Object(api["g" /* httpPost */])(data, this.$api.getlistNum).then(function (res) {
  994. personInfo = res.data.list;
  995. var restaurants = res.data.list;
  996. var results = queryString ? restaurants.filter(_this2.createFilter(queryString)) : restaurants;
  997. cb(results);
  998. });
  999. },
  1000. createFilter: function createFilter(queryString) {
  1001. return function (restaurant) {
  1002. return restaurant.name.indexOf(queryString) === 0;
  1003. };
  1004. },
  1005. // 同步合约状态
  1006. syncContractStatusMethods: function syncContractStatusMethods() {
  1007. var _this3 = this;
  1008. Object(api["d" /* httpGet */])('', '/v1/leases/auto/UpdatePayment').then(function (res2) {});
  1009. Object(api["d" /* httpGet */])('', this.$api.getAutoRetreat).then(function (res) {
  1010. if (res.success) {
  1011. _this3.$message.success('同步成功');
  1012. _this3.getLeasesList();
  1013. _this3.getLeasesStatus();
  1014. } else {
  1015. _this3.$message.error('同步失败');
  1016. }
  1017. });
  1018. },
  1019. // 确认修改备注
  1020. confirmRemark: function confirmRemark(index, row) {
  1021. var _this4 = this;
  1022. var list = [{
  1023. id: row.id,
  1024. remark: row.remark
  1025. }];
  1026. Object(api["g" /* httpPost */])(list, this.$api.postUpdateLeases).then(function (res) {
  1027. if (res.success) {
  1028. _this4.$message.success('更新成功');
  1029. _this4.modifyIndex = '';
  1030. _this4.getLeasesList();
  1031. } else {
  1032. _this4.$message.error(res.message);
  1033. }
  1034. });
  1035. },
  1036. // 修改备注
  1037. setRemark: function setRemark(index, row) {
  1038. if (this.modifyIndex === '') {
  1039. this.modifyIndex = index;
  1040. } else {
  1041. this.modifyIndex = '';
  1042. }
  1043. },
  1044. // 确认是否有重复人员签约合同
  1045. setLeasesMethods: function setLeasesMethods(cardId, callback) {
  1046. var _this5 = this;
  1047. return asyncToGenerator_default()( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
  1048. var QData, data;
  1049. return regenerator_default.a.wrap(function _callee$(_context) {
  1050. while (1) {
  1051. switch (_context.prev = _context.next) {
  1052. case 0:
  1053. QData = util["a" /* default */].validObject({
  1054. phone: cardId
  1055. });
  1056. data = {
  1057. pageNum: _this5.pageNum,
  1058. pageSize: _this5.pageSize,
  1059. orderBy: "create_time desc",
  1060. q: stringify_default()(QData)
  1061. };
  1062. if (data.q == '{}') {
  1063. delete data.q;
  1064. }
  1065. Object(api["g" /* httpPost */])(data, _this5.$api.postLeasesList).then(function (res) {
  1066. if (res.success) {
  1067. var list = [];
  1068. res.data.list.map(function (li) {
  1069. if (li.status == 1 || li.status == 2) {
  1070. list.push(li);
  1071. }
  1072. });
  1073. if (list.length > 0) {
  1074. callback(false);
  1075. } else {
  1076. callback(true);
  1077. }
  1078. } else {
  1079. callback(false);
  1080. }
  1081. });
  1082. case 4:
  1083. case "end":
  1084. return _context.stop();
  1085. }
  1086. }
  1087. }, _callee, _this5);
  1088. }))();
  1089. },
  1090. // 获取合同列表
  1091. getLeasesList: function getLeasesList() {
  1092. var _this6 = this;
  1093. var QData = util["a" /* default */].validObject({
  1094. phone: this.search.phone,
  1095. name: this.search.name,
  1096. status: this.search.status,
  1097. signingTime: this.search.signingTime,
  1098. contractTime: this.search.contractTime,
  1099. siteIds: this.search.siteIds
  1100. });
  1101. var data = {
  1102. pageNum: this.pageNum,
  1103. pageSize: this.pageSize,
  1104. orderBy: "create_time desc",
  1105. q: stringify_default()(QData)
  1106. };
  1107. if (data.q == '{}') {
  1108. delete data.q;
  1109. }
  1110. Object(api["g" /* httpPost */])(data, this.$api.postLeasesList).then(function (res) {
  1111. if (res.success) {
  1112. res.data.list.map(function (li) {
  1113. li.signingTime = moment_default()(li.signingTime).format('YYYY-MM-DD HH:mm:ss');
  1114. li.contractTime = moment_default()(li.contractTime).format('YYYY-MM-DD HH:mm:ss');
  1115. li.createTime = moment_default()(li.createTime).format('YYYY-MM-DD HH:mm:ss');
  1116. // li.monthRent = JSON.parse(li.expand).rent || 0
  1117. });
  1118. _this6.tableList = res.data.list;
  1119. _this6.pageTotal = res.data.total;
  1120. _this6.contractStatus.total = res.data.total;
  1121. } else {
  1122. _this6.$message.error(res.message);
  1123. }
  1124. });
  1125. },
  1126. // 获取合约状态统计
  1127. getLeasesStatus: function getLeasesStatus() {
  1128. var _this7 = this;
  1129. Object(api["d" /* httpGet */])('', this.$api.getLeasesStatusstatistics).then(function (res) {
  1130. if (res.success) {
  1131. var list = res.data;
  1132. var contractStatus = {
  1133. total: 0,
  1134. signed: 0,
  1135. expired: 0,
  1136. arrears: 0,
  1137. toBeSigned: 0
  1138. };
  1139. list.map(function (li) {
  1140. if (li.value === 0) {
  1141. li.lable = '待签约';
  1142. contractStatus.toBeSigned += li.total;
  1143. } else if (li.value === 1) {
  1144. li.lable = '已签约';
  1145. contractStatus.signed += li.total;
  1146. } else if (li.value === 2) {
  1147. li.lable = '已欠费';
  1148. contractStatus.arrears += li.total;
  1149. } else if (li.value === 3) {
  1150. li.lable = '已退租';
  1151. contractStatus.expired += li.total;
  1152. }
  1153. });
  1154. _this7.contractStatus = contractStatus;
  1155. }
  1156. });
  1157. },
  1158. // 删除合约
  1159. deleteAgreement: function deleteAgreement(index, row) {
  1160. var _this8 = this;
  1161. this.$confirm("是否先进行删除操作?", "提示", {
  1162. type: "warning"
  1163. }).then(function () {
  1164. var data = {
  1165. ids: [row.id]
  1166. };
  1167. Object(api["g" /* httpPost */])(data, _this8.$api.postDeleteLeases).then(function (res) {
  1168. if (res.success) {
  1169. _this8.$message.success('删除成功');
  1170. _this8.getLeasesList();
  1171. _this8.getLeasesStatus();
  1172. } else {
  1173. _this8.$message.error(res.message);
  1174. }
  1175. });
  1176. });
  1177. },
  1178. // 更新合约内容
  1179. updateAgreement: function updateAgreement(index, row) {
  1180. this.updateAgreementRow = row;
  1181. this.updateDialogStatus = true;
  1182. },
  1183. // 签约
  1184. signAContract: function signAContract() {
  1185. var _this9 = this;
  1186. return asyncToGenerator_default()( /*#__PURE__*/regenerator_default.a.mark(function _callee3() {
  1187. var info, formData;
  1188. return regenerator_default.a.wrap(function _callee3$(_context3) {
  1189. while (1) {
  1190. switch (_context3.prev = _context3.next) {
  1191. case 0:
  1192. info = JSON.parse(localStorage.getItem('info'));
  1193. formData = _this9.form;
  1194. _context3.next = 4;
  1195. return _this9.setLeasesMethods(formData.tenant[0].phone, function (callback) {
  1196. console.log(_this9, callback);
  1197. if (callback) {
  1198. if (formData.pay === '') {
  1199. _this9.$message.error('请选择支付方式');
  1200. } else if (formData.id === '') {
  1201. _this9.$message.error('请输入合同编号');
  1202. } else if (formData.dueDate === '') {
  1203. _this9.$message.error('请选择缴费时间');
  1204. } else if (formData.signingTime === '') {
  1205. _this9.$message.error('请选择签约时间');
  1206. } else if (formData.contractTime === '') {
  1207. _this9.$message.error('请选择有效期');
  1208. } else if (formData.tenant[0].phone === '' || formData.tenant[0].name === '') {
  1209. _this9.$message.error('请选择人员');
  1210. } else if (formData.deviceNum === '' || formData.roomName === '') {
  1211. _this9.$message.error('请选择房间');
  1212. } else {
  1213. var dueDate = formData.dueDate.getDate();
  1214. console.log(dueDate);
  1215. var leasesData = {
  1216. papersType: formData.tenant[0].cardType,
  1217. place: formData.tenant[0].place,
  1218. number: formData.id,
  1219. sex: formData.tenant[0].sex,
  1220. phone: formData.tenant[0].phone,
  1221. name: formData.tenant[0].name,
  1222. mailing: formData.tenant[0].address,
  1223. leasesType: formData.tenant[0].tenantType,
  1224. subsidyStandards: formData.tenant[0].subsidy,
  1225. payStandards: formData.pay,
  1226. signingTime: formData.signingTime,
  1227. contractTime: formData.contractTime,
  1228. cutoffTime: formData.contractTime,
  1229. dueDate: formData.dueDate,
  1230. remark: formData.remark,
  1231. enterpriseId: info.enterpriseId,
  1232. siteId: formData.roomId,
  1233. cardId: formData.tenant[0].id,
  1234. address: formData.roomName,
  1235. status: 1,
  1236. monthRent: formData.rent,
  1237. expand: stringify_default()({
  1238. rent: formData.rent,
  1239. dueDay: dueDate - 5
  1240. }) //扩展属性
  1241. };
  1242. Object(api["g" /* httpPost */])(leasesData, _this9.$api.postAddLeases).then(function (res) {
  1243. if (res.success) {
  1244. _this9.$message.success('签约成功');
  1245. var data3 = {
  1246. code: "zg/getEmergence",
  1247. data: {
  1248. lockerId: _this9.form.deviceNum
  1249. }
  1250. };
  1251. Object(api["g" /* httpPost */])(data3, _this9.$api.sendCommand).then(function (res4) {
  1252. var sendSData = {
  1253. name: formData.tenant[0].name,
  1254. address: formData.roomName,
  1255. number: formData.id,
  1256. date: dueDate,
  1257. total: formData.rent,
  1258. phone: formData.tenant[0].phone,
  1259. enterpriseId: info.enterpriseId,
  1260. password: res4.data.data
  1261. };
  1262. Object(api["g" /* httpPost */])(sendSData, _this9.$api.sendSigningNotice).then(function (res) {
  1263. if (res.success) {
  1264. _this9.$message.success("通知成功");
  1265. } else {
  1266. _this9.$message.error("通知失败");
  1267. }
  1268. });
  1269. });
  1270. _this9.getLeasesList();
  1271. _this9.getLeasesStatus();
  1272. _this9.leasesId = res.data;
  1273. formData.tenant.map(function () {
  1274. var _ref = asyncToGenerator_default()( /*#__PURE__*/regenerator_default.a.mark(function _callee2(li, index) {
  1275. return regenerator_default.a.wrap(function _callee2$(_context2) {
  1276. while (1) {
  1277. switch (_context2.prev = _context2.next) {
  1278. case 0:
  1279. if (!(li.id === '')) {
  1280. _context2.next = 5;
  1281. break;
  1282. }
  1283. _context2.next = 3;
  1284. return _this9.addPeopleMethods(li, index);
  1285. case 3:
  1286. _context2.next = 7;
  1287. break;
  1288. case 5:
  1289. _context2.next = 7;
  1290. return _this9.bindCheckIn(li, index);
  1291. case 7:
  1292. case "end":
  1293. return _context2.stop();
  1294. }
  1295. }
  1296. }, _callee2, _this9);
  1297. }));
  1298. return function (_x, _x2) {
  1299. return _ref.apply(this, arguments);
  1300. };
  1301. }());
  1302. _this9.dialogVisible = false;
  1303. } else {
  1304. _this9.$message.error(res.message);
  1305. _this9.dialogVisible = false;
  1306. }
  1307. });
  1308. }
  1309. } else {
  1310. _this9.$message.error('该人员已有合约,请重新选择');
  1311. }
  1312. });
  1313. case 4:
  1314. case "end":
  1315. return _context3.stop();
  1316. }
  1317. }
  1318. }, _callee3, _this9);
  1319. }))();
  1320. },
  1321. // 绑定入住
  1322. bindCheckIn: function bindCheckIn(li, index) {
  1323. var _this10 = this;
  1324. if (this.form.manufactureId === 201 || this.form.manufactureId === 221) {
  1325. equipment["a" /* default */].addUserToLock(this.form.deviceNum, this.form.imei, li.userPassword, '0', '1', '6226', li.name, this.form.roomName, function (callback) {
  1326. if (callback.success) {
  1327. var data = [{
  1328. cardId: li.id,
  1329. siteId: _this10.form.roomId,
  1330. startTime: _this10.form.signingTime,
  1331. endTime: _this10.form.contractTime
  1332. }];
  1333. Object(api["g" /* httpPost */])(data, _this10.$api.bindCard).then(function (res1) {});
  1334. var userStr = {
  1335. lockerId: _this10.form.deviceNum,
  1336. imei: _this10.form.imei,
  1337. lockerUserId: li.userPassword,
  1338. keyId: li.userPassword,
  1339. userTelephone: li.userTelephone,
  1340. userPassword: li.userPassword,
  1341. role: 0,
  1342. action: 1,
  1343. order: 6226,
  1344. cardName: li.name,
  1345. roomName: _this10.form.roomName
  1346. };
  1347. var lockUserData = {
  1348. deviceNum: _this10.form.deviceNum,
  1349. imei: _this10.form.imei,
  1350. cardId: li.id,
  1351. content: stringify_default()(userStr),
  1352. type: 26,
  1353. serial: callback.data.serialNumber,
  1354. startTime: _this10.form.signingTime.getTime() / 1000,
  1355. endTime: _this10.form.contractTime.getTime() / 1000
  1356. };
  1357. util["a" /* default */].sendLockUser(lockUserData, function (callbackLOCK) {});
  1358. // if(index === this.form.tenant.length-1){
  1359. // let data3 = {
  1360. // code: "zg/getEmergence",
  1361. // data: {
  1362. // lockerId:this.form.deviceNum,
  1363. // },
  1364. // };
  1365. // httpPost(data3, this.$api.sendCommand).then((res4) => {
  1366. // if(res4.success){
  1367. // this.$alert(`${res4.data.data}该密码仅在今天可以使用一次`, '临时密码', {
  1368. // confirmButtonText: '确定',
  1369. // callback: action => {
  1370. //
  1371. // }
  1372. // })
  1373. // }else {
  1374. // this.$message.error("获取临时密码失败")
  1375. // }
  1376. // })
  1377. // }
  1378. } else {
  1379. _this10.$message.error(callback.msg);
  1380. }
  1381. });
  1382. } else if (this.form.manufactureId === 101) {
  1383. var passWordStartTime = moment_default()(this.form.signingTime).format("YYYYMMDDHHmmss");
  1384. var passWordEndTime = moment_default()(this.form.contractTime).format("YYYYMMDDHHmmss");
  1385. equipment["a" /* default */].LDAddUser(this.form.deviceNum, this.form.imei, li.userTelephone, li.userPassword, li.userPassword, passWordStartTime, passWordEndTime, 26, 6226, li.name, this.form.roomName, false, function (callback) {
  1386. if (callback.success) {
  1387. var data = [{
  1388. cardId: li.id,
  1389. siteId: _this10.form.roomId,
  1390. startTime: _this10.form.signingTime,
  1391. endTime: _this10.form.contractTime
  1392. }];
  1393. Object(api["g" /* httpPost */])(data, _this10.$api.bindCard).then(function (res1) {});
  1394. var userStr = {
  1395. lockerId: _this10.form.deviceNum,
  1396. imei: _this10.form.imei,
  1397. lockerUserId: li.userPassword,
  1398. keyId: li.userPassword,
  1399. userTelephone: li.userTelephone,
  1400. userPassword: li.userPassword,
  1401. role: 0,
  1402. action: 1,
  1403. order: 6226,
  1404. cardName: li.name,
  1405. roomName: _this10.form.roomName
  1406. };
  1407. var lockUserData = {
  1408. deviceNum: _this10.form.deviceNum,
  1409. imei: _this10.form.imei,
  1410. cardId: li.id,
  1411. content: stringify_default()(userStr),
  1412. type: 26,
  1413. serial: callback.data.serialNumber,
  1414. startTime: _this10.form.signingTime.getTime() / 1000,
  1415. endTime: _this10.form.contractTime.getTime() / 1000
  1416. };
  1417. util["a" /* default */].sendLockUser(lockUserData, function (callbackLOCK) {});
  1418. } else {
  1419. _this10.$message.error(callback.msg);
  1420. }
  1421. });
  1422. }
  1423. },
  1424. // 添加新人员
  1425. addPeopleMethods: function addPeopleMethods(item, index) {
  1426. var _this11 = this;
  1427. return asyncToGenerator_default()( /*#__PURE__*/regenerator_default.a.mark(function _callee4() {
  1428. var info, infoStr, data;
  1429. return regenerator_default.a.wrap(function _callee4$(_context4) {
  1430. while (1) {
  1431. switch (_context4.prev = _context4.next) {
  1432. case 0:
  1433. info = JSON.parse(localStorage.getItem('info'));
  1434. infoStr = {
  1435. userTelephone: item.phone,
  1436. userPassword: item.phone.substring(item.phone.length - 6, item.phone.length),
  1437. userId: item.phone.substring(item.phone.length - 6, item.phone.length),
  1438. keyId: item.phone.substring(item.phone.length - 6, item.phone.length)
  1439. };
  1440. data = {
  1441. cardId: '',
  1442. cardState: 1,
  1443. info: stringify_default()(infoStr),
  1444. name: item.name,
  1445. number: item.number,
  1446. phone: item.phone,
  1447. sex: parseInt(item.sex),
  1448. enterpriseId: info.enterpriseId,
  1449. type: 0
  1450. };
  1451. allFun["a" /* default */].addPeople(data, function (callback) {
  1452. if (callback.success) {
  1453. var leasesData = [{
  1454. id: _this11.leasesId,
  1455. cardId: callback.data
  1456. }];
  1457. setTimeout(function () {
  1458. Object(api["g" /* httpPost */])(leasesData, _this11.$api.postUpdateLeases).then(function (res) {});
  1459. }, 1000);
  1460. var ids = {
  1461. ids: [callback.data]
  1462. };
  1463. _this11.form.tenant[index].id = callback.data; //新增人员id加入数据源
  1464. _this11.form.tenant[index].userTelephone = infoStr.userTelephone;
  1465. _this11.form.tenant[index].userPassword = infoStr.userPassword;
  1466. _this11.form.tenant[index].userId = infoStr.userId;
  1467. _this11.form.tenant[index].keyId = infoStr.keyId;
  1468. Object(api["g" /* httpPost */])(ids, _this11.$api.createkeyCard).then(function (res) {});
  1469. _this11.bindCheckIn(_this11.form.tenant[index], index);
  1470. } else {
  1471. _this11.$message.error(callback.message);
  1472. }
  1473. });
  1474. case 4:
  1475. case "end":
  1476. return _context4.stop();
  1477. }
  1478. }
  1479. }, _callee4, _this11);
  1480. }))();
  1481. },
  1482. // 删除同住人
  1483. deleteCohabitant: function deleteCohabitant(index) {
  1484. this.form.tenant.splice(index, 1);
  1485. },
  1486. // 添加同住人
  1487. addCohabitant: function addCohabitant() {
  1488. var sourceData = {
  1489. id: '',
  1490. name: '',
  1491. phone: '',
  1492. number: '',
  1493. cardType: 1,
  1494. sex: '',
  1495. place: '',
  1496. address: '',
  1497. tenantType: '',
  1498. subsidy: '',
  1499. userTelephone: '',
  1500. userPassword: '',
  1501. userId: '',
  1502. keyId: ''
  1503. };
  1504. this.form.tenant.push(sourceData);
  1505. },
  1506. // 选择房间
  1507. selectRoom: function selectRoom(index, row) {
  1508. var _this12 = this;
  1509. return asyncToGenerator_default()( /*#__PURE__*/regenerator_default.a.mark(function _callee5() {
  1510. var repeatStatus, dataList, resultStatus, i;
  1511. return regenerator_default.a.wrap(function _callee5$(_context5) {
  1512. while (1) {
  1513. switch (_context5.prev = _context5.next) {
  1514. case 0:
  1515. repeatStatus = util["a" /* default */].isRepeat(_this12.form.tenant);
  1516. if (!repeatStatus) {
  1517. _context5.next = 6;
  1518. break;
  1519. }
  1520. _this12.$message.warning('同住人员有重复的表单信息,请填写正确表单信息');
  1521. _this12.activeNames = '1';
  1522. _context5.next = 20;
  1523. break;
  1524. case 6:
  1525. dataList = _this12.form.tenant;
  1526. resultStatus = true;
  1527. for (i = 0; i < dataList.length; i++) {
  1528. if (dataList[i].number === '' || dataList[i].phone === '' || dataList[i].name === '' || dataList[i].cardType === '') {
  1529. resultStatus = false;
  1530. }
  1531. }
  1532. if (resultStatus) {
  1533. _context5.next = 14;
  1534. break;
  1535. }
  1536. _this12.$message.warning('请正确填写签约人表单信息');
  1537. _this12.activeNames = '1';
  1538. _context5.next = 20;
  1539. break;
  1540. case 14:
  1541. _this12.form.roomName = row.path;
  1542. _this12.form.roomId = row.id;
  1543. _this12.form.acreage = row.acreage;
  1544. _this12.form.layout = row.layout;
  1545. _context5.next = 20;
  1546. return _this12.getDeviceInfo();
  1547. case 20:
  1548. case "end":
  1549. return _context5.stop();
  1550. }
  1551. }
  1552. }, _callee5, _this12);
  1553. }))();
  1554. },
  1555. // 获取房间对应设备信息
  1556. getDeviceInfo: function getDeviceInfo() {
  1557. var _this13 = this;
  1558. var q = {
  1559. roomIds: [this.form.roomId]
  1560. };
  1561. var data = {
  1562. q: stringify_default()(q),
  1563. pageNum: 1,
  1564. pageSize: 1
  1565. };
  1566. Object(api["g" /* httpPost */])(data, this.$api.getDeviceItems).then(function (res) {
  1567. if (res.success) {
  1568. if (res.data.list.length > 0) {
  1569. _this13.form.deviceNum = res.data.list[0].deviceNum;
  1570. _this13.form.imei = res.data.list[0].imei;
  1571. _this13.form.manufactureId = res.data.list[0].manufactureId;
  1572. _this13.activeNames = '3';
  1573. } else {
  1574. _this13.form.roomId = '';
  1575. _this13.form.roomName = '';
  1576. _this13.form.acreage = '';
  1577. _this13.form.layout = '';
  1578. _this13.$message.error('该房间还未绑定设备,请绑定设备后进行入住');
  1579. }
  1580. } else {
  1581. _this13.$message.error(res.message);
  1582. }
  1583. });
  1584. },
  1585. // 搜索房源
  1586. searchRoom: function searchRoom() {
  1587. var _this14 = this;
  1588. var q = {
  1589. name: this.form.roomNameSearch,
  1590. ancestor: this.checkNodeId,
  1591. isRoom: 1
  1592. };
  1593. var data = {
  1594. q: stringify_default()(q),
  1595. type: 0,
  1596. pageNum: 1,
  1597. pageSize: 10
  1598. };
  1599. Object(api["d" /* httpGet */])(data, this.$api.getSiteList).then(function (res) {
  1600. if (res.success) {
  1601. res.data.list.list.map(function (li) {
  1602. var name = util["a" /* default */].findIndexArray(_this14.roomList, li.id, []);
  1603. var layoutText = li.layout === 0 ? '单间' : li.layout === 1 ? '一室一厅' : li.layout === 2 ? '两室一厅' : '三室一厅';
  1604. var path = '';
  1605. if (name) {
  1606. path = name.join('/');
  1607. }
  1608. li['layoutText'] = layoutText;
  1609. li['path'] = path;
  1610. });
  1611. _this14.tableDataRom = res.data.list.list;
  1612. } else {
  1613. _this14.$message.error(res.message);
  1614. }
  1615. });
  1616. },
  1617. // 搜索对应人员
  1618. searchPeople: function searchPeople(index) {
  1619. var _this15 = this;
  1620. if (!util["a" /* default */].verificationPhone(this.form.tenant[index].phone) && this.form.tenant[index].phone.length > 0) {
  1621. this.$message.error('手机格式错误');
  1622. }
  1623. if (Object(verification["a" /* default */])(this.form.tenant[index].number)) {
  1624. this.$message.error('身份证号错误');
  1625. }
  1626. var q = {
  1627. number: this.form.tenant[index].number,
  1628. phone: this.form.tenant[index].phone
  1629. };
  1630. var data = {
  1631. pageNum: 1,
  1632. pageSize: 10,
  1633. orderBy: "create_time desc",
  1634. q: stringify_default()(q)
  1635. };
  1636. Object(api["g" /* httpPost */])(data, this.$api.getlistNum).then(function (res1) {
  1637. if (res1.success) {
  1638. if (res1.data.list.length > 0) {
  1639. var personInfo = JSON.parse(res1.data.list[0].info);
  1640. _this15.form.tenant[index].id = res1.data.list[0].id;
  1641. _this15.form.tenant[index].phone = res1.data.list[0].phone;
  1642. _this15.form.tenant[index].number = res1.data.list[0].number;
  1643. _this15.form.tenant[index].sex = res1.data.list[0].sex;
  1644. _this15.form.tenant[index].name = res1.data.list[0].name;
  1645. _this15.form.tenant[index].userTelephone = personInfo.userTelephone;
  1646. _this15.form.tenant[index].userPassword = personInfo.userPassword;
  1647. _this15.form.tenant[index].userId = personInfo.userId;
  1648. _this15.form.tenant[index].keyId = personInfo.keyId;
  1649. } else {
  1650. _this15.form.tenant[index].id = '';
  1651. _this15.form.tenant[index].phone = '';
  1652. _this15.form.tenant[index].number = '';
  1653. _this15.form.tenant[index].sex = '';
  1654. _this15.form.tenant[index].name = '';
  1655. _this15.form.tenant[index].userTelephone = '';
  1656. _this15.form.tenant[index].userPassword = '';
  1657. _this15.form.tenant[index].userId = '';
  1658. _this15.form.tenant[index].keyId = '';
  1659. _this15.$message.error("未找到人员");
  1660. }
  1661. } else {
  1662. _this15.$message.error(res1.message);
  1663. }
  1664. });
  1665. },
  1666. // 获取房源
  1667. getAllTree: function getAllTree() {
  1668. var _this16 = this;
  1669. var data = {};
  1670. Object(api["d" /* httpGet */])(data, this.$api.getTree).then(function (res) {
  1671. var userList = [];
  1672. var temp = {},
  1673. arr = [];
  1674. res.data.forEach(function (item, index) {
  1675. if (!temp[item.id]) {
  1676. arr.push(item);
  1677. temp[item.id] = true;
  1678. }
  1679. });
  1680. arr.map(function (li) {
  1681. if (li.expand) {
  1682. if (JSON.parse(li.expand).type == "0") {
  1683. userList.push(li);
  1684. }
  1685. }
  1686. });
  1687. var list = res.data.sort(function (pre, cur) {
  1688. return pre.id - cur.id;
  1689. });
  1690. var arrData = Object(utils["o" /* uniqueArray1 */])(list, "id");
  1691. _this16.roomList = Object(utils["p" /* ztreeToElementTree */])(arrData, {});
  1692. });
  1693. },
  1694. // 选择房源
  1695. checkNode: function checkNode(e) {
  1696. var _this17 = this;
  1697. return asyncToGenerator_default()( /*#__PURE__*/regenerator_default.a.mark(function _callee6() {
  1698. var options, arr, listArr, obj;
  1699. return regenerator_default.a.wrap(function _callee6$(_context6) {
  1700. while (1) {
  1701. switch (_context6.prev = _context6.next) {
  1702. case 0:
  1703. _this17.checkNodeId = e[e.length - 1];
  1704. options = _this17.roomList;
  1705. _context6.next = 4;
  1706. return _this17.getId(options, e[e.length - 1]);
  1707. case 4:
  1708. arr = _context6.sent;
  1709. listArr = [arr[0]];
  1710. obj = _this17.getNodeId(listArr);
  1711. _this17.form.roomId = obj;
  1712. _this17.searchRoom();
  1713. case 9:
  1714. case "end":
  1715. return _context6.stop();
  1716. }
  1717. }
  1718. }, _callee6, _this17);
  1719. }))();
  1720. },
  1721. getId: function getId(list, id) {
  1722. for (var i in list) {
  1723. if (list[i].id == id) {
  1724. return [list[i]];
  1725. }
  1726. if (list[i].children) {
  1727. var node = this.getParentId(list[i].children, id);
  1728. if (node !== undefined) {
  1729. return node;
  1730. }
  1731. }
  1732. }
  1733. },
  1734. getNodeId: function getNodeId(list) {
  1735. var newNodeId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  1736. for (var i in list) {
  1737. newNodeId.push(list[i].id);
  1738. if (list[i].children) {
  1739. this.getNodeId(list[i].children, newNodeId);
  1740. }
  1741. }
  1742. return newNodeId;
  1743. },
  1744. getParentId: function getParentId(list, id) {
  1745. for (var i in list) {
  1746. if (list[i].id == id) {
  1747. return [list[i]];
  1748. }
  1749. if (list[i].children) {
  1750. var node = this.getParentId(list[i].children, id);
  1751. if (node !== undefined) {
  1752. return node.concat(list[i]);
  1753. }
  1754. }
  1755. }
  1756. },
  1757. // 签约
  1758. signContract: function signContract() {
  1759. this.dialogVisible = true;
  1760. // this.getAllTree()
  1761. },
  1762. // 批量删除
  1763. batchDeleteMethods: function batchDeleteMethods() {
  1764. var _this18 = this;
  1765. if (this.multipleSelection.length === 0) {
  1766. this.$message.error('请选择批量删除合约');
  1767. } else {
  1768. this.$confirm("是否先进行批量删除?", "提示", {
  1769. type: "warning"
  1770. }).then(function () {
  1771. var ids = [];
  1772. _this18.multipleSelection.map(function (li) {
  1773. ids.push(li.id);
  1774. });
  1775. var list = {
  1776. ids: ids
  1777. };
  1778. Object(api["g" /* httpPost */])(list, _this18.$api.postDeleteLeases).then(function (res) {
  1779. if (res.success) {
  1780. _this18.$message.success('删除成功');
  1781. _this18.getLeasesList();
  1782. _this18.getLeasesStatus();
  1783. } else {
  1784. _this18.$message.error(res.message);
  1785. }
  1786. });
  1787. });
  1788. }
  1789. },
  1790. // 批量退租
  1791. batchLeaseCancellationMethods: function batchLeaseCancellationMethods() {
  1792. var _this19 = this;
  1793. if (this.multipleSelection.length === 0) {
  1794. this.$message.error('请选择批量退租合约');
  1795. } else {
  1796. this.$confirm("是否先进行批量退租?", "提示", {
  1797. type: "warning"
  1798. }).then(function () {
  1799. _this19.rentingMultipleMethods();
  1800. });
  1801. }
  1802. },
  1803. // 退租
  1804. rentOutOperation: function rentOutOperation(index, row) {
  1805. var _this20 = this;
  1806. this.multipleSelection = [row];
  1807. this.$confirm("是否先进行退租?", "提示", {
  1808. type: "warning"
  1809. }).then(function () {
  1810. _this20.rentingMultipleMethods();
  1811. });
  1812. },
  1813. // 退租方法
  1814. rentingMultipleMethods: function rentingMultipleMethods() {
  1815. var _this21 = this;
  1816. var _this = this;
  1817. this.multipleSelection.map(function (li) {
  1818. _this21.getRoomIdDeviceInfo(li.siteId).then(function (res) {
  1819. if (res.data.total > 0) {
  1820. if (res.data.list[0].manufactureId === 201 || res.data.list[0].manufactureId === 221) {
  1821. allFun["a" /* default */].unbindPeopleAndRooms(li.cardId, res.data.list[0].imei, function (callback) {
  1822. if (callback.success) {
  1823. var dataOne = util["a" /* default */].zlib_unzip(callback.data);
  1824. if (dataOne.length > 0) {
  1825. var lookUserInfo = JSON.parse(dataOne[0].content);
  1826. var dataLook = {
  1827. lockerId: dataOne[0].deviceNum,
  1828. imei: dataOne[0].imei,
  1829. lockerUserId: lookUserInfo.lockerUserId,
  1830. keyId: lookUserInfo.keyId,
  1831. role: 0,
  1832. action: 2, //1--添加、2--删除、3--修改
  1833. order: 6203,
  1834. cardName: lookUserInfo.cardName,
  1835. roomName: lookUserInfo.roomName
  1836. };
  1837. Object(api["g" /* httpPost */])(dataLook, _this.$api.ZGduserOperation).then(function (res2) {
  1838. if (res2.success) {
  1839. var dataUnbind = [{
  1840. siteId: li.siteId,
  1841. cardId: li.cardId
  1842. }];
  1843. Object(api["g" /* httpPost */])(dataUnbind, _this.$api.unbindCard).then(function (res) {
  1844. _this.$message.success("退租成功");
  1845. var refundLeasesData = [{
  1846. id: li.id,
  1847. status: 3
  1848. }];
  1849. Object(api["g" /* httpPost */])(refundLeasesData, _this.$api.postUpdateLeases).then(function (res) {});
  1850. _this.getLeasesList();
  1851. _this.getLeasesStatus();
  1852. });
  1853. } else {
  1854. _this.$message.error(res2.msg);
  1855. }
  1856. });
  1857. }
  1858. } else {
  1859. _this.$message.error(callback.msg);
  1860. }
  1861. });
  1862. } else if (res.data.list[0].manufactureId === 101) {
  1863. allFun["a" /* default */].unbindPeopleAndRooms(li.cardId, res.data.list[0].imei, function (callback) {
  1864. if (callback.success) {
  1865. var dataOne = util["a" /* default */].zlib_unzip(callback.data);
  1866. var lookUserInfo = JSON.parse(dataOne[0].content);
  1867. var str = {
  1868. imei: dataOne[0].imei,
  1869. deviceNum: dataOne[0].deviceNum,
  1870. userTelephone: lookUserInfo.userTelephone,
  1871. userPassword: lookUserInfo.userPassword,
  1872. operateMode: 3,
  1873. order: 6203,
  1874. password: "20210816",
  1875. cardName: lookUserInfo.cardName,
  1876. roomName: lookUserInfo.roomName,
  1877. is: false
  1878. };
  1879. Object(api["g" /* httpPost */])(str, _this.$api.getDeviceOperateUserInfo).then(function (res1) {
  1880. if (res1.success) {
  1881. var dataUnbind = [{
  1882. siteId: li.siteId,
  1883. cardId: li.cardId
  1884. }];
  1885. Object(api["g" /* httpPost */])(dataUnbind, _this.$api.unbindCard).then(function (res) {
  1886. _this.$message.success("退租成功");
  1887. var refundLeasesData = [{
  1888. id: li.id,
  1889. status: 3
  1890. }];
  1891. Object(api["g" /* httpPost */])(refundLeasesData, _this.$api.postUpdateLeases).then(function (res) {});
  1892. _this.getLeasesList();
  1893. _this.getLeasesStatus();
  1894. });
  1895. } else {
  1896. _this.$message.error(res1.msg);
  1897. }
  1898. });
  1899. } else {
  1900. _this.$message.error(callback.msg);
  1901. }
  1902. });
  1903. }
  1904. } else {
  1905. _this21.$notify({
  1906. title: '警告',
  1907. message: "\u8BE5\u5408\u7EA6\u623F\u95F4\uFF08" + li.address + "\uFF09\u6CA1\u6709\u627E\u5230\u5BF9\u5E94\u623F\u95F4\u4FE1\u606F",
  1908. duration: 0,
  1909. type: 'warning'
  1910. });
  1911. return false;
  1912. }
  1913. });
  1914. });
  1915. },
  1916. // 根据房间id获取设备信息
  1917. getRoomIdDeviceInfo: function getRoomIdDeviceInfo(roomId) {
  1918. var _this = this;
  1919. return new promise_default.a(function (resolve, reject) {
  1920. var q = {
  1921. roomIds: [roomId]
  1922. };
  1923. var data = {
  1924. q: stringify_default()(q),
  1925. pageNum: 1,
  1926. pageSize: 1
  1927. };
  1928. Object(api["g" /* httpPost */])(data, _this.$api.getDeviceItems).then(function (res) {
  1929. resolve(res);
  1930. });
  1931. });
  1932. },
  1933. // 多选
  1934. handleSelectionChange: function handleSelectionChange(value) {
  1935. this.multipleSelection = value;
  1936. },
  1937. // 关闭签约弹窗
  1938. handleClose: function handleClose() {
  1939. this.dialogVisible = false;
  1940. },
  1941. handleCloseExport: function handleCloseExport() {
  1942. this.dialogVisibleExport = false;
  1943. },
  1944. // 重置搜索
  1945. restSearch: function restSearch() {
  1946. this.search = {
  1947. name: '',
  1948. phone: '',
  1949. status: '',
  1950. signingTime: '',
  1951. contractTime: '',
  1952. siteIds: ''
  1953. };
  1954. },
  1955. // 搜索
  1956. handleSearch: function handleSearch() {
  1957. this.getLeasesList();
  1958. },
  1959. // 设置每页数量
  1960. handleSizeChange: function handleSizeChange(val) {
  1961. this.pageSize = val;
  1962. this.getLeasesList();
  1963. },
  1964. // 跳转页码
  1965. handleCurrentChange: function handleCurrentChange(val) {
  1966. this.pageNum = val;
  1967. this.getLeasesList();
  1968. }
  1969. }
  1970. });
  1971. // CONCATENATED MODULE: ./node_modules/vue-loader/lib/template-compiler?{"id":"data-v-30b27e78","hasScoped":true,"transformToRequire":{"video":["src","poster"],"source":"src","img":"src","image":"xlink:href"},"buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/views/agreement.vue
  1972. var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"agreement"},[_c('div',{staticClass:"container"},[_c('el-row',{staticClass:"mb-5",attrs:{"gutter":20}},[_c('el-col',{attrs:{"span":24}},[_c('el-card',{attrs:{"shadow":"never"}},[_c('div',{staticClass:"d-flex flex-wrap align-center justify-space-around font-style"},[_c('div',{staticClass:"flexLi my-2 d-flex flex-nowrap align-center d-inlie-block text-center hand-type"},[_c('div',{staticClass:"mr-2"},[_c('i',{staticClass:"iconfont httpicon-tongjifenxi font-size-40 color-03A9F4"})]),_vm._v(" "),_c('div',[_c('div',{staticClass:"color-00000073 font-size-16 font-weight-700 color-03A9F4"},[_vm._v("总收入")]),_vm._v(" "),_c('div',{staticClass:"font-size-24 mt-2"},[_c('NumberGrow',{staticClass:"color-03A9F4",attrs:{"value":0}}),_c('span',{staticClass:"font-size-16 color-00000073 ml-1"},[_vm._v("元")])],1)])]),_vm._v(" "),_c('div',{staticClass:"flexLi my-2 d-flex flex-nowrap align-center d-inlie-block text-center hand-type"},[_c('div',{staticClass:"mr-2"},[_c('i',{staticClass:"iconfont httpicon-yewuguanli font-size-40 color-03A9F4"})]),_vm._v(" "),_c('div',[_c('div',{staticClass:"color-00000073 font-size-16 font-weight-700 color-03A9F4"},[_vm._v("合同数")]),_vm._v(" "),_c('div',{staticClass:"font-size-24 mt-2"},[_c('NumberGrow',{staticClass:"color-03A9F4",attrs:{"value":_vm.contractStatus.total}}),_c('span',{staticClass:"font-size-16 color-00000073 ml-1"},[_vm._v("个")])],1)])]),_vm._v(" "),_c('div',{staticClass:"flexLi my-2 d-flex flex-nowrap align-center d-inlie-block text-center hand-type"},[_c('div',{staticClass:"mr-2"},[_c('i',{staticClass:"iconfont httpicon-pingzhengguanli font-size-40 color-03A9F4"})]),_vm._v(" "),_c('div',[_c('div',{staticClass:"color-00000073 font-size-16 font-weight-700 color-03A9F4"},[_vm._v("已签约")]),_vm._v(" "),_c('div',{staticClass:"font-size-24 mt-2"},[_c('NumberGrow',{staticClass:"color-03A9F4",attrs:{"value":_vm.contractStatus.signed}}),_c('span',{staticClass:"font-size-16 color-00000073 ml-1"},[_vm._v("人")])],1)])]),_vm._v(" "),_c('div',{staticClass:"flexLi my-2 d-flex flex-nowrap align-center d-inlie-block text-center hand-type"},[_c('div',{staticClass:"mr-2"},[_c('i',{staticClass:"iconfont httpicon-wuyedangan font-size-40 color-ff9900"})]),_vm._v(" "),_c('div',[_c('div',{staticClass:"color-00000073 font-size-16 font-weight-700 color-ff9900"},[_vm._v("已到期")]),_vm._v(" "),_c('div',{staticClass:"font-size-24 mt-2"},[_c('NumberGrow',{staticClass:"color-ff9900",attrs:{"value":_vm.contractStatus.expired}}),_c('span',{staticClass:"font-size-16 color-00000073 ml-1"},[_vm._v("间")])],1)])]),_vm._v(" "),_c('div',{staticClass:"flexLi my-2 d-flex flex-nowrap align-center d-inlie-block text-center hand-type"},[_c('div',{staticClass:"mr-2"},[_c('i',{staticClass:"iconfont httpicon-pingzhengguanli font-size-40 color-F56C6C"})]),_vm._v(" "),_c('div',[_c('div',{staticClass:"color-00000073 font-size-16 font-weight-700 color-F56C6C"},[_vm._v("已欠费")]),_vm._v(" "),_c('div',{staticClass:"font-size-24 mt-2"},[_c('NumberGrow',{staticClass:"color-F56C6C",attrs:{"value":_vm.contractStatus.arrears}}),_c('span',{staticClass:"font-size-16 color-00000073 ml-1"},[_vm._v("间")])],1)])]),_vm._v(" "),_c('div',{staticClass:"flexLi my-2 d-flex flex-nowrap align-center d-inlie-block text-center hand-type"},[_c('div',{staticClass:"mr-2"},[_c('i',{staticClass:"iconfont httpicon-bianji font-size-40 color-03A9F4"})]),_vm._v(" "),_c('div',[_c('div',{staticClass:"color-00000073 font-size-16 font-weight-700 color-03A9F4"},[_vm._v("待签约")]),_vm._v(" "),_c('div',{staticClass:"font-size-24 mt-2"},[_c('NumberGrow',{staticClass:"color-03A9F4",attrs:{"value":_vm.contractStatus.toBeSigned}}),_c('span',{staticClass:"font-size-16 color-00000073 ml-1"},[_vm._v("人")])],1)])])])])],1)],1),_vm._v(" "),_c('el-input',{staticClass:"handle-input width150 mb-1",attrs:{"size":"small","placeholder":"租客名称","clearable":true},model:{value:(_vm.search.name),callback:function ($$v) {_vm.$set(_vm.se
  1973. var item = ref.item;
  1974. return [_c('div',{staticClass:"name"},[_vm._v(_vm._s(item.name)+"->"+_vm._s(item.phone))])]}}],null,true),model:{value:(_vm.form.tenant[index].name),callback:function ($$v) {_vm.$set(_vm.form.tenant[index], "name", $$v)},expression:"form.tenant[index].name"}})],1)]),_vm._v(" "),_c('div',{staticClass:"demo-input-suffix d-inlie-block mr-2 mb-2"},[_c('div',{staticClass:"d-flex align-center"},[_c('span',{staticClass:"width50 text-center"},[_c('b',{staticClass:"color-red"},[_vm._v("*")]),_vm._v("手机号")]),_vm._v(" "),_c('el-input',{staticClass:"width200",attrs:{"clearable":true,"placeholder":"请输入电话号码"},model:{value:(_vm.form.tenant[index].phone),callback:function ($$v) {_vm.$set(_vm.form.tenant[index], "phone", $$v)},expression:"form.tenant[index].phone"}},[_c('el-button',{attrs:{"slot":"append","icon":"el-icon-right"},on:{"click":function($event){$event.stopPropagation();return _vm.searchPeople(index)}},slot:"append"})],1)],1)]),_vm._v(" "),_c('div',{staticClass:"demo-input-suffix d-inlie-block mr-2 mb-2"},[_c('div',{staticClass:"d-flex align-center"},[_c('span',{staticClass:"width100 text-center mr-1"},[_c('b',{staticClass:"color-red"},[_vm._v("*")]),_vm._v("证件类型")]),_vm._v(" "),_c('el-select',{staticClass:"width200",attrs:{"placeholder":"请选择证件类型","clearable":true},model:{value:(_vm.form.tenant[index].cardType),callback:function ($$v) {_vm.$set(_vm.form.tenant[index], "cardType", $$v)},expression:"form.tenant[index].cardType"}},_vm._l((_vm.IdCardOptions),function(item){return _c('el-option',{key:item.value,attrs:{"label":item.label,"value":item.value}})}),1)],1)]),_vm._v(" "),_c('div',{staticClass:"demo-input-suffix d-inlie-block mr-2 mb-2"},[_c('div',{staticClass:"d-flex align-center"},[_c('span',{staticClass:"width50 text-center"},[_c('b',{staticClass:"color-red"},[_vm._v("*")]),_vm._v("证件号")]),_vm._v(" "),_c('el-input',{staticClass:"width200",attrs:{"clearable":true,"placeholder":"请输入证件号"},model:{value:(_vm.form.tenant[index].number),callback:function ($$v) {_vm.$set(_vm.form.tenant[index], "number", $$v)},expression:"form.tenant[index].number"}},[_c('el-button',{attrs:{"slot":"append","icon":"el-icon-right"},on:{"click":function($event){$event.stopPropagation();return _vm.searchPeople(index)}},slot:"append"})],1)],1)]),_vm._v(" "),_c('div',{staticClass:"demo-input-suffix d-inlie-block mr-2 mb-2"},[_c('div',{staticClass:"d-flex align-center"},[_c('span',{staticClass:"width50 text-center"},[_vm._v("性别")]),_vm._v(" "),_c('el-select',{staticClass:"width200",attrs:{"placeholder":"请选择性别","clearable":true},model:{value:(_vm.form.tenant[index].sex),callback:function ($$v) {_vm.$set(_vm.form.tenant[index], "sex", $$v)},expression:"form.tenant[index].sex"}},_vm._l((_vm.sexOptions),function(item){return _c('el-option',{key:item.value,attrs:{"label":item.label,"value":item.value}})}),1)],1)]),_vm._v(" "),_c('div',{staticClass:"demo-input-suffix d-inlie-block mr-2 mb-2"},[_c('div',{staticClass:"d-flex align-center"},[_c('span',{staticClass:"width50 text-center"},[_vm._v("籍贯")]),_vm._v(" "),_c('el-input',{staticClass:"width200",attrs:{"clearable":true,"placeholder":"请输入籍贯"},model:{value:(_vm.form.tenant[index].place),callback:function ($$v) {_vm.$set(_vm.form.tenant[index], "place", $$v)},expression:"form.tenant[index].place"}})],1)]),_vm._v(" "),_c('div',{staticClass:"demo-input-suffix d-inlie-block mr-2 mb-2"},[_c('div',{staticClass:"d-flex align-center"},[_c('span',{staticClass:"width100 text-center mr-1"},[_vm._v("通讯地址")]),_vm._v(" "),_c('el-input',{staticClass:"width200",attrs:{"clearable":true,"placeholder":"请输入通讯地址"},model:{value:(_vm.form.tenant[index].address),callback:function ($$v) {_vm.$set(_vm.form.tenant[index], "address", $$v)},expression:"form.tenant[index].address"}})],1)]),_vm._v(" "),_c('div',{staticClass:"demo-input-suffix d-inlie-block mr-2 mb-2"},[_c('div',{staticClass:"d-flex align-center"},[_c('span',{staticClass:"width100 text-center mr-1"},[_vm._v("租户类别")]),_vm._v(" "),_c('el-select',{staticCl
  1975. var staticRenderFns = []
  1976. var esExports = { render: render, staticRenderFns: staticRenderFns }
  1977. /* harmony default export */ var views_agreement = (esExports);
  1978. // CONCATENATED MODULE: ./src/views/agreement.vue
  1979. function injectStyle (ssrContext) {
  1980. __webpack_require__("BR/S")
  1981. }
  1982. var normalizeComponent = __webpack_require__("VU/8")
  1983. /* script */
  1984. /* template */
  1985. /* template functional */
  1986. var __vue_template_functional__ = false
  1987. /* styles */
  1988. var __vue_styles__ = injectStyle
  1989. /* scopeId */
  1990. var __vue_scopeId__ = "data-v-30b27e78"
  1991. /* moduleIdentifier (server only) */
  1992. var __vue_module_identifier__ = null
  1993. var Component = normalizeComponent(
  1994. agreement,
  1995. views_agreement,
  1996. __vue_template_functional__,
  1997. __vue_styles__,
  1998. __vue_scopeId__,
  1999. __vue_module_identifier__
  2000. )
  2001. /* harmony default export */ var src_views_agreement = __webpack_exports__["default"] = (Component.exports);
  2002. /***/ }),
  2003. /***/ "SiUS":
  2004. /***/ (function(module, exports) {
  2005. // removed by extract-text-webpack-plugin
  2006. /***/ }),
  2007. /***/ "U3YJ":
  2008. /***/ (function(module, exports, __webpack_require__) {
  2009. var require;var require;!function(e){if(true)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.htmlDocx=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return require(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  2010. /*!
  2011. * The buffer module from node.js, for the browser.
  2012. *
  2013. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  2014. * @license MIT
  2015. */
  2016. var base64 = _dereq_('base64-js')
  2017. var ieee754 = _dereq_('ieee754')
  2018. var isArray = _dereq_('is-array')
  2019. exports.Buffer = Buffer
  2020. exports.SlowBuffer = Buffer
  2021. exports.INSPECT_MAX_BYTES = 50
  2022. Buffer.poolSize = 8192 // not used by this implementation
  2023. var kMaxLength = 0x3fffffff
  2024. /**
  2025. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2026. * === true Use Uint8Array implementation (fastest)
  2027. * === false Use Object implementation (most compatible, even IE6)
  2028. *
  2029. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2030. * Opera 11.6+, iOS 4.2+.
  2031. *
  2032. * Note:
  2033. *
  2034. * - Implementation must support adding new properties to `Uint8Array` instances.
  2035. * Firefox 4-29 lacked support, fixed in Firefox 30+.
  2036. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  2037. *
  2038. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  2039. *
  2040. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  2041. * incorrect length in some situations.
  2042. *
  2043. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
  2044. * get the Object implementation, which is slower but will work correctly.
  2045. */
  2046. Buffer.TYPED_ARRAY_SUPPORT = (function () {
  2047. try {
  2048. var buf = new ArrayBuffer(0)
  2049. var arr = new Uint8Array(buf)
  2050. arr.foo = function () { return 42 }
  2051. return 42 === arr.foo() && // typed array instances can be augmented
  2052. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  2053. new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  2054. } catch (e) {
  2055. return false
  2056. }
  2057. })()
  2058. /**
  2059. * Class: Buffer
  2060. * =============
  2061. *
  2062. * The Buffer constructor returns instances of `Uint8Array` that are augmented
  2063. * with function properties for all the node `Buffer` API functions. We use
  2064. * `Uint8Array` so that square bracket notation works as expected -- it returns
  2065. * a single octet.
  2066. *
  2067. * By augmenting the instances, we can avoid modifying the `Uint8Array`
  2068. * prototype.
  2069. */
  2070. function Buffer (subject, encoding, noZero) {
  2071. if (!(this instanceof Buffer))
  2072. return new Buffer(subject, encoding, noZero)
  2073. var type = typeof subject
  2074. // Find the length
  2075. var length
  2076. if (type === 'number')
  2077. length = subject > 0 ? subject >>> 0 : 0
  2078. else if (type === 'string') {
  2079. if (encoding === 'base64')
  2080. subject = base64clean(subject)
  2081. length = Buffer.byteLength(subject, encoding)
  2082. } else if (type === 'object' && subject !== null) { // assume object is array-like
  2083. if (subject.type === 'Buffer' && isArray(subject.data))
  2084. subject = subject.data
  2085. length = +subject.length > 0 ? Math.floor(+subject.length) : 0
  2086. } else
  2087. throw new TypeError('must start with number, buffer, array or string')
  2088. if (this.length > kMaxLength)
  2089. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2090. 'size: 0x' + kMaxLength.toString(16) + ' bytes')
  2091. var buf
  2092. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2093. // Preferred: Return an augmented `Uint8Array` instance for best performance
  2094. buf = Buffer._augment(new Uint8Array(length))
  2095. } else {
  2096. // Fallback: Return THIS instance of Buffer (created by `new`)
  2097. buf = this
  2098. buf.length = length
  2099. buf._isBuffer = true
  2100. }
  2101. var i
  2102. if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
  2103. // Speed optimization -- use set if we're copying from a typed array
  2104. buf._set(subject)
  2105. } else if (isArrayish(subject)) {
  2106. // Treat array-ish objects as a byte array
  2107. if (Buffer.isBuffer(subject)) {
  2108. for (i = 0; i < length; i++)
  2109. buf[i] = subject.readUInt8(i)
  2110. } else {
  2111. for (i = 0; i < length; i++)
  2112. buf[i] = ((subject[i] % 256) + 256) % 256
  2113. }
  2114. } else if (type === 'string') {
  2115. buf.write(subject, 0, encoding)
  2116. } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) {
  2117. for (i = 0; i < length; i++) {
  2118. buf[i] = 0
  2119. }
  2120. }
  2121. return buf
  2122. }
  2123. Buffer.isBuffer = function (b) {
  2124. return !!(b != null && b._isBuffer)
  2125. }
  2126. Buffer.compare = function (a, b) {
  2127. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b))
  2128. throw new TypeError('Arguments must be Buffers')
  2129. var x = a.length
  2130. var y = b.length
  2131. for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
  2132. if (i !== len) {
  2133. x = a[i]
  2134. y = b[i]
  2135. }
  2136. if (x < y) return -1
  2137. if (y < x) return 1
  2138. return 0
  2139. }
  2140. Buffer.isEncoding = function (encoding) {
  2141. switch (String(encoding).toLowerCase()) {
  2142. case 'hex':
  2143. case 'utf8':
  2144. case 'utf-8':
  2145. case 'ascii':
  2146. case 'binary':
  2147. case 'base64':
  2148. case 'raw':
  2149. case 'ucs2':
  2150. case 'ucs-2':
  2151. case 'utf16le':
  2152. case 'utf-16le':
  2153. return true
  2154. default:
  2155. return false
  2156. }
  2157. }
  2158. Buffer.concat = function (list, totalLength) {
  2159. if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])')
  2160. if (list.length === 0) {
  2161. return new Buffer(0)
  2162. } else if (list.length === 1) {
  2163. return list[0]
  2164. }
  2165. var i
  2166. if (totalLength === undefined) {
  2167. totalLength = 0
  2168. for (i = 0; i < list.length; i++) {
  2169. totalLength += list[i].length
  2170. }
  2171. }
  2172. var buf = new Buffer(totalLength)
  2173. var pos = 0
  2174. for (i = 0; i < list.length; i++) {
  2175. var item = list[i]
  2176. item.copy(buf, pos)
  2177. pos += item.length
  2178. }
  2179. return buf
  2180. }
  2181. Buffer.byteLength = function (str, encoding) {
  2182. var ret
  2183. str = str + ''
  2184. switch (encoding || 'utf8') {
  2185. case 'ascii':
  2186. case 'binary':
  2187. case 'raw':
  2188. ret = str.length
  2189. break
  2190. case 'ucs2':
  2191. case 'ucs-2':
  2192. case 'utf16le':
  2193. case 'utf-16le':
  2194. ret = str.length * 2
  2195. break
  2196. case 'hex':
  2197. ret = str.length >>> 1
  2198. break
  2199. case 'utf8':
  2200. case 'utf-8':
  2201. ret = utf8ToBytes(str).length
  2202. break
  2203. case 'base64':
  2204. ret = base64ToBytes(str).length
  2205. break
  2206. default:
  2207. ret = str.length
  2208. }
  2209. return ret
  2210. }
  2211. // pre-set for values that may exist in the future
  2212. Buffer.prototype.length = undefined
  2213. Buffer.prototype.parent = undefined
  2214. // toString(encoding, start=0, end=buffer.length)
  2215. Buffer.prototype.toString = function (encoding, start, end) {
  2216. var loweredCase = false
  2217. start = start >>> 0
  2218. end = end === undefined || end === Infinity ? this.length : end >>> 0
  2219. if (!encoding) encoding = 'utf8'
  2220. if (start < 0) start = 0
  2221. if (end > this.length) end = this.length
  2222. if (end <= start) return ''
  2223. while (true) {
  2224. switch (encoding) {
  2225. case 'hex':
  2226. return hexSlice(this, start, end)
  2227. case 'utf8':
  2228. case 'utf-8':
  2229. return utf8Slice(this, start, end)
  2230. case 'ascii':
  2231. return asciiSlice(this, start, end)
  2232. case 'binary':
  2233. return binarySlice(this, start, end)
  2234. case 'base64':
  2235. return base64Slice(this, start, end)
  2236. case 'ucs2':
  2237. case 'ucs-2':
  2238. case 'utf16le':
  2239. case 'utf-16le':
  2240. return utf16leSlice(this, start, end)
  2241. default:
  2242. if (loweredCase)
  2243. throw new TypeError('Unknown encoding: ' + encoding)
  2244. encoding = (encoding + '').toLowerCase()
  2245. loweredCase = true
  2246. }
  2247. }
  2248. }
  2249. Buffer.prototype.equals = function (b) {
  2250. if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2251. return Buffer.compare(this, b) === 0
  2252. }
  2253. Buffer.prototype.inspect = function () {
  2254. var str = ''
  2255. var max = exports.INSPECT_MAX_BYTES
  2256. if (this.length > 0) {
  2257. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  2258. if (this.length > max)
  2259. str += ' ... '
  2260. }
  2261. return '<Buffer ' + str + '>'
  2262. }
  2263. Buffer.prototype.compare = function (b) {
  2264. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2265. return Buffer.compare(this, b)
  2266. }
  2267. // `get` will be removed in Node 0.13+
  2268. Buffer.prototype.get = function (offset) {
  2269. console.log('.get() is deprecated. Access using array indexes instead.')
  2270. return this.readUInt8(offset)
  2271. }
  2272. // `set` will be removed in Node 0.13+
  2273. Buffer.prototype.set = function (v, offset) {
  2274. console.log('.set() is deprecated. Access using array indexes instead.')
  2275. return this.writeUInt8(v, offset)
  2276. }
  2277. function hexWrite (buf, string, offset, length) {
  2278. offset = Number(offset) || 0
  2279. var remaining = buf.length - offset
  2280. if (!length) {
  2281. length = remaining
  2282. } else {
  2283. length = Number(length)
  2284. if (length > remaining) {
  2285. length = remaining
  2286. }
  2287. }
  2288. // must be an even number of digits
  2289. var strLen = string.length
  2290. if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  2291. if (length > strLen / 2) {
  2292. length = strLen / 2
  2293. }
  2294. for (var i = 0; i < length; i++) {
  2295. var byte = parseInt(string.substr(i * 2, 2), 16)
  2296. if (isNaN(byte)) throw new Error('Invalid hex string')
  2297. buf[offset + i] = byte
  2298. }
  2299. return i
  2300. }
  2301. function utf8Write (buf, string, offset, length) {
  2302. var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
  2303. return charsWritten
  2304. }
  2305. function asciiWrite (buf, string, offset, length) {
  2306. var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
  2307. return charsWritten
  2308. }
  2309. function binaryWrite (buf, string, offset, length) {
  2310. return asciiWrite(buf, string, offset, length)
  2311. }
  2312. function base64Write (buf, string, offset, length) {
  2313. var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
  2314. return charsWritten
  2315. }
  2316. function utf16leWrite (buf, string, offset, length) {
  2317. var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length, 2)
  2318. return charsWritten
  2319. }
  2320. Buffer.prototype.write = function (string, offset, length, encoding) {
  2321. // Support both (string, offset, length, encoding)
  2322. // and the legacy (string, encoding, offset, length)
  2323. if (isFinite(offset)) {
  2324. if (!isFinite(length)) {
  2325. encoding = length
  2326. length = undefined
  2327. }
  2328. } else { // legacy
  2329. var swap = encoding
  2330. encoding = offset
  2331. offset = length
  2332. length = swap
  2333. }
  2334. offset = Number(offset) || 0
  2335. var remaining = this.length - offset
  2336. if (!length) {
  2337. length = remaining
  2338. } else {
  2339. length = Number(length)
  2340. if (length > remaining) {
  2341. length = remaining
  2342. }
  2343. }
  2344. encoding = String(encoding || 'utf8').toLowerCase()
  2345. var ret
  2346. switch (encoding) {
  2347. case 'hex':
  2348. ret = hexWrite(this, string, offset, length)
  2349. break
  2350. case 'utf8':
  2351. case 'utf-8':
  2352. ret = utf8Write(this, string, offset, length)
  2353. break
  2354. case 'ascii':
  2355. ret = asciiWrite(this, string, offset, length)
  2356. break
  2357. case 'binary':
  2358. ret = binaryWrite(this, string, offset, length)
  2359. break
  2360. case 'base64':
  2361. ret = base64Write(this, string, offset, length)
  2362. break
  2363. case 'ucs2':
  2364. case 'ucs-2':
  2365. case 'utf16le':
  2366. case 'utf-16le':
  2367. ret = utf16leWrite(this, string, offset, length)
  2368. break
  2369. default:
  2370. throw new TypeError('Unknown encoding: ' + encoding)
  2371. }
  2372. return ret
  2373. }
  2374. Buffer.prototype.toJSON = function () {
  2375. return {
  2376. type: 'Buffer',
  2377. data: Array.prototype.slice.call(this._arr || this, 0)
  2378. }
  2379. }
  2380. function base64Slice (buf, start, end) {
  2381. if (start === 0 && end === buf.length) {
  2382. return base64.fromByteArray(buf)
  2383. } else {
  2384. return base64.fromByteArray(buf.slice(start, end))
  2385. }
  2386. }
  2387. function utf8Slice (buf, start, end) {
  2388. var res = ''
  2389. var tmp = ''
  2390. end = Math.min(buf.length, end)
  2391. for (var i = start; i < end; i++) {
  2392. if (buf[i] <= 0x7F) {
  2393. res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
  2394. tmp = ''
  2395. } else {
  2396. tmp += '%' + buf[i].toString(16)
  2397. }
  2398. }
  2399. return res + decodeUtf8Char(tmp)
  2400. }
  2401. function asciiSlice (buf, start, end) {
  2402. var ret = ''
  2403. end = Math.min(buf.length, end)
  2404. for (var i = start; i < end; i++) {
  2405. ret += String.fromCharCode(buf[i])
  2406. }
  2407. return ret
  2408. }
  2409. function binarySlice (buf, start, end) {
  2410. return asciiSlice(buf, start, end)
  2411. }
  2412. function hexSlice (buf, start, end) {
  2413. var len = buf.length
  2414. if (!start || start < 0) start = 0
  2415. if (!end || end < 0 || end > len) end = len
  2416. var out = ''
  2417. for (var i = start; i < end; i++) {
  2418. out += toHex(buf[i])
  2419. }
  2420. return out
  2421. }
  2422. function utf16leSlice (buf, start, end) {
  2423. var bytes = buf.slice(start, end)
  2424. var res = ''
  2425. for (var i = 0; i < bytes.length; i += 2) {
  2426. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  2427. }
  2428. return res
  2429. }
  2430. Buffer.prototype.slice = function (start, end) {
  2431. var len = this.length
  2432. start = ~~start
  2433. end = end === undefined ? len : ~~end
  2434. if (start < 0) {
  2435. start += len;
  2436. if (start < 0)
  2437. start = 0
  2438. } else if (start > len) {
  2439. start = len
  2440. }
  2441. if (end < 0) {
  2442. end += len
  2443. if (end < 0)
  2444. end = 0
  2445. } else if (end > len) {
  2446. end = len
  2447. }
  2448. if (end < start)
  2449. end = start
  2450. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2451. return Buffer._augment(this.subarray(start, end))
  2452. } else {
  2453. var sliceLen = end - start
  2454. var newBuf = new Buffer(sliceLen, undefined, true)
  2455. for (var i = 0; i < sliceLen; i++) {
  2456. newBuf[i] = this[i + start]
  2457. }
  2458. return newBuf
  2459. }
  2460. }
  2461. /*
  2462. * Need to make sure that buffer isn't trying to write out of bounds.
  2463. */
  2464. function checkOffset (offset, ext, length) {
  2465. if ((offset % 1) !== 0 || offset < 0)
  2466. throw new RangeError('offset is not uint')
  2467. if (offset + ext > length)
  2468. throw new RangeError('Trying to access beyond buffer length')
  2469. }
  2470. Buffer.prototype.readUInt8 = function (offset, noAssert) {
  2471. if (!noAssert)
  2472. checkOffset(offset, 1, this.length)
  2473. return this[offset]
  2474. }
  2475. Buffer.prototype.readUInt16LE = function (offset, noAssert) {
  2476. if (!noAssert)
  2477. checkOffset(offset, 2, this.length)
  2478. return this[offset] | (this[offset + 1] << 8)
  2479. }
  2480. Buffer.prototype.readUInt16BE = function (offset, noAssert) {
  2481. if (!noAssert)
  2482. checkOffset(offset, 2, this.length)
  2483. return (this[offset] << 8) | this[offset + 1]
  2484. }
  2485. Buffer.prototype.readUInt32LE = function (offset, noAssert) {
  2486. if (!noAssert)
  2487. checkOffset(offset, 4, this.length)
  2488. return ((this[offset]) |
  2489. (this[offset + 1] << 8) |
  2490. (this[offset + 2] << 16)) +
  2491. (this[offset + 3] * 0x1000000)
  2492. }
  2493. Buffer.prototype.readUInt32BE = function (offset, noAssert) {
  2494. if (!noAssert)
  2495. checkOffset(offset, 4, this.length)
  2496. return (this[offset] * 0x1000000) +
  2497. ((this[offset + 1] << 16) |
  2498. (this[offset + 2] << 8) |
  2499. this[offset + 3])
  2500. }
  2501. Buffer.prototype.readInt8 = function (offset, noAssert) {
  2502. if (!noAssert)
  2503. checkOffset(offset, 1, this.length)
  2504. if (!(this[offset] & 0x80))
  2505. return (this[offset])
  2506. return ((0xff - this[offset] + 1) * -1)
  2507. }
  2508. Buffer.prototype.readInt16LE = function (offset, noAssert) {
  2509. if (!noAssert)
  2510. checkOffset(offset, 2, this.length)
  2511. var val = this[offset] | (this[offset + 1] << 8)
  2512. return (val & 0x8000) ? val | 0xFFFF0000 : val
  2513. }
  2514. Buffer.prototype.readInt16BE = function (offset, noAssert) {
  2515. if (!noAssert)
  2516. checkOffset(offset, 2, this.length)
  2517. var val = this[offset + 1] | (this[offset] << 8)
  2518. return (val & 0x8000) ? val | 0xFFFF0000 : val
  2519. }
  2520. Buffer.prototype.readInt32LE = function (offset, noAssert) {
  2521. if (!noAssert)
  2522. checkOffset(offset, 4, this.length)
  2523. return (this[offset]) |
  2524. (this[offset + 1] << 8) |
  2525. (this[offset + 2] << 16) |
  2526. (this[offset + 3] << 24)
  2527. }
  2528. Buffer.prototype.readInt32BE = function (offset, noAssert) {
  2529. if (!noAssert)
  2530. checkOffset(offset, 4, this.length)
  2531. return (this[offset] << 24) |
  2532. (this[offset + 1] << 16) |
  2533. (this[offset + 2] << 8) |
  2534. (this[offset + 3])
  2535. }
  2536. Buffer.prototype.readFloatLE = function (offset, noAssert) {
  2537. if (!noAssert)
  2538. checkOffset(offset, 4, this.length)
  2539. return ieee754.read(this, offset, true, 23, 4)
  2540. }
  2541. Buffer.prototype.readFloatBE = function (offset, noAssert) {
  2542. if (!noAssert)
  2543. checkOffset(offset, 4, this.length)
  2544. return ieee754.read(this, offset, false, 23, 4)
  2545. }
  2546. Buffer.prototype.readDoubleLE = function (offset, noAssert) {
  2547. if (!noAssert)
  2548. checkOffset(offset, 8, this.length)
  2549. return ieee754.read(this, offset, true, 52, 8)
  2550. }
  2551. Buffer.prototype.readDoubleBE = function (offset, noAssert) {
  2552. if (!noAssert)
  2553. checkOffset(offset, 8, this.length)
  2554. return ieee754.read(this, offset, false, 52, 8)
  2555. }
  2556. function checkInt (buf, value, offset, ext, max, min) {
  2557. if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
  2558. if (value > max || value < min) throw new TypeError('value is out of bounds')
  2559. if (offset + ext > buf.length) throw new TypeError('index out of range')
  2560. }
  2561. Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
  2562. value = +value
  2563. offset = offset >>> 0
  2564. if (!noAssert)
  2565. checkInt(this, value, offset, 1, 0xff, 0)
  2566. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  2567. this[offset] = value
  2568. return offset + 1
  2569. }
  2570. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  2571. if (value < 0) value = 0xffff + value + 1
  2572. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
  2573. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  2574. (littleEndian ? i : 1 - i) * 8
  2575. }
  2576. }
  2577. Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
  2578. value = +value
  2579. offset = offset >>> 0
  2580. if (!noAssert)
  2581. checkInt(this, value, offset, 2, 0xffff, 0)
  2582. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2583. this[offset] = value
  2584. this[offset + 1] = (value >>> 8)
  2585. } else objectWriteUInt16(this, value, offset, true)
  2586. return offset + 2
  2587. }
  2588. Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
  2589. value = +value
  2590. offset = offset >>> 0
  2591. if (!noAssert)
  2592. checkInt(this, value, offset, 2, 0xffff, 0)
  2593. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2594. this[offset] = (value >>> 8)
  2595. this[offset + 1] = value
  2596. } else objectWriteUInt16(this, value, offset, false)
  2597. return offset + 2
  2598. }
  2599. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  2600. if (value < 0) value = 0xffffffff + value + 1
  2601. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
  2602. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  2603. }
  2604. }
  2605. Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
  2606. value = +value
  2607. offset = offset >>> 0
  2608. if (!noAssert)
  2609. checkInt(this, value, offset, 4, 0xffffffff, 0)
  2610. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2611. this[offset + 3] = (value >>> 24)
  2612. this[offset + 2] = (value >>> 16)
  2613. this[offset + 1] = (value >>> 8)
  2614. this[offset] = value
  2615. } else objectWriteUInt32(this, value, offset, true)
  2616. return offset + 4
  2617. }
  2618. Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
  2619. value = +value
  2620. offset = offset >>> 0
  2621. if (!noAssert)
  2622. checkInt(this, value, offset, 4, 0xffffffff, 0)
  2623. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2624. this[offset] = (value >>> 24)
  2625. this[offset + 1] = (value >>> 16)
  2626. this[offset + 2] = (value >>> 8)
  2627. this[offset + 3] = value
  2628. } else objectWriteUInt32(this, value, offset, false)
  2629. return offset + 4
  2630. }
  2631. Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
  2632. value = +value
  2633. offset = offset >>> 0
  2634. if (!noAssert)
  2635. checkInt(this, value, offset, 1, 0x7f, -0x80)
  2636. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  2637. if (value < 0) value = 0xff + value + 1
  2638. this[offset] = value
  2639. return offset + 1
  2640. }
  2641. Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
  2642. value = +value
  2643. offset = offset >>> 0
  2644. if (!noAssert)
  2645. checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  2646. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2647. this[offset] = value
  2648. this[offset + 1] = (value >>> 8)
  2649. } else objectWriteUInt16(this, value, offset, true)
  2650. return offset + 2
  2651. }
  2652. Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
  2653. value = +value
  2654. offset = offset >>> 0
  2655. if (!noAssert)
  2656. checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  2657. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2658. this[offset] = (value >>> 8)
  2659. this[offset + 1] = value
  2660. } else objectWriteUInt16(this, value, offset, false)
  2661. return offset + 2
  2662. }
  2663. Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
  2664. value = +value
  2665. offset = offset >>> 0
  2666. if (!noAssert)
  2667. checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  2668. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2669. this[offset] = value
  2670. this[offset + 1] = (value >>> 8)
  2671. this[offset + 2] = (value >>> 16)
  2672. this[offset + 3] = (value >>> 24)
  2673. } else objectWriteUInt32(this, value, offset, true)
  2674. return offset + 4
  2675. }
  2676. Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
  2677. value = +value
  2678. offset = offset >>> 0
  2679. if (!noAssert)
  2680. checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  2681. if (value < 0) value = 0xffffffff + value + 1
  2682. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2683. this[offset] = (value >>> 24)
  2684. this[offset + 1] = (value >>> 16)
  2685. this[offset + 2] = (value >>> 8)
  2686. this[offset + 3] = value
  2687. } else objectWriteUInt32(this, value, offset, false)
  2688. return offset + 4
  2689. }
  2690. function checkIEEE754 (buf, value, offset, ext, max, min) {
  2691. if (value > max || value < min) throw new TypeError('value is out of bounds')
  2692. if (offset + ext > buf.length) throw new TypeError('index out of range')
  2693. }
  2694. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  2695. if (!noAssert)
  2696. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  2697. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  2698. return offset + 4
  2699. }
  2700. Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
  2701. return writeFloat(this, value, offset, true, noAssert)
  2702. }
  2703. Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
  2704. return writeFloat(this, value, offset, false, noAssert)
  2705. }
  2706. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  2707. if (!noAssert)
  2708. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  2709. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  2710. return offset + 8
  2711. }
  2712. Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
  2713. return writeDouble(this, value, offset, true, noAssert)
  2714. }
  2715. Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
  2716. return writeDouble(this, value, offset, false, noAssert)
  2717. }
  2718. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  2719. Buffer.prototype.copy = function (target, target_start, start, end) {
  2720. var source = this
  2721. if (!start) start = 0
  2722. if (!end && end !== 0) end = this.length
  2723. if (!target_start) target_start = 0
  2724. // Copy 0 bytes; we're done
  2725. if (end === start) return
  2726. if (target.length === 0 || source.length === 0) return
  2727. // Fatal error conditions
  2728. if (end < start) throw new TypeError('sourceEnd < sourceStart')
  2729. if (target_start < 0 || target_start >= target.length)
  2730. throw new TypeError('targetStart out of bounds')
  2731. if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds')
  2732. if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds')
  2733. // Are we oob?
  2734. if (end > this.length)
  2735. end = this.length
  2736. if (target.length - target_start < end - start)
  2737. end = target.length - target_start + start
  2738. var len = end - start
  2739. if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  2740. for (var i = 0; i < len; i++) {
  2741. target[i + target_start] = this[i + start]
  2742. }
  2743. } else {
  2744. target._set(this.subarray(start, start + len), target_start)
  2745. }
  2746. }
  2747. // fill(value, start=0, end=buffer.length)
  2748. Buffer.prototype.fill = function (value, start, end) {
  2749. if (!value) value = 0
  2750. if (!start) start = 0
  2751. if (!end) end = this.length
  2752. if (end < start) throw new TypeError('end < start')
  2753. // Fill 0 bytes; we're done
  2754. if (end === start) return
  2755. if (this.length === 0) return
  2756. if (start < 0 || start >= this.length) throw new TypeError('start out of bounds')
  2757. if (end < 0 || end > this.length) throw new TypeError('end out of bounds')
  2758. var i
  2759. if (typeof value === 'number') {
  2760. for (i = start; i < end; i++) {
  2761. this[i] = value
  2762. }
  2763. } else {
  2764. var bytes = utf8ToBytes(value.toString())
  2765. var len = bytes.length
  2766. for (i = start; i < end; i++) {
  2767. this[i] = bytes[i % len]
  2768. }
  2769. }
  2770. return this
  2771. }
  2772. /**
  2773. * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
  2774. * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
  2775. */
  2776. Buffer.prototype.toArrayBuffer = function () {
  2777. if (typeof Uint8Array !== 'undefined') {
  2778. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2779. return (new Buffer(this)).buffer
  2780. } else {
  2781. var buf = new Uint8Array(this.length)
  2782. for (var i = 0, len = buf.length; i < len; i += 1) {
  2783. buf[i] = this[i]
  2784. }
  2785. return buf.buffer
  2786. }
  2787. } else {
  2788. throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
  2789. }
  2790. }
  2791. // HELPER FUNCTIONS
  2792. // ================
  2793. var BP = Buffer.prototype
  2794. /**
  2795. * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
  2796. */
  2797. Buffer._augment = function (arr) {
  2798. arr.constructor = Buffer
  2799. arr._isBuffer = true
  2800. // save reference to original Uint8Array get/set methods before overwriting
  2801. arr._get = arr.get
  2802. arr._set = arr.set
  2803. // deprecated, will be removed in node 0.13+
  2804. arr.get = BP.get
  2805. arr.set = BP.set
  2806. arr.write = BP.write
  2807. arr.toString = BP.toString
  2808. arr.toLocaleString = BP.toString
  2809. arr.toJSON = BP.toJSON
  2810. arr.equals = BP.equals
  2811. arr.compare = BP.compare
  2812. arr.copy = BP.copy
  2813. arr.slice = BP.slice
  2814. arr.readUInt8 = BP.readUInt8
  2815. arr.readUInt16LE = BP.readUInt16LE
  2816. arr.readUInt16BE = BP.readUInt16BE
  2817. arr.readUInt32LE = BP.readUInt32LE
  2818. arr.readUInt32BE = BP.readUInt32BE
  2819. arr.readInt8 = BP.readInt8
  2820. arr.readInt16LE = BP.readInt16LE
  2821. arr.readInt16BE = BP.readInt16BE
  2822. arr.readInt32LE = BP.readInt32LE
  2823. arr.readInt32BE = BP.readInt32BE
  2824. arr.readFloatLE = BP.readFloatLE
  2825. arr.readFloatBE = BP.readFloatBE
  2826. arr.readDoubleLE = BP.readDoubleLE
  2827. arr.readDoubleBE = BP.readDoubleBE
  2828. arr.writeUInt8 = BP.writeUInt8
  2829. arr.writeUInt16LE = BP.writeUInt16LE
  2830. arr.writeUInt16BE = BP.writeUInt16BE
  2831. arr.writeUInt32LE = BP.writeUInt32LE
  2832. arr.writeUInt32BE = BP.writeUInt32BE
  2833. arr.writeInt8 = BP.writeInt8
  2834. arr.writeInt16LE = BP.writeInt16LE
  2835. arr.writeInt16BE = BP.writeInt16BE
  2836. arr.writeInt32LE = BP.writeInt32LE
  2837. arr.writeInt32BE = BP.writeInt32BE
  2838. arr.writeFloatLE = BP.writeFloatLE
  2839. arr.writeFloatBE = BP.writeFloatBE
  2840. arr.writeDoubleLE = BP.writeDoubleLE
  2841. arr.writeDoubleBE = BP.writeDoubleBE
  2842. arr.fill = BP.fill
  2843. arr.inspect = BP.inspect
  2844. arr.toArrayBuffer = BP.toArrayBuffer
  2845. return arr
  2846. }
  2847. var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
  2848. function base64clean (str) {
  2849. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2850. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  2851. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2852. while (str.length % 4 !== 0) {
  2853. str = str + '='
  2854. }
  2855. return str
  2856. }
  2857. function stringtrim (str) {
  2858. if (str.trim) return str.trim()
  2859. return str.replace(/^\s+|\s+$/g, '')
  2860. }
  2861. function isArrayish (subject) {
  2862. return isArray(subject) || Buffer.isBuffer(subject) ||
  2863. subject && typeof subject === 'object' &&
  2864. typeof subject.length === 'number'
  2865. }
  2866. function toHex (n) {
  2867. if (n < 16) return '0' + n.toString(16)
  2868. return n.toString(16)
  2869. }
  2870. function utf8ToBytes (str) {
  2871. var byteArray = []
  2872. for (var i = 0; i < str.length; i++) {
  2873. var b = str.charCodeAt(i)
  2874. if (b <= 0x7F) {
  2875. byteArray.push(b)
  2876. } else {
  2877. var start = i
  2878. if (b >= 0xD800 && b <= 0xDFFF) i++
  2879. var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
  2880. for (var j = 0; j < h.length; j++) {
  2881. byteArray.push(parseInt(h[j], 16))
  2882. }
  2883. }
  2884. }
  2885. return byteArray
  2886. }
  2887. function asciiToBytes (str) {
  2888. var byteArray = []
  2889. for (var i = 0; i < str.length; i++) {
  2890. // Node's code seems to be doing this and not & 0x7F..
  2891. byteArray.push(str.charCodeAt(i) & 0xFF)
  2892. }
  2893. return byteArray
  2894. }
  2895. function utf16leToBytes (str) {
  2896. var c, hi, lo
  2897. var byteArray = []
  2898. for (var i = 0; i < str.length; i++) {
  2899. c = str.charCodeAt(i)
  2900. hi = c >> 8
  2901. lo = c % 256
  2902. byteArray.push(lo)
  2903. byteArray.push(hi)
  2904. }
  2905. return byteArray
  2906. }
  2907. function base64ToBytes (str) {
  2908. return base64.toByteArray(str)
  2909. }
  2910. function blitBuffer (src, dst, offset, length, unitSize) {
  2911. if (unitSize) length -= length % unitSize;
  2912. for (var i = 0; i < length; i++) {
  2913. if ((i + offset >= dst.length) || (i >= src.length))
  2914. break
  2915. dst[i + offset] = src[i]
  2916. }
  2917. return i
  2918. }
  2919. function decodeUtf8Char (str) {
  2920. try {
  2921. return decodeURIComponent(str)
  2922. } catch (err) {
  2923. return String.fromCharCode(0xFFFD) // UTF 8 invalid char
  2924. }
  2925. }
  2926. },{"base64-js":2,"ieee754":3,"is-array":4}],2:[function(_dereq_,module,exports){
  2927. var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  2928. ;(function (exports) {
  2929. 'use strict';
  2930. var Arr = (typeof Uint8Array !== 'undefined')
  2931. ? Uint8Array
  2932. : Array
  2933. var PLUS = '+'.charCodeAt(0)
  2934. var SLASH = '/'.charCodeAt(0)
  2935. var NUMBER = '0'.charCodeAt(0)
  2936. var LOWER = 'a'.charCodeAt(0)
  2937. var UPPER = 'A'.charCodeAt(0)
  2938. function decode (elt) {
  2939. var code = elt.charCodeAt(0)
  2940. if (code === PLUS)
  2941. return 62 // '+'
  2942. if (code === SLASH)
  2943. return 63 // '/'
  2944. if (code < NUMBER)
  2945. return -1 //no match
  2946. if (code < NUMBER + 10)
  2947. return code - NUMBER + 26 + 26
  2948. if (code < UPPER + 26)
  2949. return code - UPPER
  2950. if (code < LOWER + 26)
  2951. return code - LOWER + 26
  2952. }
  2953. function b64ToByteArray (b64) {
  2954. var i, j, l, tmp, placeHolders, arr
  2955. if (b64.length % 4 > 0) {
  2956. throw new Error('Invalid string. Length must be a multiple of 4')
  2957. }
  2958. // the number of equal signs (place holders)
  2959. // if there are two placeholders, than the two characters before it
  2960. // represent one byte
  2961. // if there is only one, then the three characters before it represent 2 bytes
  2962. // this is just a cheap hack to not do indexOf twice
  2963. var len = b64.length
  2964. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
  2965. // base64 is 4/3 + up to two characters of the original data
  2966. arr = new Arr(b64.length * 3 / 4 - placeHolders)
  2967. // if there are placeholders, only get up to the last complete 4 chars
  2968. l = placeHolders > 0 ? b64.length - 4 : b64.length
  2969. var L = 0
  2970. function push (v) {
  2971. arr[L++] = v
  2972. }
  2973. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  2974. tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
  2975. push((tmp & 0xFF0000) >> 16)
  2976. push((tmp & 0xFF00) >> 8)
  2977. push(tmp & 0xFF)
  2978. }
  2979. if (placeHolders === 2) {
  2980. tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
  2981. push(tmp & 0xFF)
  2982. } else if (placeHolders === 1) {
  2983. tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
  2984. push((tmp >> 8) & 0xFF)
  2985. push(tmp & 0xFF)
  2986. }
  2987. return arr
  2988. }
  2989. function uint8ToBase64 (uint8) {
  2990. var i,
  2991. extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
  2992. output = "",
  2993. temp, length
  2994. function encode (num) {
  2995. return lookup.charAt(num)
  2996. }
  2997. function tripletToBase64 (num) {
  2998. return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
  2999. }
  3000. // go through the array every three bytes, we'll deal with trailing stuff later
  3001. for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
  3002. temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  3003. output += tripletToBase64(temp)
  3004. }
  3005. // pad the end with zeros, but make sure to not forget the extra bytes
  3006. switch (extraBytes) {
  3007. case 1:
  3008. temp = uint8[uint8.length - 1]
  3009. output += encode(temp >> 2)
  3010. output += encode((temp << 4) & 0x3F)
  3011. output += '=='
  3012. break
  3013. case 2:
  3014. temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
  3015. output += encode(temp >> 10)
  3016. output += encode((temp >> 4) & 0x3F)
  3017. output += encode((temp << 2) & 0x3F)
  3018. output += '='
  3019. break
  3020. }
  3021. return output
  3022. }
  3023. exports.toByteArray = b64ToByteArray
  3024. exports.fromByteArray = uint8ToBase64
  3025. }(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
  3026. },{}],3:[function(_dereq_,module,exports){
  3027. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  3028. var e, m
  3029. var eLen = nBytes * 8 - mLen - 1
  3030. var eMax = (1 << eLen) - 1
  3031. var eBias = eMax >> 1
  3032. var nBits = -7
  3033. var i = isLE ? (nBytes - 1) : 0
  3034. var d = isLE ? -1 : 1
  3035. var s = buffer[offset + i]
  3036. i += d
  3037. e = s & ((1 << (-nBits)) - 1)
  3038. s >>= (-nBits)
  3039. nBits += eLen
  3040. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  3041. m = e & ((1 << (-nBits)) - 1)
  3042. e >>= (-nBits)
  3043. nBits += mLen
  3044. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  3045. if (e === 0) {
  3046. e = 1 - eBias
  3047. } else if (e === eMax) {
  3048. return m ? NaN : ((s ? -1 : 1) * Infinity)
  3049. } else {
  3050. m = m + Math.pow(2, mLen)
  3051. e = e - eBias
  3052. }
  3053. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  3054. }
  3055. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  3056. var e, m, c
  3057. var eLen = nBytes * 8 - mLen - 1
  3058. var eMax = (1 << eLen) - 1
  3059. var eBias = eMax >> 1
  3060. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  3061. var i = isLE ? 0 : (nBytes - 1)
  3062. var d = isLE ? 1 : -1
  3063. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  3064. value = Math.abs(value)
  3065. if (isNaN(value) || value === Infinity) {
  3066. m = isNaN(value) ? 1 : 0
  3067. e = eMax
  3068. } else {
  3069. e = Math.floor(Math.log(value) / Math.LN2)
  3070. if (value * (c = Math.pow(2, -e)) < 1) {
  3071. e--
  3072. c *= 2
  3073. }
  3074. if (e + eBias >= 1) {
  3075. value += rt / c
  3076. } else {
  3077. value += rt * Math.pow(2, 1 - eBias)
  3078. }
  3079. if (value * c >= 2) {
  3080. e++
  3081. c /= 2
  3082. }
  3083. if (e + eBias >= eMax) {
  3084. m = 0
  3085. e = eMax
  3086. } else if (e + eBias >= 1) {
  3087. m = (value * c - 1) * Math.pow(2, mLen)
  3088. e = e + eBias
  3089. } else {
  3090. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  3091. e = 0
  3092. }
  3093. }
  3094. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  3095. e = (e << mLen) | m
  3096. eLen += mLen
  3097. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  3098. buffer[offset + i - d] |= s * 128
  3099. }
  3100. },{}],4:[function(_dereq_,module,exports){
  3101. /**
  3102. * isArray
  3103. */
  3104. var isArray = Array.isArray;
  3105. /**
  3106. * toString
  3107. */
  3108. var str = Object.prototype.toString;
  3109. /**
  3110. * Whether or not the given `val`
  3111. * is an array.
  3112. *
  3113. * example:
  3114. *
  3115. * isArray([]);
  3116. * // > true
  3117. * isArray(arguments);
  3118. * // > false
  3119. * isArray('');
  3120. * // > false
  3121. *
  3122. * @param {mixed} val
  3123. * @return {bool}
  3124. */
  3125. module.exports = isArray || function (val) {
  3126. return !! val && '[object Array]' == str.call(val);
  3127. };
  3128. },{}],5:[function(_dereq_,module,exports){
  3129. 'use strict';
  3130. var DataReader = _dereq_('./dataReader');
  3131. function ArrayReader(data) {
  3132. if (data) {
  3133. this.data = data;
  3134. this.length = this.data.length;
  3135. this.index = 0;
  3136. this.zero = 0;
  3137. for(var i = 0; i < this.data.length; i++) {
  3138. data[i] = data[i] & 0xFF;
  3139. }
  3140. }
  3141. }
  3142. ArrayReader.prototype = new DataReader();
  3143. /**
  3144. * @see DataReader.byteAt
  3145. */
  3146. ArrayReader.prototype.byteAt = function(i) {
  3147. return this.data[this.zero + i];
  3148. };
  3149. /**
  3150. * @see DataReader.lastIndexOfSignature
  3151. */
  3152. ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  3153. var sig0 = sig.charCodeAt(0),
  3154. sig1 = sig.charCodeAt(1),
  3155. sig2 = sig.charCodeAt(2),
  3156. sig3 = sig.charCodeAt(3);
  3157. for (var i = this.length - 4; i >= 0; --i) {
  3158. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  3159. return i - this.zero;
  3160. }
  3161. }
  3162. return -1;
  3163. };
  3164. /**
  3165. * @see DataReader.readData
  3166. */
  3167. ArrayReader.prototype.readData = function(size) {
  3168. this.checkOffset(size);
  3169. if(size === 0) {
  3170. return [];
  3171. }
  3172. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  3173. this.index += size;
  3174. return result;
  3175. };
  3176. module.exports = ArrayReader;
  3177. },{"./dataReader":10}],6:[function(_dereq_,module,exports){
  3178. 'use strict';
  3179. // private property
  3180. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3181. // public method for encoding
  3182. exports.encode = function(input, utf8) {
  3183. var output = "";
  3184. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3185. var i = 0;
  3186. while (i < input.length) {
  3187. chr1 = input.charCodeAt(i++);
  3188. chr2 = input.charCodeAt(i++);
  3189. chr3 = input.charCodeAt(i++);
  3190. enc1 = chr1 >> 2;
  3191. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3192. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3193. enc4 = chr3 & 63;
  3194. if (isNaN(chr2)) {
  3195. enc3 = enc4 = 64;
  3196. }
  3197. else if (isNaN(chr3)) {
  3198. enc4 = 64;
  3199. }
  3200. output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  3201. }
  3202. return output;
  3203. };
  3204. // public method for decoding
  3205. exports.decode = function(input, utf8) {
  3206. var output = "";
  3207. var chr1, chr2, chr3;
  3208. var enc1, enc2, enc3, enc4;
  3209. var i = 0;
  3210. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  3211. while (i < input.length) {
  3212. enc1 = _keyStr.indexOf(input.charAt(i++));
  3213. enc2 = _keyStr.indexOf(input.charAt(i++));
  3214. enc3 = _keyStr.indexOf(input.charAt(i++));
  3215. enc4 = _keyStr.indexOf(input.charAt(i++));
  3216. chr1 = (enc1 << 2) | (enc2 >> 4);
  3217. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  3218. chr3 = ((enc3 & 3) << 6) | enc4;
  3219. output = output + String.fromCharCode(chr1);
  3220. if (enc3 != 64) {
  3221. output = output + String.fromCharCode(chr2);
  3222. }
  3223. if (enc4 != 64) {
  3224. output = output + String.fromCharCode(chr3);
  3225. }
  3226. }
  3227. return output;
  3228. };
  3229. },{}],7:[function(_dereq_,module,exports){
  3230. 'use strict';
  3231. function CompressedObject() {
  3232. this.compressedSize = 0;
  3233. this.uncompressedSize = 0;
  3234. this.crc32 = 0;
  3235. this.compressionMethod = null;
  3236. this.compressedContent = null;
  3237. }
  3238. CompressedObject.prototype = {
  3239. /**
  3240. * Return the decompressed content in an unspecified format.
  3241. * The format will depend on the decompressor.
  3242. * @return {Object} the decompressed content.
  3243. */
  3244. getContent: function() {
  3245. return null; // see implementation
  3246. },
  3247. /**
  3248. * Return the compressed content in an unspecified format.
  3249. * The format will depend on the compressed conten source.
  3250. * @return {Object} the compressed content.
  3251. */
  3252. getCompressedContent: function() {
  3253. return null; // see implementation
  3254. }
  3255. };
  3256. module.exports = CompressedObject;
  3257. },{}],8:[function(_dereq_,module,exports){
  3258. 'use strict';
  3259. exports.STORE = {
  3260. magic: "\x00\x00",
  3261. compress: function(content, compressionOptions) {
  3262. return content; // no compression
  3263. },
  3264. uncompress: function(content) {
  3265. return content; // no compression
  3266. },
  3267. compressInputType: null,
  3268. uncompressInputType: null
  3269. };
  3270. exports.DEFLATE = _dereq_('./flate');
  3271. },{"./flate":13}],9:[function(_dereq_,module,exports){
  3272. 'use strict';
  3273. var utils = _dereq_('./utils');
  3274. var table = [
  3275. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
  3276. 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  3277. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
  3278. 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  3279. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
  3280. 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  3281. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
  3282. 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  3283. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
  3284. 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  3285. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
  3286. 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  3287. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
  3288. 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  3289. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
  3290. 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  3291. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
  3292. 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  3293. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
  3294. 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  3295. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
  3296. 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  3297. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
  3298. 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  3299. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
  3300. 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  3301. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
  3302. 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  3303. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
  3304. 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  3305. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
  3306. 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  3307. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
  3308. 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  3309. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
  3310. 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  3311. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
  3312. 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  3313. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
  3314. 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  3315. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
  3316. 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  3317. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
  3318. 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  3319. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
  3320. 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  3321. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
  3322. 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  3323. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
  3324. 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  3325. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
  3326. 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  3327. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
  3328. 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  3329. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
  3330. 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  3331. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
  3332. 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  3333. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
  3334. 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  3335. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
  3336. 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  3337. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
  3338. 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  3339. ];
  3340. /**
  3341. *
  3342. * Javascript crc32
  3343. * http://www.webtoolkit.info/
  3344. *
  3345. */
  3346. module.exports = function crc32(input, crc) {
  3347. if (typeof input === "undefined" || !input.length) {
  3348. return 0;
  3349. }
  3350. var isArray = utils.getTypeOf(input) !== "string";
  3351. if (typeof(crc) == "undefined") {
  3352. crc = 0;
  3353. }
  3354. var x = 0;
  3355. var y = 0;
  3356. var b = 0;
  3357. crc = crc ^ (-1);
  3358. for (var i = 0, iTop = input.length; i < iTop; i++) {
  3359. b = isArray ? input[i] : input.charCodeAt(i);
  3360. y = (crc ^ b) & 0xFF;
  3361. x = table[y];
  3362. crc = (crc >>> 8) ^ x;
  3363. }
  3364. return crc ^ (-1);
  3365. };
  3366. // vim: set shiftwidth=4 softtabstop=4:
  3367. },{"./utils":26}],10:[function(_dereq_,module,exports){
  3368. 'use strict';
  3369. var utils = _dereq_('./utils');
  3370. function DataReader(data) {
  3371. this.data = null; // type : see implementation
  3372. this.length = 0;
  3373. this.index = 0;
  3374. this.zero = 0;
  3375. }
  3376. DataReader.prototype = {
  3377. /**
  3378. * Check that the offset will not go too far.
  3379. * @param {string} offset the additional offset to check.
  3380. * @throws {Error} an Error if the offset is out of bounds.
  3381. */
  3382. checkOffset: function(offset) {
  3383. this.checkIndex(this.index + offset);
  3384. },
  3385. /**
  3386. * Check that the specifed index will not be too far.
  3387. * @param {string} newIndex the index to check.
  3388. * @throws {Error} an Error if the index is out of bounds.
  3389. */
  3390. checkIndex: function(newIndex) {
  3391. if (this.length < this.zero + newIndex || newIndex < 0) {
  3392. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  3393. }
  3394. },
  3395. /**
  3396. * Change the index.
  3397. * @param {number} newIndex The new index.
  3398. * @throws {Error} if the new index is out of the data.
  3399. */
  3400. setIndex: function(newIndex) {
  3401. this.checkIndex(newIndex);
  3402. this.index = newIndex;
  3403. },
  3404. /**
  3405. * Skip the next n bytes.
  3406. * @param {number} n the number of bytes to skip.
  3407. * @throws {Error} if the new index is out of the data.
  3408. */
  3409. skip: function(n) {
  3410. this.setIndex(this.index + n);
  3411. },
  3412. /**
  3413. * Get the byte at the specified index.
  3414. * @param {number} i the index to use.
  3415. * @return {number} a byte.
  3416. */
  3417. byteAt: function(i) {
  3418. // see implementations
  3419. },
  3420. /**
  3421. * Get the next number with a given byte size.
  3422. * @param {number} size the number of bytes to read.
  3423. * @return {number} the corresponding number.
  3424. */
  3425. readInt: function(size) {
  3426. var result = 0,
  3427. i;
  3428. this.checkOffset(size);
  3429. for (i = this.index + size - 1; i >= this.index; i--) {
  3430. result = (result << 8) + this.byteAt(i);
  3431. }
  3432. this.index += size;
  3433. return result;
  3434. },
  3435. /**
  3436. * Get the next string with a given byte size.
  3437. * @param {number} size the number of bytes to read.
  3438. * @return {string} the corresponding string.
  3439. */
  3440. readString: function(size) {
  3441. return utils.transformTo("string", this.readData(size));
  3442. },
  3443. /**
  3444. * Get raw data without conversion, <size> bytes.
  3445. * @param {number} size the number of bytes to read.
  3446. * @return {Object} the raw data, implementation specific.
  3447. */
  3448. readData: function(size) {
  3449. // see implementations
  3450. },
  3451. /**
  3452. * Find the last occurence of a zip signature (4 bytes).
  3453. * @param {string} sig the signature to find.
  3454. * @return {number} the index of the last occurence, -1 if not found.
  3455. */
  3456. lastIndexOfSignature: function(sig) {
  3457. // see implementations
  3458. },
  3459. /**
  3460. * Get the next date.
  3461. * @return {Date} the date.
  3462. */
  3463. readDate: function() {
  3464. var dostime = this.readInt(4);
  3465. return new Date(
  3466. ((dostime >> 25) & 0x7f) + 1980, // year
  3467. ((dostime >> 21) & 0x0f) - 1, // month
  3468. (dostime >> 16) & 0x1f, // day
  3469. (dostime >> 11) & 0x1f, // hour
  3470. (dostime >> 5) & 0x3f, // minute
  3471. (dostime & 0x1f) << 1); // second
  3472. }
  3473. };
  3474. module.exports = DataReader;
  3475. },{"./utils":26}],11:[function(_dereq_,module,exports){
  3476. 'use strict';
  3477. exports.base64 = false;
  3478. exports.binary = false;
  3479. exports.dir = false;
  3480. exports.createFolders = false;
  3481. exports.date = null;
  3482. exports.compression = null;
  3483. exports.compressionOptions = null;
  3484. exports.comment = null;
  3485. exports.unixPermissions = null;
  3486. exports.dosPermissions = null;
  3487. },{}],12:[function(_dereq_,module,exports){
  3488. 'use strict';
  3489. var utils = _dereq_('./utils');
  3490. /**
  3491. * @deprecated
  3492. * This function will be removed in a future version without replacement.
  3493. */
  3494. exports.string2binary = function(str) {
  3495. return utils.string2binary(str);
  3496. };
  3497. /**
  3498. * @deprecated
  3499. * This function will be removed in a future version without replacement.
  3500. */
  3501. exports.string2Uint8Array = function(str) {
  3502. return utils.transformTo("uint8array", str);
  3503. };
  3504. /**
  3505. * @deprecated
  3506. * This function will be removed in a future version without replacement.
  3507. */
  3508. exports.uint8Array2String = function(array) {
  3509. return utils.transformTo("string", array);
  3510. };
  3511. /**
  3512. * @deprecated
  3513. * This function will be removed in a future version without replacement.
  3514. */
  3515. exports.string2Blob = function(str) {
  3516. var buffer = utils.transformTo("arraybuffer", str);
  3517. return utils.arrayBuffer2Blob(buffer);
  3518. };
  3519. /**
  3520. * @deprecated
  3521. * This function will be removed in a future version without replacement.
  3522. */
  3523. exports.arrayBuffer2Blob = function(buffer) {
  3524. return utils.arrayBuffer2Blob(buffer);
  3525. };
  3526. /**
  3527. * @deprecated
  3528. * This function will be removed in a future version without replacement.
  3529. */
  3530. exports.transformTo = function(outputType, input) {
  3531. return utils.transformTo(outputType, input);
  3532. };
  3533. /**
  3534. * @deprecated
  3535. * This function will be removed in a future version without replacement.
  3536. */
  3537. exports.getTypeOf = function(input) {
  3538. return utils.getTypeOf(input);
  3539. };
  3540. /**
  3541. * @deprecated
  3542. * This function will be removed in a future version without replacement.
  3543. */
  3544. exports.checkSupport = function(type) {
  3545. return utils.checkSupport(type);
  3546. };
  3547. /**
  3548. * @deprecated
  3549. * This value will be removed in a future version without replacement.
  3550. */
  3551. exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
  3552. /**
  3553. * @deprecated
  3554. * This value will be removed in a future version without replacement.
  3555. */
  3556. exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
  3557. /**
  3558. * @deprecated
  3559. * This function will be removed in a future version without replacement.
  3560. */
  3561. exports.pretty = function(str) {
  3562. return utils.pretty(str);
  3563. };
  3564. /**
  3565. * @deprecated
  3566. * This function will be removed in a future version without replacement.
  3567. */
  3568. exports.findCompression = function(compressionMethod) {
  3569. return utils.findCompression(compressionMethod);
  3570. };
  3571. /**
  3572. * @deprecated
  3573. * This function will be removed in a future version without replacement.
  3574. */
  3575. exports.isRegExp = function (object) {
  3576. return utils.isRegExp(object);
  3577. };
  3578. },{"./utils":26}],13:[function(_dereq_,module,exports){
  3579. 'use strict';
  3580. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  3581. var pako = _dereq_("pako");
  3582. exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  3583. exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  3584. exports.magic = "\x08\x00";
  3585. exports.compress = function(input, compressionOptions) {
  3586. return pako.deflateRaw(input, {
  3587. level : compressionOptions.level || -1 // default compression
  3588. });
  3589. };
  3590. exports.uncompress = function(input) {
  3591. return pako.inflateRaw(input);
  3592. };
  3593. },{"pako":29}],14:[function(_dereq_,module,exports){
  3594. 'use strict';
  3595. var base64 = _dereq_('./base64');
  3596. /**
  3597. Usage:
  3598. zip = new JSZip();
  3599. zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
  3600. zip.folder("images").file("smile.gif", base64Data, {base64: true});
  3601. zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
  3602. zip.remove("tempfile");
  3603. base64zip = zip.generate();
  3604. **/
  3605. /**
  3606. * Representation a of zip file in js
  3607. * @constructor
  3608. * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
  3609. * @param {Object=} options the options for creating this objects (optional).
  3610. */
  3611. function JSZip(data, options) {
  3612. // if this constructor is used without `new`, it adds `new` before itself:
  3613. if(!(this instanceof JSZip)) return new JSZip(data, options);
  3614. // object containing the files :
  3615. // {
  3616. // "folder/" : {...},
  3617. // "folder/data.txt" : {...}
  3618. // }
  3619. this.files = {};
  3620. this.comment = null;
  3621. // Where we are in the hierarchy
  3622. this.root = "";
  3623. if (data) {
  3624. this.load(data, options);
  3625. }
  3626. this.clone = function() {
  3627. var newObj = new JSZip();
  3628. for (var i in this) {
  3629. if (typeof this[i] !== "function") {
  3630. newObj[i] = this[i];
  3631. }
  3632. }
  3633. return newObj;
  3634. };
  3635. }
  3636. JSZip.prototype = _dereq_('./object');
  3637. JSZip.prototype.load = _dereq_('./load');
  3638. JSZip.support = _dereq_('./support');
  3639. JSZip.defaults = _dereq_('./defaults');
  3640. /**
  3641. * @deprecated
  3642. * This namespace will be removed in a future version without replacement.
  3643. */
  3644. JSZip.utils = _dereq_('./deprecatedPublicUtils');
  3645. JSZip.base64 = {
  3646. /**
  3647. * @deprecated
  3648. * This method will be removed in a future version without replacement.
  3649. */
  3650. encode : function(input) {
  3651. return base64.encode(input);
  3652. },
  3653. /**
  3654. * @deprecated
  3655. * This method will be removed in a future version without replacement.
  3656. */
  3657. decode : function(input) {
  3658. return base64.decode(input);
  3659. }
  3660. };
  3661. JSZip.compressions = _dereq_('./compressions');
  3662. module.exports = JSZip;
  3663. },{"./base64":6,"./compressions":8,"./defaults":11,"./deprecatedPublicUtils":12,"./load":15,"./object":18,"./support":22}],15:[function(_dereq_,module,exports){
  3664. 'use strict';
  3665. var base64 = _dereq_('./base64');
  3666. var utf8 = _dereq_('./utf8');
  3667. var utils = _dereq_('./utils');
  3668. var ZipEntries = _dereq_('./zipEntries');
  3669. module.exports = function(data, options) {
  3670. var files, zipEntries, i, input;
  3671. options = utils.extend(options || {}, {
  3672. base64: false,
  3673. checkCRC32: false,
  3674. optimizedBinaryString : false,
  3675. createFolders: false,
  3676. decodeFileName: utf8.utf8decode
  3677. });
  3678. if (options.base64) {
  3679. data = base64.decode(data);
  3680. }
  3681. zipEntries = new ZipEntries(data, options);
  3682. files = zipEntries.files;
  3683. for (i = 0; i < files.length; i++) {
  3684. input = files[i];
  3685. this.file(input.fileNameStr, input.decompressed, {
  3686. binary: true,
  3687. optimizedBinaryString: true,
  3688. date: input.date,
  3689. dir: input.dir,
  3690. comment : input.fileCommentStr.length ? input.fileCommentStr : null,
  3691. unixPermissions : input.unixPermissions,
  3692. dosPermissions : input.dosPermissions,
  3693. createFolders: options.createFolders
  3694. });
  3695. }
  3696. if (zipEntries.zipComment.length) {
  3697. this.comment = zipEntries.zipComment;
  3698. }
  3699. return this;
  3700. };
  3701. },{"./base64":6,"./utf8":25,"./utils":26,"./zipEntries":27}],16:[function(_dereq_,module,exports){
  3702. (function (Buffer){
  3703. 'use strict';
  3704. module.exports = function(data, encoding){
  3705. return new Buffer(data, encoding);
  3706. };
  3707. module.exports.test = function(b){
  3708. return Buffer.isBuffer(b);
  3709. };
  3710. }).call(this,_dereq_("buffer").Buffer)
  3711. },{"buffer":1}],17:[function(_dereq_,module,exports){
  3712. 'use strict';
  3713. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  3714. function NodeBufferReader(data) {
  3715. this.data = data;
  3716. this.length = this.data.length;
  3717. this.index = 0;
  3718. this.zero = 0;
  3719. }
  3720. NodeBufferReader.prototype = new Uint8ArrayReader();
  3721. /**
  3722. * @see DataReader.readData
  3723. */
  3724. NodeBufferReader.prototype.readData = function(size) {
  3725. this.checkOffset(size);
  3726. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  3727. this.index += size;
  3728. return result;
  3729. };
  3730. module.exports = NodeBufferReader;
  3731. },{"./uint8ArrayReader":23}],18:[function(_dereq_,module,exports){
  3732. 'use strict';
  3733. var support = _dereq_('./support');
  3734. var utils = _dereq_('./utils');
  3735. var crc32 = _dereq_('./crc32');
  3736. var signature = _dereq_('./signature');
  3737. var defaults = _dereq_('./defaults');
  3738. var base64 = _dereq_('./base64');
  3739. var compressions = _dereq_('./compressions');
  3740. var CompressedObject = _dereq_('./compressedObject');
  3741. var nodeBuffer = _dereq_('./nodeBuffer');
  3742. var utf8 = _dereq_('./utf8');
  3743. var StringWriter = _dereq_('./stringWriter');
  3744. var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter');
  3745. /**
  3746. * Returns the raw data of a ZipObject, decompress the content if necessary.
  3747. * @param {ZipObject} file the file to use.
  3748. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  3749. */
  3750. var getRawData = function(file) {
  3751. if (file._data instanceof CompressedObject) {
  3752. file._data = file._data.getContent();
  3753. file.options.binary = true;
  3754. file.options.base64 = false;
  3755. if (utils.getTypeOf(file._data) === "uint8array") {
  3756. var copy = file._data;
  3757. // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
  3758. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
  3759. file._data = new Uint8Array(copy.length);
  3760. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  3761. if (copy.length !== 0) {
  3762. file._data.set(copy, 0);
  3763. }
  3764. }
  3765. }
  3766. return file._data;
  3767. };
  3768. /**
  3769. * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
  3770. * @param {ZipObject} file the file to use.
  3771. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  3772. */
  3773. var getBinaryData = function(file) {
  3774. var result = getRawData(file),
  3775. type = utils.getTypeOf(result);
  3776. if (type === "string") {
  3777. if (!file.options.binary) {
  3778. // unicode text !
  3779. // unicode string => binary string is a painful process, check if we can avoid it.
  3780. if (support.nodebuffer) {
  3781. return nodeBuffer(result, "utf-8");
  3782. }
  3783. }
  3784. return file.asBinary();
  3785. }
  3786. return result;
  3787. };
  3788. /**
  3789. * Transform this._data into a string.
  3790. * @param {function} filter a function String -> String, applied if not null on the result.
  3791. * @return {String} the string representing this._data.
  3792. */
  3793. var dataToString = function(asUTF8) {
  3794. var result = getRawData(this);
  3795. if (result === null || typeof result === "undefined") {
  3796. return "";
  3797. }
  3798. // if the data is a base64 string, we decode it before checking the encoding !
  3799. if (this.options.base64) {
  3800. result = base64.decode(result);
  3801. }
  3802. if (asUTF8 && this.options.binary) {
  3803. // JSZip.prototype.utf8decode supports arrays as input
  3804. // skip to array => string step, utf8decode will do it.
  3805. result = out.utf8decode(result);
  3806. }
  3807. else {
  3808. // no utf8 transformation, do the array => string step.
  3809. result = utils.transformTo("string", result);
  3810. }
  3811. if (!asUTF8 && !this.options.binary) {
  3812. result = utils.transformTo("string", out.utf8encode(result));
  3813. }
  3814. return result;
  3815. };
  3816. /**
  3817. * A simple object representing a file in the zip file.
  3818. * @constructor
  3819. * @param {string} name the name of the file
  3820. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  3821. * @param {Object} options the options of the file
  3822. */
  3823. var ZipObject = function(name, data, options) {
  3824. this.name = name;
  3825. this.dir = options.dir;
  3826. this.date = options.date;
  3827. this.comment = options.comment;
  3828. this.unixPermissions = options.unixPermissions;
  3829. this.dosPermissions = options.dosPermissions;
  3830. this._data = data;
  3831. this.options = options;
  3832. /*
  3833. * This object contains initial values for dir and date.
  3834. * With them, we can check if the user changed the deprecated metadata in
  3835. * `ZipObject#options` or not.
  3836. */
  3837. this._initialMetadata = {
  3838. dir : options.dir,
  3839. date : options.date
  3840. };
  3841. };
  3842. ZipObject.prototype = {
  3843. /**
  3844. * Return the content as UTF8 string.
  3845. * @return {string} the UTF8 string.
  3846. */
  3847. asText: function() {
  3848. return dataToString.call(this, true);
  3849. },
  3850. /**
  3851. * Returns the binary content.
  3852. * @return {string} the content as binary.
  3853. */
  3854. asBinary: function() {
  3855. return dataToString.call(this, false);
  3856. },
  3857. /**
  3858. * Returns the content as a nodejs Buffer.
  3859. * @return {Buffer} the content as a Buffer.
  3860. */
  3861. asNodeBuffer: function() {
  3862. var result = getBinaryData(this);
  3863. return utils.transformTo("nodebuffer", result);
  3864. },
  3865. /**
  3866. * Returns the content as an Uint8Array.
  3867. * @return {Uint8Array} the content as an Uint8Array.
  3868. */
  3869. asUint8Array: function() {
  3870. var result = getBinaryData(this);
  3871. return utils.transformTo("uint8array", result);
  3872. },
  3873. /**
  3874. * Returns the content as an ArrayBuffer.
  3875. * @return {ArrayBuffer} the content as an ArrayBufer.
  3876. */
  3877. asArrayBuffer: function() {
  3878. return this.asUint8Array().buffer;
  3879. }
  3880. };
  3881. /**
  3882. * Transform an integer into a string in hexadecimal.
  3883. * @private
  3884. * @param {number} dec the number to convert.
  3885. * @param {number} bytes the number of bytes to generate.
  3886. * @returns {string} the result.
  3887. */
  3888. var decToHex = function(dec, bytes) {
  3889. var hex = "",
  3890. i;
  3891. for (i = 0; i < bytes; i++) {
  3892. hex += String.fromCharCode(dec & 0xff);
  3893. dec = dec >>> 8;
  3894. }
  3895. return hex;
  3896. };
  3897. /**
  3898. * Transforms the (incomplete) options from the user into the complete
  3899. * set of options to create a file.
  3900. * @private
  3901. * @param {Object} o the options from the user.
  3902. * @return {Object} the complete set of options.
  3903. */
  3904. var prepareFileAttrs = function(o) {
  3905. o = o || {};
  3906. if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
  3907. o.binary = true;
  3908. }
  3909. o = utils.extend(o, defaults);
  3910. o.date = o.date || new Date();
  3911. if (o.compression !== null) o.compression = o.compression.toUpperCase();
  3912. return o;
  3913. };
  3914. /**
  3915. * Add a file in the current folder.
  3916. * @private
  3917. * @param {string} name the name of the file
  3918. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  3919. * @param {Object} o the options of the file
  3920. * @return {Object} the new file.
  3921. */
  3922. var fileAdd = function(name, data, o) {
  3923. // be sure sub folders exist
  3924. var dataType = utils.getTypeOf(data),
  3925. parent;
  3926. o = prepareFileAttrs(o);
  3927. if (typeof o.unixPermissions === "string") {
  3928. o.unixPermissions = parseInt(o.unixPermissions, 8);
  3929. }
  3930. // UNX_IFDIR 0040000 see zipinfo.c
  3931. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  3932. o.dir = true;
  3933. }
  3934. // Bit 4 Directory
  3935. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  3936. o.dir = true;
  3937. }
  3938. if (o.dir) {
  3939. name = forceTrailingSlash(name);
  3940. }
  3941. if (o.createFolders && (parent = parentFolder(name))) {
  3942. folderAdd.call(this, parent, true);
  3943. }
  3944. if (o.dir || data === null || typeof data === "undefined") {
  3945. o.base64 = false;
  3946. o.binary = false;
  3947. data = null;
  3948. dataType = null;
  3949. }
  3950. else if (dataType === "string") {
  3951. if (o.binary && !o.base64) {
  3952. // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
  3953. if (o.optimizedBinaryString !== true) {
  3954. // this is a string, not in a base64 format.
  3955. // Be sure that this is a correct "binary string"
  3956. data = utils.string2binary(data);
  3957. }
  3958. }
  3959. }
  3960. else { // arraybuffer, uint8array, ...
  3961. o.base64 = false;
  3962. o.binary = true;
  3963. if (!dataType && !(data instanceof CompressedObject)) {
  3964. throw new Error("The data of '" + name + "' is in an unsupported format !");
  3965. }
  3966. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  3967. if (dataType === "arraybuffer") {
  3968. data = utils.transformTo("uint8array", data);
  3969. }
  3970. }
  3971. var object = new ZipObject(name, data, o);
  3972. this.files[name] = object;
  3973. return object;
  3974. };
  3975. /**
  3976. * Find the parent folder of the path.
  3977. * @private
  3978. * @param {string} path the path to use
  3979. * @return {string} the parent folder, or ""
  3980. */
  3981. var parentFolder = function (path) {
  3982. if (path.slice(-1) == '/') {
  3983. path = path.substring(0, path.length - 1);
  3984. }
  3985. var lastSlash = path.lastIndexOf('/');
  3986. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  3987. };
  3988. /**
  3989. * Returns the path with a slash at the end.
  3990. * @private
  3991. * @param {String} path the path to check.
  3992. * @return {String} the path with a trailing slash.
  3993. */
  3994. var forceTrailingSlash = function(path) {
  3995. // Check the name ends with a /
  3996. if (path.slice(-1) != "/") {
  3997. path += "/"; // IE doesn't like substr(-1)
  3998. }
  3999. return path;
  4000. };
  4001. /**
  4002. * Add a (sub) folder in the current folder.
  4003. * @private
  4004. * @param {string} name the folder's name
  4005. * @param {boolean=} [createFolders] If true, automatically create sub
  4006. * folders. Defaults to false.
  4007. * @return {Object} the new folder.
  4008. */
  4009. var folderAdd = function(name, createFolders) {
  4010. createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
  4011. name = forceTrailingSlash(name);
  4012. // Does this folder already exist?
  4013. if (!this.files[name]) {
  4014. fileAdd.call(this, name, null, {
  4015. dir: true,
  4016. createFolders: createFolders
  4017. });
  4018. }
  4019. return this.files[name];
  4020. };
  4021. /**
  4022. * Generate a JSZip.CompressedObject for a given zipOject.
  4023. * @param {ZipObject} file the object to read.
  4024. * @param {JSZip.compression} compression the compression to use.
  4025. * @param {Object} compressionOptions the options to use when compressing.
  4026. * @return {JSZip.CompressedObject} the compressed result.
  4027. */
  4028. var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
  4029. var result = new CompressedObject(),
  4030. content;
  4031. // the data has not been decompressed, we might reuse things !
  4032. if (file._data instanceof CompressedObject) {
  4033. result.uncompressedSize = file._data.uncompressedSize;
  4034. result.crc32 = file._data.crc32;
  4035. if (result.uncompressedSize === 0 || file.dir) {
  4036. compression = compressions['STORE'];
  4037. result.compressedContent = "";
  4038. result.crc32 = 0;
  4039. }
  4040. else if (file._data.compressionMethod === compression.magic) {
  4041. result.compressedContent = file._data.getCompressedContent();
  4042. }
  4043. else {
  4044. content = file._data.getContent();
  4045. // need to decompress / recompress
  4046. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  4047. }
  4048. }
  4049. else {
  4050. // have uncompressed data
  4051. content = getBinaryData(file);
  4052. if (!content || content.length === 0 || file.dir) {
  4053. compression = compressions['STORE'];
  4054. content = "";
  4055. }
  4056. result.uncompressedSize = content.length;
  4057. result.crc32 = crc32(content);
  4058. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  4059. }
  4060. result.compressedSize = result.compressedContent.length;
  4061. result.compressionMethod = compression.magic;
  4062. return result;
  4063. };
  4064. /**
  4065. * Generate the UNIX part of the external file attributes.
  4066. * @param {Object} unixPermissions the unix permissions or null.
  4067. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  4068. * @return {Number} a 32 bit integer.
  4069. *
  4070. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  4071. *
  4072. * TTTTsstrwxrwxrwx0000000000ADVSHR
  4073. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  4074. * ^^^_________________________ setuid, setgid, sticky
  4075. * ^^^^^^^^^________________ permissions
  4076. * ^^^^^^^^^^______ not used ?
  4077. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  4078. */
  4079. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  4080. var result = unixPermissions;
  4081. if (!unixPermissions) {
  4082. // I can't use octal values in strict mode, hence the hexa.
  4083. // 040775 => 0x41fd
  4084. // 0100664 => 0x81b4
  4085. result = isDir ? 0x41fd : 0x81b4;
  4086. }
  4087. return (result & 0xFFFF) << 16;
  4088. };
  4089. /**
  4090. * Generate the DOS part of the external file attributes.
  4091. * @param {Object} dosPermissions the dos permissions or null.
  4092. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  4093. * @return {Number} a 32 bit integer.
  4094. *
  4095. * Bit 0 Read-Only
  4096. * Bit 1 Hidden
  4097. * Bit 2 System
  4098. * Bit 3 Volume Label
  4099. * Bit 4 Directory
  4100. * Bit 5 Archive
  4101. */
  4102. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  4103. // the dir flag is already set for compatibility
  4104. return (dosPermissions || 0) & 0x3F;
  4105. };
  4106. /**
  4107. * Generate the various parts used in the construction of the final zip file.
  4108. * @param {string} name the file name.
  4109. * @param {ZipObject} file the file content.
  4110. * @param {JSZip.CompressedObject} compressedObject the compressed object.
  4111. * @param {number} offset the current offset from the start of the zip file.
  4112. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  4113. * @param {Function} encodeFileName the function to encode the file name / comment.
  4114. * @return {object} the zip parts.
  4115. */
  4116. var generateZipParts = function(name, file, compressedObject, offset, platform, encodeFileName) {
  4117. var data = compressedObject.compressedContent,
  4118. useCustomEncoding = encodeFileName !== utf8.utf8encode,
  4119. encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  4120. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  4121. comment = file.comment || "",
  4122. encodedComment = utils.transformTo("string", encodeFileName(comment)),
  4123. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  4124. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  4125. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  4126. o = file.options,
  4127. dosTime,
  4128. dosDate,
  4129. extraFields = "",
  4130. unicodePathExtraField = "",
  4131. unicodeCommentExtraField = "",
  4132. dir, date;
  4133. // handle the deprecated options.dir
  4134. if (file._initialMetadata.dir !== file.dir) {
  4135. dir = file.dir;
  4136. } else {
  4137. dir = o.dir;
  4138. }
  4139. // handle the deprecated options.date
  4140. if(file._initialMetadata.date !== file.date) {
  4141. date = file.date;
  4142. } else {
  4143. date = o.date;
  4144. }
  4145. var extFileAttr = 0;
  4146. var versionMadeBy = 0;
  4147. if (dir) {
  4148. // dos or unix, we set the dos dir flag
  4149. extFileAttr |= 0x00010;
  4150. }
  4151. if(platform === "UNIX") {
  4152. versionMadeBy = 0x031E; // UNIX, version 3.0
  4153. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  4154. } else { // DOS or other, fallback to DOS
  4155. versionMadeBy = 0x0014; // DOS, version 2.0
  4156. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  4157. }
  4158. // date
  4159. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  4160. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  4161. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  4162. dosTime = date.getHours();
  4163. dosTime = dosTime << 6;
  4164. dosTime = dosTime | date.getMinutes();
  4165. dosTime = dosTime << 5;
  4166. dosTime = dosTime | date.getSeconds() / 2;
  4167. dosDate = date.getFullYear() - 1980;
  4168. dosDate = dosDate << 4;
  4169. dosDate = dosDate | (date.getMonth() + 1);
  4170. dosDate = dosDate << 5;
  4171. dosDate = dosDate | date.getDate();
  4172. if (useUTF8ForFileName) {
  4173. // set the unicode path extra field. unzip needs at least one extra
  4174. // field to correctly handle unicode path, so using the path is as good
  4175. // as any other information. This could improve the situation with
  4176. // other archive managers too.
  4177. // This field is usually used without the utf8 flag, with a non
  4178. // unicode path in the header (winrar, winzip). This helps (a bit)
  4179. // with the messy Windows' default compressed folders feature but
  4180. // breaks on p7zip which doesn't seek the unicode path extra field.
  4181. // So for now, UTF-8 everywhere !
  4182. unicodePathExtraField =
  4183. // Version
  4184. decToHex(1, 1) +
  4185. // NameCRC32
  4186. decToHex(crc32(encodedFileName), 4) +
  4187. // UnicodeName
  4188. utfEncodedFileName;
  4189. extraFields +=
  4190. // Info-ZIP Unicode Path Extra Field
  4191. "\x75\x70" +
  4192. // size
  4193. decToHex(unicodePathExtraField.length, 2) +
  4194. // content
  4195. unicodePathExtraField;
  4196. }
  4197. if(useUTF8ForComment) {
  4198. unicodeCommentExtraField =
  4199. // Version
  4200. decToHex(1, 1) +
  4201. // CommentCRC32
  4202. decToHex(this.crc32(encodedComment), 4) +
  4203. // UnicodeName
  4204. utfEncodedComment;
  4205. extraFields +=
  4206. // Info-ZIP Unicode Path Extra Field
  4207. "\x75\x63" +
  4208. // size
  4209. decToHex(unicodeCommentExtraField.length, 2) +
  4210. // content
  4211. unicodeCommentExtraField;
  4212. }
  4213. var header = "";
  4214. // version needed to extract
  4215. header += "\x0A\x00";
  4216. // general purpose bit flag
  4217. // set bit 11 if utf8
  4218. header += !useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
  4219. // compression method
  4220. header += compressedObject.compressionMethod;
  4221. // last mod file time
  4222. header += decToHex(dosTime, 2);
  4223. // last mod file date
  4224. header += decToHex(dosDate, 2);
  4225. // crc-32
  4226. header += decToHex(compressedObject.crc32, 4);
  4227. // compressed size
  4228. header += decToHex(compressedObject.compressedSize, 4);
  4229. // uncompressed size
  4230. header += decToHex(compressedObject.uncompressedSize, 4);
  4231. // file name length
  4232. header += decToHex(encodedFileName.length, 2);
  4233. // extra field length
  4234. header += decToHex(extraFields.length, 2);
  4235. var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  4236. var dirRecord = signature.CENTRAL_FILE_HEADER +
  4237. // version made by (00: DOS)
  4238. decToHex(versionMadeBy, 2) +
  4239. // file header (common to file and central directory)
  4240. header +
  4241. // file comment length
  4242. decToHex(encodedComment.length, 2) +
  4243. // disk number start
  4244. "\x00\x00" +
  4245. // internal file attributes TODO
  4246. "\x00\x00" +
  4247. // external file attributes
  4248. decToHex(extFileAttr, 4) +
  4249. // relative offset of local header
  4250. decToHex(offset, 4) +
  4251. // file name
  4252. encodedFileName +
  4253. // extra field
  4254. extraFields +
  4255. // file comment
  4256. encodedComment;
  4257. return {
  4258. fileRecord: fileRecord,
  4259. dirRecord: dirRecord,
  4260. compressedObject: compressedObject
  4261. };
  4262. };
  4263. // return the actual prototype of JSZip
  4264. var out = {
  4265. /**
  4266. * Read an existing zip and merge the data in the current JSZip object.
  4267. * The implementation is in jszip-load.js, don't forget to include it.
  4268. * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
  4269. * @param {Object} options Options for loading the stream.
  4270. * options.base64 : is the stream in base64 ? default : false
  4271. * @return {JSZip} the current JSZip object
  4272. */
  4273. load: function(stream, options) {
  4274. throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
  4275. },
  4276. /**
  4277. * Filter nested files/folders with the specified function.
  4278. * @param {Function} search the predicate to use :
  4279. * function (relativePath, file) {...}
  4280. * It takes 2 arguments : the relative path and the file.
  4281. * @return {Array} An array of matching elements.
  4282. */
  4283. filter: function(search) {
  4284. var result = [],
  4285. filename, relativePath, file, fileClone;
  4286. for (filename in this.files) {
  4287. if (!this.files.hasOwnProperty(filename)) {
  4288. continue;
  4289. }
  4290. file = this.files[filename];
  4291. // return a new object, don't let the user mess with our internal objects :)
  4292. fileClone = new ZipObject(file.name, file._data, utils.extend(file.options));
  4293. relativePath = filename.slice(this.root.length, filename.length);
  4294. if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
  4295. search(relativePath, fileClone)) { // and the file matches the function
  4296. result.push(fileClone);
  4297. }
  4298. }
  4299. return result;
  4300. },
  4301. /**
  4302. * Add a file to the zip file, or search a file.
  4303. * @param {string|RegExp} name The name of the file to add (if data is defined),
  4304. * the name of the file to find (if no data) or a regex to match files.
  4305. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  4306. * @param {Object} o File options
  4307. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  4308. * a file (when searching by string) or an array of files (when searching by regex).
  4309. */
  4310. file: function(name, data, o) {
  4311. if (arguments.length === 1) {
  4312. if (utils.isRegExp(name)) {
  4313. var regexp = name;
  4314. return this.filter(function(relativePath, file) {
  4315. return !file.dir && regexp.test(relativePath);
  4316. });
  4317. }
  4318. else { // text
  4319. return this.filter(function(relativePath, file) {
  4320. return !file.dir && relativePath === name;
  4321. })[0] || null;
  4322. }
  4323. }
  4324. else { // more than one argument : we have data !
  4325. name = this.root + name;
  4326. fileAdd.call(this, name, data, o);
  4327. }
  4328. return this;
  4329. },
  4330. /**
  4331. * Add a directory to the zip file, or search.
  4332. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  4333. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  4334. */
  4335. folder: function(arg) {
  4336. if (!arg) {
  4337. return this;
  4338. }
  4339. if (utils.isRegExp(arg)) {
  4340. return this.filter(function(relativePath, file) {
  4341. return file.dir && arg.test(relativePath);
  4342. });
  4343. }
  4344. // else, name is a new folder
  4345. var name = this.root + arg;
  4346. var newFolder = folderAdd.call(this, name);
  4347. // Allow chaining by returning a new object with this folder as the root
  4348. var ret = this.clone();
  4349. ret.root = newFolder.name;
  4350. return ret;
  4351. },
  4352. /**
  4353. * Delete a file, or a directory and all sub-files, from the zip
  4354. * @param {string} name the name of the file to delete
  4355. * @return {JSZip} this JSZip object
  4356. */
  4357. remove: function(name) {
  4358. name = this.root + name;
  4359. var file = this.files[name];
  4360. if (!file) {
  4361. // Look for any folders
  4362. if (name.slice(-1) != "/") {
  4363. name += "/";
  4364. }
  4365. file = this.files[name];
  4366. }
  4367. if (file && !file.dir) {
  4368. // file
  4369. delete this.files[name];
  4370. } else {
  4371. // maybe a folder, delete recursively
  4372. var kids = this.filter(function(relativePath, file) {
  4373. return file.name.slice(0, name.length) === name;
  4374. });
  4375. for (var i = 0; i < kids.length; i++) {
  4376. delete this.files[kids[i].name];
  4377. }
  4378. }
  4379. return this;
  4380. },
  4381. /**
  4382. * Generate the complete zip file
  4383. * @param {Object} options the options to generate the zip file :
  4384. * - base64, (deprecated, use type instead) true to generate base64.
  4385. * - compression, "STORE" by default.
  4386. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  4387. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  4388. */
  4389. generate: function(options) {
  4390. options = utils.extend(options || {}, {
  4391. base64: true,
  4392. compression: "STORE",
  4393. compressionOptions : null,
  4394. type: "base64",
  4395. platform: "DOS",
  4396. comment: null,
  4397. mimeType: 'application/zip',
  4398. encodeFileName: utf8.utf8encode
  4399. });
  4400. utils.checkSupport(options.type);
  4401. // accept nodejs `process.platform`
  4402. if(
  4403. options.platform === 'darwin' ||
  4404. options.platform === 'freebsd' ||
  4405. options.platform === 'linux' ||
  4406. options.platform === 'sunos'
  4407. ) {
  4408. options.platform = "UNIX";
  4409. }
  4410. if (options.platform === 'win32') {
  4411. options.platform = "DOS";
  4412. }
  4413. var zipData = [],
  4414. localDirLength = 0,
  4415. centralDirLength = 0,
  4416. writer, i,
  4417. encodedComment = utils.transformTo("string", options.encodeFileName(options.comment || this.comment || ""));
  4418. // first, generate all the zip parts.
  4419. for (var name in this.files) {
  4420. if (!this.files.hasOwnProperty(name)) {
  4421. continue;
  4422. }
  4423. var file = this.files[name];
  4424. var compressionName = file.options.compression || options.compression.toUpperCase();
  4425. var compression = compressions[compressionName];
  4426. if (!compression) {
  4427. throw new Error(compressionName + " is not a valid compression method !");
  4428. }
  4429. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  4430. var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
  4431. var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform, options.encodeFileName);
  4432. localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
  4433. centralDirLength += zipPart.dirRecord.length;
  4434. zipData.push(zipPart);
  4435. }
  4436. var dirEnd = "";
  4437. // end of central dir signature
  4438. dirEnd = signature.CENTRAL_DIRECTORY_END +
  4439. // number of this disk
  4440. "\x00\x00" +
  4441. // number of the disk with the start of the central directory
  4442. "\x00\x00" +
  4443. // total number of entries in the central directory on this disk
  4444. decToHex(zipData.length, 2) +
  4445. // total number of entries in the central directory
  4446. decToHex(zipData.length, 2) +
  4447. // size of the central directory 4 bytes
  4448. decToHex(centralDirLength, 4) +
  4449. // offset of start of central directory with respect to the starting disk number
  4450. decToHex(localDirLength, 4) +
  4451. // .ZIP file comment length
  4452. decToHex(encodedComment.length, 2) +
  4453. // .ZIP file comment
  4454. encodedComment;
  4455. // we have all the parts (and the total length)
  4456. // time to create a writer !
  4457. var typeName = options.type.toLowerCase();
  4458. if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
  4459. writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
  4460. }else{
  4461. writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
  4462. }
  4463. for (i = 0; i < zipData.length; i++) {
  4464. writer.append(zipData[i].fileRecord);
  4465. writer.append(zipData[i].compressedObject.compressedContent);
  4466. }
  4467. for (i = 0; i < zipData.length; i++) {
  4468. writer.append(zipData[i].dirRecord);
  4469. }
  4470. writer.append(dirEnd);
  4471. var zip = writer.finalize();
  4472. switch(options.type.toLowerCase()) {
  4473. // case "zip is an Uint8Array"
  4474. case "uint8array" :
  4475. case "arraybuffer" :
  4476. case "nodebuffer" :
  4477. return utils.transformTo(options.type.toLowerCase(), zip);
  4478. case "blob" :
  4479. return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
  4480. // case "zip is a string"
  4481. case "base64" :
  4482. return (options.base64) ? base64.encode(zip) : zip;
  4483. default : // case "string" :
  4484. return zip;
  4485. }
  4486. },
  4487. /**
  4488. * @deprecated
  4489. * This method will be removed in a future version without replacement.
  4490. */
  4491. crc32: function (input, crc) {
  4492. return crc32(input, crc);
  4493. },
  4494. /**
  4495. * @deprecated
  4496. * This method will be removed in a future version without replacement.
  4497. */
  4498. utf8encode: function (string) {
  4499. return utils.transformTo("string", utf8.utf8encode(string));
  4500. },
  4501. /**
  4502. * @deprecated
  4503. * This method will be removed in a future version without replacement.
  4504. */
  4505. utf8decode: function (input) {
  4506. return utf8.utf8decode(input);
  4507. }
  4508. };
  4509. module.exports = out;
  4510. },{"./base64":6,"./compressedObject":7,"./compressions":8,"./crc32":9,"./defaults":11,"./nodeBuffer":16,"./signature":19,"./stringWriter":21,"./support":22,"./uint8ArrayWriter":24,"./utf8":25,"./utils":26}],19:[function(_dereq_,module,exports){
  4511. 'use strict';
  4512. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  4513. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  4514. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  4515. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  4516. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  4517. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  4518. },{}],20:[function(_dereq_,module,exports){
  4519. 'use strict';
  4520. var DataReader = _dereq_('./dataReader');
  4521. var utils = _dereq_('./utils');
  4522. function StringReader(data, optimizedBinaryString) {
  4523. this.data = data;
  4524. if (!optimizedBinaryString) {
  4525. this.data = utils.string2binary(this.data);
  4526. }
  4527. this.length = this.data.length;
  4528. this.index = 0;
  4529. this.zero = 0;
  4530. }
  4531. StringReader.prototype = new DataReader();
  4532. /**
  4533. * @see DataReader.byteAt
  4534. */
  4535. StringReader.prototype.byteAt = function(i) {
  4536. return this.data.charCodeAt(this.zero + i);
  4537. };
  4538. /**
  4539. * @see DataReader.lastIndexOfSignature
  4540. */
  4541. StringReader.prototype.lastIndexOfSignature = function(sig) {
  4542. return this.data.lastIndexOf(sig) - this.zero;
  4543. };
  4544. /**
  4545. * @see DataReader.readData
  4546. */
  4547. StringReader.prototype.readData = function(size) {
  4548. this.checkOffset(size);
  4549. // this will work because the constructor applied the "& 0xff" mask.
  4550. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  4551. this.index += size;
  4552. return result;
  4553. };
  4554. module.exports = StringReader;
  4555. },{"./dataReader":10,"./utils":26}],21:[function(_dereq_,module,exports){
  4556. 'use strict';
  4557. var utils = _dereq_('./utils');
  4558. /**
  4559. * An object to write any content to a string.
  4560. * @constructor
  4561. */
  4562. var StringWriter = function() {
  4563. this.data = [];
  4564. };
  4565. StringWriter.prototype = {
  4566. /**
  4567. * Append any content to the current string.
  4568. * @param {Object} input the content to add.
  4569. */
  4570. append: function(input) {
  4571. input = utils.transformTo("string", input);
  4572. this.data.push(input);
  4573. },
  4574. /**
  4575. * Finalize the construction an return the result.
  4576. * @return {string} the generated string.
  4577. */
  4578. finalize: function() {
  4579. return this.data.join("");
  4580. }
  4581. };
  4582. module.exports = StringWriter;
  4583. },{"./utils":26}],22:[function(_dereq_,module,exports){
  4584. (function (Buffer){
  4585. 'use strict';
  4586. exports.base64 = true;
  4587. exports.array = true;
  4588. exports.string = true;
  4589. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  4590. // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
  4591. // Browserify will provide a Buffer implementation for browsers, which is
  4592. // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
  4593. exports.nodebuffer = typeof Buffer !== "undefined";
  4594. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  4595. exports.uint8array = typeof Uint8Array !== "undefined";
  4596. if (typeof ArrayBuffer === "undefined") {
  4597. exports.blob = false;
  4598. }
  4599. else {
  4600. var buffer = new ArrayBuffer(0);
  4601. try {
  4602. exports.blob = new Blob([buffer], {
  4603. type: "application/zip"
  4604. }).size === 0;
  4605. }
  4606. catch (e) {
  4607. try {
  4608. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  4609. var builder = new Builder();
  4610. builder.append(buffer);
  4611. exports.blob = builder.getBlob('application/zip').size === 0;
  4612. }
  4613. catch (e) {
  4614. exports.blob = false;
  4615. }
  4616. }
  4617. }
  4618. }).call(this,_dereq_("buffer").Buffer)
  4619. },{"buffer":1}],23:[function(_dereq_,module,exports){
  4620. 'use strict';
  4621. var ArrayReader = _dereq_('./arrayReader');
  4622. function Uint8ArrayReader(data) {
  4623. if (data) {
  4624. this.data = data;
  4625. this.length = this.data.length;
  4626. this.index = 0;
  4627. this.zero = 0;
  4628. }
  4629. }
  4630. Uint8ArrayReader.prototype = new ArrayReader();
  4631. /**
  4632. * @see DataReader.readData
  4633. */
  4634. Uint8ArrayReader.prototype.readData = function(size) {
  4635. this.checkOffset(size);
  4636. if(size === 0) {
  4637. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  4638. return new Uint8Array(0);
  4639. }
  4640. var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  4641. this.index += size;
  4642. return result;
  4643. };
  4644. module.exports = Uint8ArrayReader;
  4645. },{"./arrayReader":5}],24:[function(_dereq_,module,exports){
  4646. 'use strict';
  4647. var utils = _dereq_('./utils');
  4648. /**
  4649. * An object to write any content to an Uint8Array.
  4650. * @constructor
  4651. * @param {number} length The length of the array.
  4652. */
  4653. var Uint8ArrayWriter = function(length) {
  4654. this.data = new Uint8Array(length);
  4655. this.index = 0;
  4656. };
  4657. Uint8ArrayWriter.prototype = {
  4658. /**
  4659. * Append any content to the current array.
  4660. * @param {Object} input the content to add.
  4661. */
  4662. append: function(input) {
  4663. if (input.length !== 0) {
  4664. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  4665. input = utils.transformTo("uint8array", input);
  4666. this.data.set(input, this.index);
  4667. this.index += input.length;
  4668. }
  4669. },
  4670. /**
  4671. * Finalize the construction an return the result.
  4672. * @return {Uint8Array} the generated array.
  4673. */
  4674. finalize: function() {
  4675. return this.data;
  4676. }
  4677. };
  4678. module.exports = Uint8ArrayWriter;
  4679. },{"./utils":26}],25:[function(_dereq_,module,exports){
  4680. 'use strict';
  4681. var utils = _dereq_('./utils');
  4682. var support = _dereq_('./support');
  4683. var nodeBuffer = _dereq_('./nodeBuffer');
  4684. /**
  4685. * The following functions come from pako, from pako/lib/utils/strings
  4686. * released under the MIT license, see pako https://github.com/nodeca/pako/
  4687. */
  4688. // Table with utf8 lengths (calculated by first byte of sequence)
  4689. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  4690. // because max possible codepoint is 0x10ffff
  4691. var _utf8len = new Array(256);
  4692. for (var i=0; i<256; i++) {
  4693. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  4694. }
  4695. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  4696. // convert string to array (typed, when possible)
  4697. var string2buf = function (str) {
  4698. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  4699. // count binary size
  4700. for (m_pos = 0; m_pos < str_len; m_pos++) {
  4701. c = str.charCodeAt(m_pos);
  4702. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  4703. c2 = str.charCodeAt(m_pos+1);
  4704. if ((c2 & 0xfc00) === 0xdc00) {
  4705. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4706. m_pos++;
  4707. }
  4708. }
  4709. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  4710. }
  4711. // allocate buffer
  4712. if (support.uint8array) {
  4713. buf = new Uint8Array(buf_len);
  4714. } else {
  4715. buf = new Array(buf_len);
  4716. }
  4717. // convert
  4718. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  4719. c = str.charCodeAt(m_pos);
  4720. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  4721. c2 = str.charCodeAt(m_pos+1);
  4722. if ((c2 & 0xfc00) === 0xdc00) {
  4723. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4724. m_pos++;
  4725. }
  4726. }
  4727. if (c < 0x80) {
  4728. /* one byte */
  4729. buf[i++] = c;
  4730. } else if (c < 0x800) {
  4731. /* two bytes */
  4732. buf[i++] = 0xC0 | (c >>> 6);
  4733. buf[i++] = 0x80 | (c & 0x3f);
  4734. } else if (c < 0x10000) {
  4735. /* three bytes */
  4736. buf[i++] = 0xE0 | (c >>> 12);
  4737. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  4738. buf[i++] = 0x80 | (c & 0x3f);
  4739. } else {
  4740. /* four bytes */
  4741. buf[i++] = 0xf0 | (c >>> 18);
  4742. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  4743. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  4744. buf[i++] = 0x80 | (c & 0x3f);
  4745. }
  4746. }
  4747. return buf;
  4748. };
  4749. // Calculate max possible position in utf8 buffer,
  4750. // that will not break sequence. If that's not possible
  4751. // - (very small limits) return max size as is.
  4752. //
  4753. // buf[] - utf8 bytes array
  4754. // max - length limit (mandatory);
  4755. var utf8border = function(buf, max) {
  4756. var pos;
  4757. max = max || buf.length;
  4758. if (max > buf.length) { max = buf.length; }
  4759. // go back from last position, until start of sequence found
  4760. pos = max-1;
  4761. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  4762. // Fuckup - very small and broken sequence,
  4763. // return max, because we should return something anyway.
  4764. if (pos < 0) { return max; }
  4765. // If we came to start of buffer - that means vuffer is too small,
  4766. // return max too.
  4767. if (pos === 0) { return max; }
  4768. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  4769. };
  4770. // convert array to string
  4771. var buf2string = function (buf) {
  4772. var str, i, out, c, c_len;
  4773. var len = buf.length;
  4774. // Reserve max possible length (2 words per char)
  4775. // NB: by unknown reasons, Array is significantly faster for
  4776. // String.fromCharCode.apply than Uint16Array.
  4777. var utf16buf = new Array(len*2);
  4778. for (out=0, i=0; i<len;) {
  4779. c = buf[i++];
  4780. // quick process ascii
  4781. if (c < 0x80) { utf16buf[out++] = c; continue; }
  4782. c_len = _utf8len[c];
  4783. // skip 5 & 6 byte codes
  4784. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  4785. // apply mask on first byte
  4786. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  4787. // join the rest
  4788. while (c_len > 1 && i < len) {
  4789. c = (c << 6) | (buf[i++] & 0x3f);
  4790. c_len--;
  4791. }
  4792. // terminated by end of string?
  4793. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  4794. if (c < 0x10000) {
  4795. utf16buf[out++] = c;
  4796. } else {
  4797. c -= 0x10000;
  4798. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  4799. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  4800. }
  4801. }
  4802. // shrinkBuf(utf16buf, out)
  4803. if (utf16buf.length !== out) {
  4804. if(utf16buf.subarray) {
  4805. utf16buf = utf16buf.subarray(0, out);
  4806. } else {
  4807. utf16buf.length = out;
  4808. }
  4809. }
  4810. // return String.fromCharCode.apply(null, utf16buf);
  4811. return utils.applyFromCharCode(utf16buf);
  4812. };
  4813. // That's all for the pako functions.
  4814. /**
  4815. * Transform a javascript string into an array (typed if possible) of bytes,
  4816. * UTF-8 encoded.
  4817. * @param {String} str the string to encode
  4818. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  4819. */
  4820. exports.utf8encode = function utf8encode(str) {
  4821. if (support.nodebuffer) {
  4822. return nodeBuffer(str, "utf-8");
  4823. }
  4824. return string2buf(str);
  4825. };
  4826. /**
  4827. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  4828. * string into a javascript string.
  4829. * @param {Array|Uint8Array|Buffer} buf the data de decode
  4830. * @return {String} the decoded string.
  4831. */
  4832. exports.utf8decode = function utf8decode(buf) {
  4833. if (support.nodebuffer) {
  4834. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  4835. }
  4836. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  4837. // return buf2string(buf);
  4838. // Chrome prefers to work with "small" chunks of data
  4839. // for the method buf2string.
  4840. // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
  4841. var result = [], k = 0, len = buf.length, chunk = 65536;
  4842. while (k < len) {
  4843. var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
  4844. if (support.uint8array) {
  4845. result.push(buf2string(buf.subarray(k, nextBoundary)));
  4846. } else {
  4847. result.push(buf2string(buf.slice(k, nextBoundary)));
  4848. }
  4849. k = nextBoundary;
  4850. }
  4851. return result.join("");
  4852. };
  4853. // vim: set shiftwidth=4 softtabstop=4:
  4854. },{"./nodeBuffer":16,"./support":22,"./utils":26}],26:[function(_dereq_,module,exports){
  4855. 'use strict';
  4856. var support = _dereq_('./support');
  4857. var compressions = _dereq_('./compressions');
  4858. var nodeBuffer = _dereq_('./nodeBuffer');
  4859. /**
  4860. * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
  4861. * @param {string} str the string to transform.
  4862. * @return {String} the binary string.
  4863. */
  4864. exports.string2binary = function(str) {
  4865. var result = "";
  4866. for (var i = 0; i < str.length; i++) {
  4867. result += String.fromCharCode(str.charCodeAt(i) & 0xff);
  4868. }
  4869. return result;
  4870. };
  4871. exports.arrayBuffer2Blob = function(buffer, mimeType) {
  4872. exports.checkSupport("blob");
  4873. mimeType = mimeType || 'application/zip';
  4874. try {
  4875. // Blob constructor
  4876. return new Blob([buffer], {
  4877. type: mimeType
  4878. });
  4879. }
  4880. catch (e) {
  4881. try {
  4882. // deprecated, browser only, old way
  4883. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  4884. var builder = new Builder();
  4885. builder.append(buffer);
  4886. return builder.getBlob(mimeType);
  4887. }
  4888. catch (e) {
  4889. // well, fuck ?!
  4890. throw new Error("Bug : can't construct the Blob.");
  4891. }
  4892. }
  4893. };
  4894. /**
  4895. * The identity function.
  4896. * @param {Object} input the input.
  4897. * @return {Object} the same input.
  4898. */
  4899. function identity(input) {
  4900. return input;
  4901. }
  4902. /**
  4903. * Fill in an array with a string.
  4904. * @param {String} str the string to use.
  4905. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  4906. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  4907. */
  4908. function stringToArrayLike(str, array) {
  4909. for (var i = 0; i < str.length; ++i) {
  4910. array[i] = str.charCodeAt(i) & 0xFF;
  4911. }
  4912. return array;
  4913. }
  4914. /**
  4915. * Transform an array-like object to a string.
  4916. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  4917. * @return {String} the result.
  4918. */
  4919. function arrayLikeToString(array) {
  4920. // Performances notes :
  4921. // --------------------
  4922. // String.fromCharCode.apply(null, array) is the fastest, see
  4923. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  4924. // but the stack is limited (and we can get huge arrays !).
  4925. //
  4926. // result += String.fromCharCode(array[i]); generate too many strings !
  4927. //
  4928. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  4929. var chunk = 65536;
  4930. var result = [],
  4931. len = array.length,
  4932. type = exports.getTypeOf(array),
  4933. k = 0,
  4934. canUseApply = true;
  4935. try {
  4936. switch(type) {
  4937. case "uint8array":
  4938. String.fromCharCode.apply(null, new Uint8Array(0));
  4939. break;
  4940. case "nodebuffer":
  4941. String.fromCharCode.apply(null, nodeBuffer(0));
  4942. break;
  4943. }
  4944. } catch(e) {
  4945. canUseApply = false;
  4946. }
  4947. // no apply : slow and painful algorithm
  4948. // default browser on android 4.*
  4949. if (!canUseApply) {
  4950. var resultStr = "";
  4951. for(var i = 0; i < array.length;i++) {
  4952. resultStr += String.fromCharCode(array[i]);
  4953. }
  4954. return resultStr;
  4955. }
  4956. while (k < len && chunk > 1) {
  4957. try {
  4958. if (type === "array" || type === "nodebuffer") {
  4959. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  4960. }
  4961. else {
  4962. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  4963. }
  4964. k += chunk;
  4965. }
  4966. catch (e) {
  4967. chunk = Math.floor(chunk / 2);
  4968. }
  4969. }
  4970. return result.join("");
  4971. }
  4972. exports.applyFromCharCode = arrayLikeToString;
  4973. /**
  4974. * Copy the data from an array-like to an other array-like.
  4975. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  4976. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  4977. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  4978. */
  4979. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  4980. for (var i = 0; i < arrayFrom.length; i++) {
  4981. arrayTo[i] = arrayFrom[i];
  4982. }
  4983. return arrayTo;
  4984. }
  4985. // a matrix containing functions to transform everything into everything.
  4986. var transform = {};
  4987. // string to ?
  4988. transform["string"] = {
  4989. "string": identity,
  4990. "array": function(input) {
  4991. return stringToArrayLike(input, new Array(input.length));
  4992. },
  4993. "arraybuffer": function(input) {
  4994. return transform["string"]["uint8array"](input).buffer;
  4995. },
  4996. "uint8array": function(input) {
  4997. return stringToArrayLike(input, new Uint8Array(input.length));
  4998. },
  4999. "nodebuffer": function(input) {
  5000. return stringToArrayLike(input, nodeBuffer(input.length));
  5001. }
  5002. };
  5003. // array to ?
  5004. transform["array"] = {
  5005. "string": arrayLikeToString,
  5006. "array": identity,
  5007. "arraybuffer": function(input) {
  5008. return (new Uint8Array(input)).buffer;
  5009. },
  5010. "uint8array": function(input) {
  5011. return new Uint8Array(input);
  5012. },
  5013. "nodebuffer": function(input) {
  5014. return nodeBuffer(input);
  5015. }
  5016. };
  5017. // arraybuffer to ?
  5018. transform["arraybuffer"] = {
  5019. "string": function(input) {
  5020. return arrayLikeToString(new Uint8Array(input));
  5021. },
  5022. "array": function(input) {
  5023. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  5024. },
  5025. "arraybuffer": identity,
  5026. "uint8array": function(input) {
  5027. return new Uint8Array(input);
  5028. },
  5029. "nodebuffer": function(input) {
  5030. return nodeBuffer(new Uint8Array(input));
  5031. }
  5032. };
  5033. // uint8array to ?
  5034. transform["uint8array"] = {
  5035. "string": arrayLikeToString,
  5036. "array": function(input) {
  5037. return arrayLikeToArrayLike(input, new Array(input.length));
  5038. },
  5039. "arraybuffer": function(input) {
  5040. return input.buffer;
  5041. },
  5042. "uint8array": identity,
  5043. "nodebuffer": function(input) {
  5044. return nodeBuffer(input);
  5045. }
  5046. };
  5047. // nodebuffer to ?
  5048. transform["nodebuffer"] = {
  5049. "string": arrayLikeToString,
  5050. "array": function(input) {
  5051. return arrayLikeToArrayLike(input, new Array(input.length));
  5052. },
  5053. "arraybuffer": function(input) {
  5054. return transform["nodebuffer"]["uint8array"](input).buffer;
  5055. },
  5056. "uint8array": function(input) {
  5057. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  5058. },
  5059. "nodebuffer": identity
  5060. };
  5061. /**
  5062. * Transform an input into any type.
  5063. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  5064. * If no output type is specified, the unmodified input will be returned.
  5065. * @param {String} outputType the output type.
  5066. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  5067. * @throws {Error} an Error if the browser doesn't support the requested output type.
  5068. */
  5069. exports.transformTo = function(outputType, input) {
  5070. if (!input) {
  5071. // undefined, null, etc
  5072. // an empty string won't harm.
  5073. input = "";
  5074. }
  5075. if (!outputType) {
  5076. return input;
  5077. }
  5078. exports.checkSupport(outputType);
  5079. var inputType = exports.getTypeOf(input);
  5080. var result = transform[inputType][outputType](input);
  5081. return result;
  5082. };
  5083. /**
  5084. * Return the type of the input.
  5085. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  5086. * @param {Object} input the input to identify.
  5087. * @return {String} the (lowercase) type of the input.
  5088. */
  5089. exports.getTypeOf = function(input) {
  5090. if (typeof input === "string") {
  5091. return "string";
  5092. }
  5093. if (Object.prototype.toString.call(input) === "[object Array]") {
  5094. return "array";
  5095. }
  5096. if (support.nodebuffer && nodeBuffer.test(input)) {
  5097. return "nodebuffer";
  5098. }
  5099. if (support.uint8array && input instanceof Uint8Array) {
  5100. return "uint8array";
  5101. }
  5102. if (support.arraybuffer && input instanceof ArrayBuffer) {
  5103. return "arraybuffer";
  5104. }
  5105. };
  5106. /**
  5107. * Throw an exception if the type is not supported.
  5108. * @param {String} type the type to check.
  5109. * @throws {Error} an Error if the browser doesn't support the requested type.
  5110. */
  5111. exports.checkSupport = function(type) {
  5112. var supported = support[type.toLowerCase()];
  5113. if (!supported) {
  5114. throw new Error(type + " is not supported by this browser");
  5115. }
  5116. };
  5117. exports.MAX_VALUE_16BITS = 65535;
  5118. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  5119. /**
  5120. * Prettify a string read as binary.
  5121. * @param {string} str the string to prettify.
  5122. * @return {string} a pretty string.
  5123. */
  5124. exports.pretty = function(str) {
  5125. var res = '',
  5126. code, i;
  5127. for (i = 0; i < (str || "").length; i++) {
  5128. code = str.charCodeAt(i);
  5129. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  5130. }
  5131. return res;
  5132. };
  5133. /**
  5134. * Find a compression registered in JSZip.
  5135. * @param {string} compressionMethod the method magic to find.
  5136. * @return {Object|null} the JSZip compression object, null if none found.
  5137. */
  5138. exports.findCompression = function(compressionMethod) {
  5139. for (var method in compressions) {
  5140. if (!compressions.hasOwnProperty(method)) {
  5141. continue;
  5142. }
  5143. if (compressions[method].magic === compressionMethod) {
  5144. return compressions[method];
  5145. }
  5146. }
  5147. return null;
  5148. };
  5149. /**
  5150. * Cross-window, cross-Node-context regular expression detection
  5151. * @param {Object} object Anything
  5152. * @return {Boolean} true if the object is a regular expression,
  5153. * false otherwise
  5154. */
  5155. exports.isRegExp = function (object) {
  5156. return Object.prototype.toString.call(object) === "[object RegExp]";
  5157. };
  5158. /**
  5159. * Merge the objects passed as parameters into a new one.
  5160. * @private
  5161. * @param {...Object} var_args All objects to merge.
  5162. * @return {Object} a new object with the data of the others.
  5163. */
  5164. exports.extend = function() {
  5165. var result = {}, i, attr;
  5166. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  5167. for (attr in arguments[i]) {
  5168. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  5169. result[attr] = arguments[i][attr];
  5170. }
  5171. }
  5172. }
  5173. return result;
  5174. };
  5175. },{"./compressions":8,"./nodeBuffer":16,"./support":22}],27:[function(_dereq_,module,exports){
  5176. 'use strict';
  5177. var StringReader = _dereq_('./stringReader');
  5178. var NodeBufferReader = _dereq_('./nodeBufferReader');
  5179. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  5180. var ArrayReader = _dereq_('./arrayReader');
  5181. var utils = _dereq_('./utils');
  5182. var sig = _dereq_('./signature');
  5183. var ZipEntry = _dereq_('./zipEntry');
  5184. var support = _dereq_('./support');
  5185. var jszipProto = _dereq_('./object');
  5186. // class ZipEntries {{{
  5187. /**
  5188. * All the entries in the zip file.
  5189. * @constructor
  5190. * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
  5191. * @param {Object} loadOptions Options for loading the stream.
  5192. */
  5193. function ZipEntries(data, loadOptions) {
  5194. this.files = [];
  5195. this.loadOptions = loadOptions;
  5196. if (data) {
  5197. this.load(data);
  5198. }
  5199. }
  5200. ZipEntries.prototype = {
  5201. /**
  5202. * Check that the reader is on the speficied signature.
  5203. * @param {string} expectedSignature the expected signature.
  5204. * @throws {Error} if it is an other signature.
  5205. */
  5206. checkSignature: function(expectedSignature) {
  5207. var signature = this.reader.readString(4);
  5208. if (signature !== expectedSignature) {
  5209. throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  5210. }
  5211. },
  5212. /**
  5213. * Check if the given signature is at the given index.
  5214. * @param {number} askedIndex the index to check.
  5215. * @param {string} expectedSignature the signature to expect.
  5216. * @return {boolean} true if the signature is here, false otherwise.
  5217. */
  5218. isSignature: function(askedIndex, expectedSignature) {
  5219. var currentIndex = this.reader.index;
  5220. this.reader.setIndex(askedIndex);
  5221. var signature = this.reader.readString(4);
  5222. var result = signature === expectedSignature;
  5223. this.reader.setIndex(currentIndex);
  5224. return result;
  5225. },
  5226. /**
  5227. * Read the end of the central directory.
  5228. */
  5229. readBlockEndOfCentral: function() {
  5230. this.diskNumber = this.reader.readInt(2);
  5231. this.diskWithCentralDirStart = this.reader.readInt(2);
  5232. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  5233. this.centralDirRecords = this.reader.readInt(2);
  5234. this.centralDirSize = this.reader.readInt(4);
  5235. this.centralDirOffset = this.reader.readInt(4);
  5236. this.zipCommentLength = this.reader.readInt(2);
  5237. // warning : the encoding depends of the system locale
  5238. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  5239. // On a windows machine, this field is encoded with the localized windows code page.
  5240. var zipComment = this.reader.readData(this.zipCommentLength);
  5241. var decodeParamType = support.uint8array ? "uint8array" : "array";
  5242. // To get consistent behavior with the generation part, we will assume that
  5243. // this is utf8 encoded unless specified otherwise.
  5244. var decodeContent = utils.transformTo(decodeParamType, zipComment);
  5245. this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  5246. },
  5247. /**
  5248. * Read the end of the Zip 64 central directory.
  5249. * Not merged with the method readEndOfCentral :
  5250. * The end of central can coexist with its Zip64 brother,
  5251. * I don't want to read the wrong number of bytes !
  5252. */
  5253. readBlockZip64EndOfCentral: function() {
  5254. this.zip64EndOfCentralSize = this.reader.readInt(8);
  5255. this.versionMadeBy = this.reader.readString(2);
  5256. this.versionNeeded = this.reader.readInt(2);
  5257. this.diskNumber = this.reader.readInt(4);
  5258. this.diskWithCentralDirStart = this.reader.readInt(4);
  5259. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  5260. this.centralDirRecords = this.reader.readInt(8);
  5261. this.centralDirSize = this.reader.readInt(8);
  5262. this.centralDirOffset = this.reader.readInt(8);
  5263. this.zip64ExtensibleData = {};
  5264. var extraDataSize = this.zip64EndOfCentralSize - 44,
  5265. index = 0,
  5266. extraFieldId,
  5267. extraFieldLength,
  5268. extraFieldValue;
  5269. while (index < extraDataSize) {
  5270. extraFieldId = this.reader.readInt(2);
  5271. extraFieldLength = this.reader.readInt(4);
  5272. extraFieldValue = this.reader.readString(extraFieldLength);
  5273. this.zip64ExtensibleData[extraFieldId] = {
  5274. id: extraFieldId,
  5275. length: extraFieldLength,
  5276. value: extraFieldValue
  5277. };
  5278. }
  5279. },
  5280. /**
  5281. * Read the end of the Zip 64 central directory locator.
  5282. */
  5283. readBlockZip64EndOfCentralLocator: function() {
  5284. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  5285. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  5286. this.disksCount = this.reader.readInt(4);
  5287. if (this.disksCount > 1) {
  5288. throw new Error("Multi-volumes zip are not supported");
  5289. }
  5290. },
  5291. /**
  5292. * Read the local files, based on the offset read in the central part.
  5293. */
  5294. readLocalFiles: function() {
  5295. var i, file;
  5296. for (i = 0; i < this.files.length; i++) {
  5297. file = this.files[i];
  5298. this.reader.setIndex(file.localHeaderOffset);
  5299. this.checkSignature(sig.LOCAL_FILE_HEADER);
  5300. file.readLocalPart(this.reader);
  5301. file.handleUTF8();
  5302. file.processAttributes();
  5303. }
  5304. },
  5305. /**
  5306. * Read the central directory.
  5307. */
  5308. readCentralDir: function() {
  5309. var file;
  5310. this.reader.setIndex(this.centralDirOffset);
  5311. while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
  5312. file = new ZipEntry({
  5313. zip64: this.zip64
  5314. }, this.loadOptions);
  5315. file.readCentralPart(this.reader);
  5316. this.files.push(file);
  5317. }
  5318. if (this.centralDirRecords !== this.files.length) {
  5319. if (this.centralDirRecords !== 0 && this.files.length === 0) {
  5320. // We expected some records but couldn't find ANY.
  5321. // This is really suspicious, as if something went wrong.
  5322. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  5323. } else {
  5324. // We found some records but not all.
  5325. // Something is wrong but we got something for the user: no error here.
  5326. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  5327. }
  5328. }
  5329. },
  5330. /**
  5331. * Read the end of central directory.
  5332. */
  5333. readEndOfCentral: function() {
  5334. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  5335. if (offset < 0) {
  5336. // Check if the content is a truncated zip or complete garbage.
  5337. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  5338. // extractible zip for example) but it can give a good hint.
  5339. // If an ajax request was used without responseType, we will also
  5340. // get unreadable data.
  5341. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  5342. if (isGarbage) {
  5343. throw new Error("Can't find end of central directory : is this a zip file ? " +
  5344. "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
  5345. } else {
  5346. throw new Error("Corrupted zip : can't find end of central directory");
  5347. }
  5348. }
  5349. this.reader.setIndex(offset);
  5350. var endOfCentralDirOffset = offset;
  5351. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  5352. this.readBlockEndOfCentral();
  5353. /* extract from the zip spec :
  5354. 4) If one of the fields in the end of central directory
  5355. record is too small to hold required data, the field
  5356. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  5357. ZIP64 format record should be created.
  5358. 5) The end of central directory record and the
  5359. Zip64 end of central directory locator record must
  5360. reside on the same disk when splitting or spanning
  5361. an archive.
  5362. */
  5363. if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {
  5364. this.zip64 = true;
  5365. /*
  5366. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  5367. the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
  5368. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  5369. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  5370. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  5371. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  5372. */
  5373. // should look for a zip64 EOCD locator
  5374. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  5375. if (offset < 0) {
  5376. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
  5377. }
  5378. this.reader.setIndex(offset);
  5379. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  5380. this.readBlockZip64EndOfCentralLocator();
  5381. // now the zip64 EOCD record
  5382. if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  5383. // console.warn("ZIP64 end of central directory not where expected.");
  5384. this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  5385. if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  5386. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory");
  5387. }
  5388. }
  5389. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  5390. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  5391. this.readBlockZip64EndOfCentral();
  5392. }
  5393. var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  5394. if (this.zip64) {
  5395. expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  5396. expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  5397. }
  5398. var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  5399. if (extraBytes > 0) {
  5400. // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  5401. if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  5402. // The offsets seem wrong, but we have something at the specified offset.
  5403. // So… we keep it.
  5404. } else {
  5405. // the offset is wrong, update the "zero" of the reader
  5406. // this happens if data has been prepended (crx files for example)
  5407. this.reader.zero = extraBytes;
  5408. }
  5409. } else if (extraBytes < 0) {
  5410. throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  5411. }
  5412. },
  5413. prepareReader: function(data) {
  5414. var type = utils.getTypeOf(data);
  5415. utils.checkSupport(type);
  5416. if (type === "string" && !support.uint8array) {
  5417. this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
  5418. }
  5419. else if (type === "nodebuffer") {
  5420. this.reader = new NodeBufferReader(data);
  5421. }
  5422. else if (support.uint8array) {
  5423. this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
  5424. } else if (support.array) {
  5425. this.reader = new ArrayReader(utils.transformTo("array", data));
  5426. } else {
  5427. throw new Error("Unexpected error: unsupported type '" + type + "'");
  5428. }
  5429. },
  5430. /**
  5431. * Read a zip file and create ZipEntries.
  5432. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  5433. */
  5434. load: function(data) {
  5435. this.prepareReader(data);
  5436. this.readEndOfCentral();
  5437. this.readCentralDir();
  5438. this.readLocalFiles();
  5439. }
  5440. };
  5441. // }}} end of ZipEntries
  5442. module.exports = ZipEntries;
  5443. },{"./arrayReader":5,"./nodeBufferReader":17,"./object":18,"./signature":19,"./stringReader":20,"./support":22,"./uint8ArrayReader":23,"./utils":26,"./zipEntry":28}],28:[function(_dereq_,module,exports){
  5444. 'use strict';
  5445. var StringReader = _dereq_('./stringReader');
  5446. var utils = _dereq_('./utils');
  5447. var CompressedObject = _dereq_('./compressedObject');
  5448. var jszipProto = _dereq_('./object');
  5449. var support = _dereq_('./support');
  5450. var MADE_BY_DOS = 0x00;
  5451. var MADE_BY_UNIX = 0x03;
  5452. // class ZipEntry {{{
  5453. /**
  5454. * An entry in the zip file.
  5455. * @constructor
  5456. * @param {Object} options Options of the current file.
  5457. * @param {Object} loadOptions Options for loading the stream.
  5458. */
  5459. function ZipEntry(options, loadOptions) {
  5460. this.options = options;
  5461. this.loadOptions = loadOptions;
  5462. }
  5463. ZipEntry.prototype = {
  5464. /**
  5465. * say if the file is encrypted.
  5466. * @return {boolean} true if the file is encrypted, false otherwise.
  5467. */
  5468. isEncrypted: function() {
  5469. // bit 1 is set
  5470. return (this.bitFlag & 0x0001) === 0x0001;
  5471. },
  5472. /**
  5473. * say if the file has utf-8 filename/comment.
  5474. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  5475. */
  5476. useUTF8: function() {
  5477. // bit 11 is set
  5478. return (this.bitFlag & 0x0800) === 0x0800;
  5479. },
  5480. /**
  5481. * Prepare the function used to generate the compressed content from this ZipFile.
  5482. * @param {DataReader} reader the reader to use.
  5483. * @param {number} from the offset from where we should read the data.
  5484. * @param {number} length the length of the data to read.
  5485. * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
  5486. */
  5487. prepareCompressedContent: function(reader, from, length) {
  5488. return function() {
  5489. var previousIndex = reader.index;
  5490. reader.setIndex(from);
  5491. var compressedFileData = reader.readData(length);
  5492. reader.setIndex(previousIndex);
  5493. return compressedFileData;
  5494. };
  5495. },
  5496. /**
  5497. * Prepare the function used to generate the uncompressed content from this ZipFile.
  5498. * @param {DataReader} reader the reader to use.
  5499. * @param {number} from the offset from where we should read the data.
  5500. * @param {number} length the length of the data to read.
  5501. * @param {JSZip.compression} compression the compression used on this file.
  5502. * @param {number} uncompressedSize the uncompressed size to expect.
  5503. * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
  5504. */
  5505. prepareContent: function(reader, from, length, compression, uncompressedSize) {
  5506. return function() {
  5507. var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
  5508. var uncompressedFileData = compression.uncompress(compressedFileData);
  5509. if (uncompressedFileData.length !== uncompressedSize) {
  5510. throw new Error("Bug : uncompressed data size mismatch");
  5511. }
  5512. return uncompressedFileData;
  5513. };
  5514. },
  5515. /**
  5516. * Read the local part of a zip file and add the info in this object.
  5517. * @param {DataReader} reader the reader to use.
  5518. */
  5519. readLocalPart: function(reader) {
  5520. var compression, localExtraFieldsLength;
  5521. // we already know everything from the central dir !
  5522. // If the central dir data are false, we are doomed.
  5523. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  5524. // The less data we get here, the more reliable this should be.
  5525. // Let's skip the whole header and dash to the data !
  5526. reader.skip(22);
  5527. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  5528. // Strangely, the filename here is OK.
  5529. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  5530. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  5531. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  5532. // the internet.
  5533. //
  5534. // I think I see the logic here : the central directory is used to display
  5535. // content and the local directory is used to extract the files. Mixing / and \
  5536. // may be used to display \ to windows users and use / when extracting the files.
  5537. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  5538. this.fileNameLength = reader.readInt(2);
  5539. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  5540. this.fileName = reader.readData(this.fileNameLength);
  5541. reader.skip(localExtraFieldsLength);
  5542. if (this.compressedSize == -1 || this.uncompressedSize == -1) {
  5543. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
  5544. }
  5545. compression = utils.findCompression(this.compressionMethod);
  5546. if (compression === null) { // no compression found
  5547. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  5548. }
  5549. this.decompressed = new CompressedObject();
  5550. this.decompressed.compressedSize = this.compressedSize;
  5551. this.decompressed.uncompressedSize = this.uncompressedSize;
  5552. this.decompressed.crc32 = this.crc32;
  5553. this.decompressed.compressionMethod = this.compressionMethod;
  5554. this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
  5555. this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
  5556. // we need to compute the crc32...
  5557. if (this.loadOptions.checkCRC32) {
  5558. this.decompressed = utils.transformTo("string", this.decompressed.getContent());
  5559. if (jszipProto.crc32(this.decompressed) !== this.crc32) {
  5560. throw new Error("Corrupted zip : CRC32 mismatch");
  5561. }
  5562. }
  5563. },
  5564. /**
  5565. * Read the central part of a zip file and add the info in this object.
  5566. * @param {DataReader} reader the reader to use.
  5567. */
  5568. readCentralPart: function(reader) {
  5569. this.versionMadeBy = reader.readInt(2);
  5570. this.versionNeeded = reader.readInt(2);
  5571. this.bitFlag = reader.readInt(2);
  5572. this.compressionMethod = reader.readString(2);
  5573. this.date = reader.readDate();
  5574. this.crc32 = reader.readInt(4);
  5575. this.compressedSize = reader.readInt(4);
  5576. this.uncompressedSize = reader.readInt(4);
  5577. this.fileNameLength = reader.readInt(2);
  5578. this.extraFieldsLength = reader.readInt(2);
  5579. this.fileCommentLength = reader.readInt(2);
  5580. this.diskNumberStart = reader.readInt(2);
  5581. this.internalFileAttributes = reader.readInt(2);
  5582. this.externalFileAttributes = reader.readInt(4);
  5583. this.localHeaderOffset = reader.readInt(4);
  5584. if (this.isEncrypted()) {
  5585. throw new Error("Encrypted zip are not supported");
  5586. }
  5587. this.fileName = reader.readData(this.fileNameLength);
  5588. this.readExtraFields(reader);
  5589. this.parseZIP64ExtraField(reader);
  5590. this.fileComment = reader.readData(this.fileCommentLength);
  5591. },
  5592. /**
  5593. * Parse the external file attributes and get the unix/dos permissions.
  5594. */
  5595. processAttributes: function () {
  5596. this.unixPermissions = null;
  5597. this.dosPermissions = null;
  5598. var madeBy = this.versionMadeBy >> 8;
  5599. // Check if we have the DOS directory flag set.
  5600. // We look for it in the DOS and UNIX permissions
  5601. // but some unknown platform could set it as a compatibility flag.
  5602. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  5603. if(madeBy === MADE_BY_DOS) {
  5604. // first 6 bits (0 to 5)
  5605. this.dosPermissions = this.externalFileAttributes & 0x3F;
  5606. }
  5607. if(madeBy === MADE_BY_UNIX) {
  5608. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  5609. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  5610. }
  5611. // fail safe : if the name ends with a / it probably means a folder
  5612. if (!this.dir && this.fileNameStr.slice(-1) === '/') {
  5613. this.dir = true;
  5614. }
  5615. },
  5616. /**
  5617. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  5618. * @param {DataReader} reader the reader to use.
  5619. */
  5620. parseZIP64ExtraField: function(reader) {
  5621. if (!this.extraFields[0x0001]) {
  5622. return;
  5623. }
  5624. // should be something, preparing the extra reader
  5625. var extraReader = new StringReader(this.extraFields[0x0001].value);
  5626. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  5627. // won't let us have more.
  5628. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  5629. this.uncompressedSize = extraReader.readInt(8);
  5630. }
  5631. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  5632. this.compressedSize = extraReader.readInt(8);
  5633. }
  5634. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  5635. this.localHeaderOffset = extraReader.readInt(8);
  5636. }
  5637. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  5638. this.diskNumberStart = extraReader.readInt(4);
  5639. }
  5640. },
  5641. /**
  5642. * Read the central part of a zip file and add the info in this object.
  5643. * @param {DataReader} reader the reader to use.
  5644. */
  5645. readExtraFields: function(reader) {
  5646. var start = reader.index,
  5647. extraFieldId,
  5648. extraFieldLength,
  5649. extraFieldValue;
  5650. this.extraFields = this.extraFields || {};
  5651. while (reader.index < start + this.extraFieldsLength) {
  5652. extraFieldId = reader.readInt(2);
  5653. extraFieldLength = reader.readInt(2);
  5654. extraFieldValue = reader.readString(extraFieldLength);
  5655. this.extraFields[extraFieldId] = {
  5656. id: extraFieldId,
  5657. length: extraFieldLength,
  5658. value: extraFieldValue
  5659. };
  5660. }
  5661. },
  5662. /**
  5663. * Apply an UTF8 transformation if needed.
  5664. */
  5665. handleUTF8: function() {
  5666. var decodeParamType = support.uint8array ? "uint8array" : "array";
  5667. if (this.useUTF8()) {
  5668. this.fileNameStr = jszipProto.utf8decode(this.fileName);
  5669. this.fileCommentStr = jszipProto.utf8decode(this.fileComment);
  5670. } else {
  5671. var upath = this.findExtraFieldUnicodePath();
  5672. if (upath !== null) {
  5673. this.fileNameStr = upath;
  5674. } else {
  5675. var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
  5676. this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  5677. }
  5678. var ucomment = this.findExtraFieldUnicodeComment();
  5679. if (ucomment !== null) {
  5680. this.fileCommentStr = ucomment;
  5681. } else {
  5682. var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
  5683. this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  5684. }
  5685. }
  5686. },
  5687. /**
  5688. * Find the unicode path declared in the extra field, if any.
  5689. * @return {String} the unicode path, null otherwise.
  5690. */
  5691. findExtraFieldUnicodePath: function() {
  5692. var upathField = this.extraFields[0x7075];
  5693. if (upathField) {
  5694. var extraReader = new StringReader(upathField.value);
  5695. // wrong version
  5696. if (extraReader.readInt(1) !== 1) {
  5697. return null;
  5698. }
  5699. // the crc of the filename changed, this field is out of date.
  5700. if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
  5701. return null;
  5702. }
  5703. return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
  5704. }
  5705. return null;
  5706. },
  5707. /**
  5708. * Find the unicode comment declared in the extra field, if any.
  5709. * @return {String} the unicode comment, null otherwise.
  5710. */
  5711. findExtraFieldUnicodeComment: function() {
  5712. var ucommentField = this.extraFields[0x6375];
  5713. if (ucommentField) {
  5714. var extraReader = new StringReader(ucommentField.value);
  5715. // wrong version
  5716. if (extraReader.readInt(1) !== 1) {
  5717. return null;
  5718. }
  5719. // the crc of the comment changed, this field is out of date.
  5720. if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
  5721. return null;
  5722. }
  5723. return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
  5724. }
  5725. return null;
  5726. }
  5727. };
  5728. module.exports = ZipEntry;
  5729. },{"./compressedObject":7,"./object":18,"./stringReader":20,"./support":22,"./utils":26}],29:[function(_dereq_,module,exports){
  5730. // Top level file is just a mixin of submodules & constants
  5731. 'use strict';
  5732. var assign = _dereq_('./lib/utils/common').assign;
  5733. var deflate = _dereq_('./lib/deflate');
  5734. var inflate = _dereq_('./lib/inflate');
  5735. var constants = _dereq_('./lib/zlib/constants');
  5736. var pako = {};
  5737. assign(pako, deflate, inflate, constants);
  5738. module.exports = pako;
  5739. },{"./lib/deflate":30,"./lib/inflate":31,"./lib/utils/common":32,"./lib/zlib/constants":35}],30:[function(_dereq_,module,exports){
  5740. 'use strict';
  5741. var zlib_deflate = _dereq_('./zlib/deflate');
  5742. var utils = _dereq_('./utils/common');
  5743. var strings = _dereq_('./utils/strings');
  5744. var msg = _dereq_('./zlib/messages');
  5745. var ZStream = _dereq_('./zlib/zstream');
  5746. var toString = Object.prototype.toString;
  5747. /* Public constants ==========================================================*/
  5748. /* ===========================================================================*/
  5749. var Z_NO_FLUSH = 0;
  5750. var Z_FINISH = 4;
  5751. var Z_OK = 0;
  5752. var Z_STREAM_END = 1;
  5753. var Z_SYNC_FLUSH = 2;
  5754. var Z_DEFAULT_COMPRESSION = -1;
  5755. var Z_DEFAULT_STRATEGY = 0;
  5756. var Z_DEFLATED = 8;
  5757. /* ===========================================================================*/
  5758. /**
  5759. * class Deflate
  5760. *
  5761. * Generic JS-style wrapper for zlib calls. If you don't need
  5762. * streaming behaviour - use more simple functions: [[deflate]],
  5763. * [[deflateRaw]] and [[gzip]].
  5764. **/
  5765. /* internal
  5766. * Deflate.chunks -> Array
  5767. *
  5768. * Chunks of output data, if [[Deflate#onData]] not overriden.
  5769. **/
  5770. /**
  5771. * Deflate.result -> Uint8Array|Array
  5772. *
  5773. * Compressed result, generated by default [[Deflate#onData]]
  5774. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  5775. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  5776. * push a chunk with explicit flush (call [[Deflate#push]] with
  5777. * `Z_SYNC_FLUSH` param).
  5778. **/
  5779. /**
  5780. * Deflate.err -> Number
  5781. *
  5782. * Error code after deflate finished. 0 (Z_OK) on success.
  5783. * You will not need it in real life, because deflate errors
  5784. * are possible only on wrong options or bad `onData` / `onEnd`
  5785. * custom handlers.
  5786. **/
  5787. /**
  5788. * Deflate.msg -> String
  5789. *
  5790. * Error message, if [[Deflate.err]] != 0
  5791. **/
  5792. /**
  5793. * new Deflate(options)
  5794. * - options (Object): zlib deflate options.
  5795. *
  5796. * Creates new deflator instance with specified params. Throws exception
  5797. * on bad params. Supported options:
  5798. *
  5799. * - `level`
  5800. * - `windowBits`
  5801. * - `memLevel`
  5802. * - `strategy`
  5803. * - `dictionary`
  5804. *
  5805. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5806. * for more information on these.
  5807. *
  5808. * Additional options, for internal needs:
  5809. *
  5810. * - `chunkSize` - size of generated data chunks (16K by default)
  5811. * - `raw` (Boolean) - do raw deflate
  5812. * - `gzip` (Boolean) - create gzip wrapper
  5813. * - `to` (String) - if equal to 'string', then result will be "binary string"
  5814. * (each char code [0..255])
  5815. * - `header` (Object) - custom header for gzip
  5816. * - `text` (Boolean) - true if compressed data believed to be text
  5817. * - `time` (Number) - modification time, unix timestamp
  5818. * - `os` (Number) - operation system code
  5819. * - `extra` (Array) - array of bytes with extra data (max 65536)
  5820. * - `name` (String) - file name (binary string)
  5821. * - `comment` (String) - comment (binary string)
  5822. * - `hcrc` (Boolean) - true if header crc should be added
  5823. *
  5824. * ##### Example:
  5825. *
  5826. * ```javascript
  5827. * var pako = require('pako')
  5828. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5829. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5830. *
  5831. * var deflate = new pako.Deflate({ level: 3});
  5832. *
  5833. * deflate.push(chunk1, false);
  5834. * deflate.push(chunk2, true); // true -> last chunk
  5835. *
  5836. * if (deflate.err) { throw new Error(deflate.err); }
  5837. *
  5838. * console.log(deflate.result);
  5839. * ```
  5840. **/
  5841. function Deflate(options) {
  5842. if (!(this instanceof Deflate)) return new Deflate(options);
  5843. this.options = utils.assign({
  5844. level: Z_DEFAULT_COMPRESSION,
  5845. method: Z_DEFLATED,
  5846. chunkSize: 16384,
  5847. windowBits: 15,
  5848. memLevel: 8,
  5849. strategy: Z_DEFAULT_STRATEGY,
  5850. to: ''
  5851. }, options || {});
  5852. var opt = this.options;
  5853. if (opt.raw && (opt.windowBits > 0)) {
  5854. opt.windowBits = -opt.windowBits;
  5855. }
  5856. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  5857. opt.windowBits += 16;
  5858. }
  5859. this.err = 0; // error code, if happens (0 = Z_OK)
  5860. this.msg = ''; // error message
  5861. this.ended = false; // used to avoid multiple onEnd() calls
  5862. this.chunks = []; // chunks of compressed data
  5863. this.strm = new ZStream();
  5864. this.strm.avail_out = 0;
  5865. var status = zlib_deflate.deflateInit2(
  5866. this.strm,
  5867. opt.level,
  5868. opt.method,
  5869. opt.windowBits,
  5870. opt.memLevel,
  5871. opt.strategy
  5872. );
  5873. if (status !== Z_OK) {
  5874. throw new Error(msg[status]);
  5875. }
  5876. if (opt.header) {
  5877. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  5878. }
  5879. if (opt.dictionary) {
  5880. var dict;
  5881. // Convert data if needed
  5882. if (typeof opt.dictionary === 'string') {
  5883. // If we need to compress text, change encoding to utf8.
  5884. dict = strings.string2buf(opt.dictionary);
  5885. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  5886. dict = new Uint8Array(opt.dictionary);
  5887. } else {
  5888. dict = opt.dictionary;
  5889. }
  5890. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  5891. if (status !== Z_OK) {
  5892. throw new Error(msg[status]);
  5893. }
  5894. this._dict_set = true;
  5895. }
  5896. }
  5897. /**
  5898. * Deflate#push(data[, mode]) -> Boolean
  5899. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  5900. * converted to utf8 byte sequence.
  5901. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5902. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5903. *
  5904. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  5905. * new compressed chunks. Returns `true` on success. The last data block must have
  5906. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5907. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5908. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  5909. *
  5910. * On fail call [[Deflate#onEnd]] with error code and return false.
  5911. *
  5912. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5913. * array format is detected automatically). Also, don't skip last param and always
  5914. * use the same type in your code (boolean or number). That will improve JS speed.
  5915. *
  5916. * For regular `Array`-s make sure all elements are [0..255].
  5917. *
  5918. * ##### Example
  5919. *
  5920. * ```javascript
  5921. * push(chunk, false); // push one of data chunks
  5922. * ...
  5923. * push(chunk, true); // push last chunk
  5924. * ```
  5925. **/
  5926. Deflate.prototype.push = function (data, mode) {
  5927. var strm = this.strm;
  5928. var chunkSize = this.options.chunkSize;
  5929. var status, _mode;
  5930. if (this.ended) { return false; }
  5931. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  5932. // Convert data if needed
  5933. if (typeof data === 'string') {
  5934. // If we need to compress text, change encoding to utf8.
  5935. strm.input = strings.string2buf(data);
  5936. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5937. strm.input = new Uint8Array(data);
  5938. } else {
  5939. strm.input = data;
  5940. }
  5941. strm.next_in = 0;
  5942. strm.avail_in = strm.input.length;
  5943. do {
  5944. if (strm.avail_out === 0) {
  5945. strm.output = new utils.Buf8(chunkSize);
  5946. strm.next_out = 0;
  5947. strm.avail_out = chunkSize;
  5948. }
  5949. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  5950. if (status !== Z_STREAM_END && status !== Z_OK) {
  5951. this.onEnd(status);
  5952. this.ended = true;
  5953. return false;
  5954. }
  5955. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  5956. if (this.options.to === 'string') {
  5957. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  5958. } else {
  5959. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5960. }
  5961. }
  5962. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  5963. // Finalize on the last chunk.
  5964. if (_mode === Z_FINISH) {
  5965. status = zlib_deflate.deflateEnd(this.strm);
  5966. this.onEnd(status);
  5967. this.ended = true;
  5968. return status === Z_OK;
  5969. }
  5970. // callback interim results if Z_SYNC_FLUSH.
  5971. if (_mode === Z_SYNC_FLUSH) {
  5972. this.onEnd(Z_OK);
  5973. strm.avail_out = 0;
  5974. return true;
  5975. }
  5976. return true;
  5977. };
  5978. /**
  5979. * Deflate#onData(chunk) -> Void
  5980. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5981. * on js engine support. When string output requested, each chunk
  5982. * will be string.
  5983. *
  5984. * By default, stores data blocks in `chunks[]` property and glue
  5985. * those in `onEnd`. Override this handler, if you need another behaviour.
  5986. **/
  5987. Deflate.prototype.onData = function (chunk) {
  5988. this.chunks.push(chunk);
  5989. };
  5990. /**
  5991. * Deflate#onEnd(status) -> Void
  5992. * - status (Number): deflate status. 0 (Z_OK) on success,
  5993. * other if not.
  5994. *
  5995. * Called once after you tell deflate that the input stream is
  5996. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5997. * or if an error happened. By default - join collected chunks,
  5998. * free memory and fill `results` / `err` properties.
  5999. **/
  6000. Deflate.prototype.onEnd = function (status) {
  6001. // On success - join
  6002. if (status === Z_OK) {
  6003. if (this.options.to === 'string') {
  6004. this.result = this.chunks.join('');
  6005. } else {
  6006. this.result = utils.flattenChunks(this.chunks);
  6007. }
  6008. }
  6009. this.chunks = [];
  6010. this.err = status;
  6011. this.msg = this.strm.msg;
  6012. };
  6013. /**
  6014. * deflate(data[, options]) -> Uint8Array|Array|String
  6015. * - data (Uint8Array|Array|String): input data to compress.
  6016. * - options (Object): zlib deflate options.
  6017. *
  6018. * Compress `data` with deflate algorithm and `options`.
  6019. *
  6020. * Supported options are:
  6021. *
  6022. * - level
  6023. * - windowBits
  6024. * - memLevel
  6025. * - strategy
  6026. * - dictionary
  6027. *
  6028. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  6029. * for more information on these.
  6030. *
  6031. * Sugar (options):
  6032. *
  6033. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  6034. * negative windowBits implicitly.
  6035. * - `to` (String) - if equal to 'string', then result will be "binary string"
  6036. * (each char code [0..255])
  6037. *
  6038. * ##### Example:
  6039. *
  6040. * ```javascript
  6041. * var pako = require('pako')
  6042. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  6043. *
  6044. * console.log(pako.deflate(data));
  6045. * ```
  6046. **/
  6047. function deflate(input, options) {
  6048. var deflator = new Deflate(options);
  6049. deflator.push(input, true);
  6050. // That will never happens, if you don't cheat with options :)
  6051. if (deflator.err) { throw deflator.msg; }
  6052. return deflator.result;
  6053. }
  6054. /**
  6055. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  6056. * - data (Uint8Array|Array|String): input data to compress.
  6057. * - options (Object): zlib deflate options.
  6058. *
  6059. * The same as [[deflate]], but creates raw data, without wrapper
  6060. * (header and adler32 crc).
  6061. **/
  6062. function deflateRaw(input, options) {
  6063. options = options || {};
  6064. options.raw = true;
  6065. return deflate(input, options);
  6066. }
  6067. /**
  6068. * gzip(data[, options]) -> Uint8Array|Array|String
  6069. * - data (Uint8Array|Array|String): input data to compress.
  6070. * - options (Object): zlib deflate options.
  6071. *
  6072. * The same as [[deflate]], but create gzip wrapper instead of
  6073. * deflate one.
  6074. **/
  6075. function gzip(input, options) {
  6076. options = options || {};
  6077. options.gzip = true;
  6078. return deflate(input, options);
  6079. }
  6080. exports.Deflate = Deflate;
  6081. exports.deflate = deflate;
  6082. exports.deflateRaw = deflateRaw;
  6083. exports.gzip = gzip;
  6084. },{"./utils/common":32,"./utils/strings":33,"./zlib/deflate":37,"./zlib/messages":42,"./zlib/zstream":44}],31:[function(_dereq_,module,exports){
  6085. 'use strict';
  6086. var zlib_inflate = _dereq_('./zlib/inflate');
  6087. var utils = _dereq_('./utils/common');
  6088. var strings = _dereq_('./utils/strings');
  6089. var c = _dereq_('./zlib/constants');
  6090. var msg = _dereq_('./zlib/messages');
  6091. var ZStream = _dereq_('./zlib/zstream');
  6092. var GZheader = _dereq_('./zlib/gzheader');
  6093. var toString = Object.prototype.toString;
  6094. /**
  6095. * class Inflate
  6096. *
  6097. * Generic JS-style wrapper for zlib calls. If you don't need
  6098. * streaming behaviour - use more simple functions: [[inflate]]
  6099. * and [[inflateRaw]].
  6100. **/
  6101. /* internal
  6102. * inflate.chunks -> Array
  6103. *
  6104. * Chunks of output data, if [[Inflate#onData]] not overriden.
  6105. **/
  6106. /**
  6107. * Inflate.result -> Uint8Array|Array|String
  6108. *
  6109. * Uncompressed result, generated by default [[Inflate#onData]]
  6110. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  6111. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  6112. * push a chunk with explicit flush (call [[Inflate#push]] with
  6113. * `Z_SYNC_FLUSH` param).
  6114. **/
  6115. /**
  6116. * Inflate.err -> Number
  6117. *
  6118. * Error code after inflate finished. 0 (Z_OK) on success.
  6119. * Should be checked if broken data possible.
  6120. **/
  6121. /**
  6122. * Inflate.msg -> String
  6123. *
  6124. * Error message, if [[Inflate.err]] != 0
  6125. **/
  6126. /**
  6127. * new Inflate(options)
  6128. * - options (Object): zlib inflate options.
  6129. *
  6130. * Creates new inflator instance with specified params. Throws exception
  6131. * on bad params. Supported options:
  6132. *
  6133. * - `windowBits`
  6134. * - `dictionary`
  6135. *
  6136. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  6137. * for more information on these.
  6138. *
  6139. * Additional options, for internal needs:
  6140. *
  6141. * - `chunkSize` - size of generated data chunks (16K by default)
  6142. * - `raw` (Boolean) - do raw inflate
  6143. * - `to` (String) - if equal to 'string', then result will be converted
  6144. * from utf8 to utf16 (javascript) string. When string output requested,
  6145. * chunk length can differ from `chunkSize`, depending on content.
  6146. *
  6147. * By default, when no options set, autodetect deflate/gzip data format via
  6148. * wrapper header.
  6149. *
  6150. * ##### Example:
  6151. *
  6152. * ```javascript
  6153. * var pako = require('pako')
  6154. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  6155. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  6156. *
  6157. * var inflate = new pako.Inflate({ level: 3});
  6158. *
  6159. * inflate.push(chunk1, false);
  6160. * inflate.push(chunk2, true); // true -> last chunk
  6161. *
  6162. * if (inflate.err) { throw new Error(inflate.err); }
  6163. *
  6164. * console.log(inflate.result);
  6165. * ```
  6166. **/
  6167. function Inflate(options) {
  6168. if (!(this instanceof Inflate)) return new Inflate(options);
  6169. this.options = utils.assign({
  6170. chunkSize: 16384,
  6171. windowBits: 0,
  6172. to: ''
  6173. }, options || {});
  6174. var opt = this.options;
  6175. // Force window size for `raw` data, if not set directly,
  6176. // because we have no header for autodetect.
  6177. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  6178. opt.windowBits = -opt.windowBits;
  6179. if (opt.windowBits === 0) { opt.windowBits = -15; }
  6180. }
  6181. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  6182. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  6183. !(options && options.windowBits)) {
  6184. opt.windowBits += 32;
  6185. }
  6186. // Gzip header has no info about windows size, we can do autodetect only
  6187. // for deflate. So, if window size not set, force it to max when gzip possible
  6188. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  6189. // bit 3 (16) -> gzipped data
  6190. // bit 4 (32) -> autodetect gzip/deflate
  6191. if ((opt.windowBits & 15) === 0) {
  6192. opt.windowBits |= 15;
  6193. }
  6194. }
  6195. this.err = 0; // error code, if happens (0 = Z_OK)
  6196. this.msg = ''; // error message
  6197. this.ended = false; // used to avoid multiple onEnd() calls
  6198. this.chunks = []; // chunks of compressed data
  6199. this.strm = new ZStream();
  6200. this.strm.avail_out = 0;
  6201. var status = zlib_inflate.inflateInit2(
  6202. this.strm,
  6203. opt.windowBits
  6204. );
  6205. if (status !== c.Z_OK) {
  6206. throw new Error(msg[status]);
  6207. }
  6208. this.header = new GZheader();
  6209. zlib_inflate.inflateGetHeader(this.strm, this.header);
  6210. }
  6211. /**
  6212. * Inflate#push(data[, mode]) -> Boolean
  6213. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  6214. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  6215. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  6216. *
  6217. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  6218. * new output chunks. Returns `true` on success. The last data block must have
  6219. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  6220. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  6221. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  6222. *
  6223. * On fail call [[Inflate#onEnd]] with error code and return false.
  6224. *
  6225. * We strongly recommend to use `Uint8Array` on input for best speed (output
  6226. * format is detected automatically). Also, don't skip last param and always
  6227. * use the same type in your code (boolean or number). That will improve JS speed.
  6228. *
  6229. * For regular `Array`-s make sure all elements are [0..255].
  6230. *
  6231. * ##### Example
  6232. *
  6233. * ```javascript
  6234. * push(chunk, false); // push one of data chunks
  6235. * ...
  6236. * push(chunk, true); // push last chunk
  6237. * ```
  6238. **/
  6239. Inflate.prototype.push = function (data, mode) {
  6240. var strm = this.strm;
  6241. var chunkSize = this.options.chunkSize;
  6242. var dictionary = this.options.dictionary;
  6243. var status, _mode;
  6244. var next_out_utf8, tail, utf8str;
  6245. var dict;
  6246. // Flag to properly process Z_BUF_ERROR on testing inflate call
  6247. // when we check that all output data was flushed.
  6248. var allowBufError = false;
  6249. if (this.ended) { return false; }
  6250. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  6251. // Convert data if needed
  6252. if (typeof data === 'string') {
  6253. // Only binary strings can be decompressed on practice
  6254. strm.input = strings.binstring2buf(data);
  6255. } else if (toString.call(data) === '[object ArrayBuffer]') {
  6256. strm.input = new Uint8Array(data);
  6257. } else {
  6258. strm.input = data;
  6259. }
  6260. strm.next_in = 0;
  6261. strm.avail_in = strm.input.length;
  6262. do {
  6263. if (strm.avail_out === 0) {
  6264. strm.output = new utils.Buf8(chunkSize);
  6265. strm.next_out = 0;
  6266. strm.avail_out = chunkSize;
  6267. }
  6268. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  6269. if (status === c.Z_NEED_DICT && dictionary) {
  6270. // Convert data if needed
  6271. if (typeof dictionary === 'string') {
  6272. dict = strings.string2buf(dictionary);
  6273. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  6274. dict = new Uint8Array(dictionary);
  6275. } else {
  6276. dict = dictionary;
  6277. }
  6278. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  6279. }
  6280. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  6281. status = c.Z_OK;
  6282. allowBufError = false;
  6283. }
  6284. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  6285. this.onEnd(status);
  6286. this.ended = true;
  6287. return false;
  6288. }
  6289. if (strm.next_out) {
  6290. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  6291. if (this.options.to === 'string') {
  6292. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  6293. tail = strm.next_out - next_out_utf8;
  6294. utf8str = strings.buf2string(strm.output, next_out_utf8);
  6295. // move tail
  6296. strm.next_out = tail;
  6297. strm.avail_out = chunkSize - tail;
  6298. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  6299. this.onData(utf8str);
  6300. } else {
  6301. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  6302. }
  6303. }
  6304. }
  6305. // When no more input data, we should check that internal inflate buffers
  6306. // are flushed. The only way to do it when avail_out = 0 - run one more
  6307. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  6308. // Here we set flag to process this error properly.
  6309. //
  6310. // NOTE. Deflate does not return error in this case and does not needs such
  6311. // logic.
  6312. if (strm.avail_in === 0 && strm.avail_out === 0) {
  6313. allowBufError = true;
  6314. }
  6315. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  6316. if (status === c.Z_STREAM_END) {
  6317. _mode = c.Z_FINISH;
  6318. }
  6319. // Finalize on the last chunk.
  6320. if (_mode === c.Z_FINISH) {
  6321. status = zlib_inflate.inflateEnd(this.strm);
  6322. this.onEnd(status);
  6323. this.ended = true;
  6324. return status === c.Z_OK;
  6325. }
  6326. // callback interim results if Z_SYNC_FLUSH.
  6327. if (_mode === c.Z_SYNC_FLUSH) {
  6328. this.onEnd(c.Z_OK);
  6329. strm.avail_out = 0;
  6330. return true;
  6331. }
  6332. return true;
  6333. };
  6334. /**
  6335. * Inflate#onData(chunk) -> Void
  6336. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  6337. * on js engine support. When string output requested, each chunk
  6338. * will be string.
  6339. *
  6340. * By default, stores data blocks in `chunks[]` property and glue
  6341. * those in `onEnd`. Override this handler, if you need another behaviour.
  6342. **/
  6343. Inflate.prototype.onData = function (chunk) {
  6344. this.chunks.push(chunk);
  6345. };
  6346. /**
  6347. * Inflate#onEnd(status) -> Void
  6348. * - status (Number): inflate status. 0 (Z_OK) on success,
  6349. * other if not.
  6350. *
  6351. * Called either after you tell inflate that the input stream is
  6352. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  6353. * or if an error happened. By default - join collected chunks,
  6354. * free memory and fill `results` / `err` properties.
  6355. **/
  6356. Inflate.prototype.onEnd = function (status) {
  6357. // On success - join
  6358. if (status === c.Z_OK) {
  6359. if (this.options.to === 'string') {
  6360. // Glue & convert here, until we teach pako to send
  6361. // utf8 alligned strings to onData
  6362. this.result = this.chunks.join('');
  6363. } else {
  6364. this.result = utils.flattenChunks(this.chunks);
  6365. }
  6366. }
  6367. this.chunks = [];
  6368. this.err = status;
  6369. this.msg = this.strm.msg;
  6370. };
  6371. /**
  6372. * inflate(data[, options]) -> Uint8Array|Array|String
  6373. * - data (Uint8Array|Array|String): input data to decompress.
  6374. * - options (Object): zlib inflate options.
  6375. *
  6376. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  6377. * format via wrapper header by default. That's why we don't provide
  6378. * separate `ungzip` method.
  6379. *
  6380. * Supported options are:
  6381. *
  6382. * - windowBits
  6383. *
  6384. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  6385. * for more information.
  6386. *
  6387. * Sugar (options):
  6388. *
  6389. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  6390. * negative windowBits implicitly.
  6391. * - `to` (String) - if equal to 'string', then result will be converted
  6392. * from utf8 to utf16 (javascript) string. When string output requested,
  6393. * chunk length can differ from `chunkSize`, depending on content.
  6394. *
  6395. *
  6396. * ##### Example:
  6397. *
  6398. * ```javascript
  6399. * var pako = require('pako')
  6400. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  6401. * , output;
  6402. *
  6403. * try {
  6404. * output = pako.inflate(input);
  6405. * } catch (err)
  6406. * console.log(err);
  6407. * }
  6408. * ```
  6409. **/
  6410. function inflate(input, options) {
  6411. var inflator = new Inflate(options);
  6412. inflator.push(input, true);
  6413. // That will never happens, if you don't cheat with options :)
  6414. if (inflator.err) { throw inflator.msg; }
  6415. return inflator.result;
  6416. }
  6417. /**
  6418. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  6419. * - data (Uint8Array|Array|String): input data to decompress.
  6420. * - options (Object): zlib inflate options.
  6421. *
  6422. * The same as [[inflate]], but creates raw data, without wrapper
  6423. * (header and adler32 crc).
  6424. **/
  6425. function inflateRaw(input, options) {
  6426. options = options || {};
  6427. options.raw = true;
  6428. return inflate(input, options);
  6429. }
  6430. /**
  6431. * ungzip(data[, options]) -> Uint8Array|Array|String
  6432. * - data (Uint8Array|Array|String): input data to decompress.
  6433. * - options (Object): zlib inflate options.
  6434. *
  6435. * Just shortcut to [[inflate]], because it autodetects format
  6436. * by header.content. Done for convenience.
  6437. **/
  6438. exports.Inflate = Inflate;
  6439. exports.inflate = inflate;
  6440. exports.inflateRaw = inflateRaw;
  6441. exports.ungzip = inflate;
  6442. },{"./utils/common":32,"./utils/strings":33,"./zlib/constants":35,"./zlib/gzheader":38,"./zlib/inflate":40,"./zlib/messages":42,"./zlib/zstream":44}],32:[function(_dereq_,module,exports){
  6443. 'use strict';
  6444. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  6445. (typeof Uint16Array !== 'undefined') &&
  6446. (typeof Int32Array !== 'undefined');
  6447. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  6448. var sources = Array.prototype.slice.call(arguments, 1);
  6449. while (sources.length) {
  6450. var source = sources.shift();
  6451. if (!source) { continue; }
  6452. if (typeof source !== 'object') {
  6453. throw new TypeError(source + 'must be non-object');
  6454. }
  6455. for (var p in source) {
  6456. if (source.hasOwnProperty(p)) {
  6457. obj[p] = source[p];
  6458. }
  6459. }
  6460. }
  6461. return obj;
  6462. };
  6463. // reduce buffer size, avoiding mem copy
  6464. exports.shrinkBuf = function (buf, size) {
  6465. if (buf.length === size) { return buf; }
  6466. if (buf.subarray) { return buf.subarray(0, size); }
  6467. buf.length = size;
  6468. return buf;
  6469. };
  6470. var fnTyped = {
  6471. arraySet: function (dest, src, src_offs, len, dest_offs) {
  6472. if (src.subarray && dest.subarray) {
  6473. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  6474. return;
  6475. }
  6476. // Fallback to ordinary array
  6477. for (var i = 0; i < len; i++) {
  6478. dest[dest_offs + i] = src[src_offs + i];
  6479. }
  6480. },
  6481. // Join array of chunks to single array.
  6482. flattenChunks: function (chunks) {
  6483. var i, l, len, pos, chunk, result;
  6484. // calculate data length
  6485. len = 0;
  6486. for (i = 0, l = chunks.length; i < l; i++) {
  6487. len += chunks[i].length;
  6488. }
  6489. // join chunks
  6490. result = new Uint8Array(len);
  6491. pos = 0;
  6492. for (i = 0, l = chunks.length; i < l; i++) {
  6493. chunk = chunks[i];
  6494. result.set(chunk, pos);
  6495. pos += chunk.length;
  6496. }
  6497. return result;
  6498. }
  6499. };
  6500. var fnUntyped = {
  6501. arraySet: function (dest, src, src_offs, len, dest_offs) {
  6502. for (var i = 0; i < len; i++) {
  6503. dest[dest_offs + i] = src[src_offs + i];
  6504. }
  6505. },
  6506. // Join array of chunks to single array.
  6507. flattenChunks: function (chunks) {
  6508. return [].concat.apply([], chunks);
  6509. }
  6510. };
  6511. // Enable/Disable typed arrays use, for testing
  6512. //
  6513. exports.setTyped = function (on) {
  6514. if (on) {
  6515. exports.Buf8 = Uint8Array;
  6516. exports.Buf16 = Uint16Array;
  6517. exports.Buf32 = Int32Array;
  6518. exports.assign(exports, fnTyped);
  6519. } else {
  6520. exports.Buf8 = Array;
  6521. exports.Buf16 = Array;
  6522. exports.Buf32 = Array;
  6523. exports.assign(exports, fnUntyped);
  6524. }
  6525. };
  6526. exports.setTyped(TYPED_OK);
  6527. },{}],33:[function(_dereq_,module,exports){
  6528. // String encode/decode helpers
  6529. 'use strict';
  6530. var utils = _dereq_('./common');
  6531. // Quick check if we can use fast array to bin string conversion
  6532. //
  6533. // - apply(Array) can fail on Android 2.2
  6534. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  6535. //
  6536. var STR_APPLY_OK = true;
  6537. var STR_APPLY_UIA_OK = true;
  6538. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  6539. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  6540. // Table with utf8 lengths (calculated by first byte of sequence)
  6541. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  6542. // because max possible codepoint is 0x10ffff
  6543. var _utf8len = new utils.Buf8(256);
  6544. for (var q = 0; q < 256; q++) {
  6545. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  6546. }
  6547. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  6548. // convert string to array (typed, when possible)
  6549. exports.string2buf = function (str) {
  6550. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  6551. // count binary size
  6552. for (m_pos = 0; m_pos < str_len; m_pos++) {
  6553. c = str.charCodeAt(m_pos);
  6554. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  6555. c2 = str.charCodeAt(m_pos + 1);
  6556. if ((c2 & 0xfc00) === 0xdc00) {
  6557. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  6558. m_pos++;
  6559. }
  6560. }
  6561. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  6562. }
  6563. // allocate buffer
  6564. buf = new utils.Buf8(buf_len);
  6565. // convert
  6566. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  6567. c = str.charCodeAt(m_pos);
  6568. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  6569. c2 = str.charCodeAt(m_pos + 1);
  6570. if ((c2 & 0xfc00) === 0xdc00) {
  6571. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  6572. m_pos++;
  6573. }
  6574. }
  6575. if (c < 0x80) {
  6576. /* one byte */
  6577. buf[i++] = c;
  6578. } else if (c < 0x800) {
  6579. /* two bytes */
  6580. buf[i++] = 0xC0 | (c >>> 6);
  6581. buf[i++] = 0x80 | (c & 0x3f);
  6582. } else if (c < 0x10000) {
  6583. /* three bytes */
  6584. buf[i++] = 0xE0 | (c >>> 12);
  6585. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  6586. buf[i++] = 0x80 | (c & 0x3f);
  6587. } else {
  6588. /* four bytes */
  6589. buf[i++] = 0xf0 | (c >>> 18);
  6590. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  6591. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  6592. buf[i++] = 0x80 | (c & 0x3f);
  6593. }
  6594. }
  6595. return buf;
  6596. };
  6597. // Helper (used in 2 places)
  6598. function buf2binstring(buf, len) {
  6599. // use fallback for big arrays to avoid stack overflow
  6600. if (len < 65537) {
  6601. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  6602. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  6603. }
  6604. }
  6605. var result = '';
  6606. for (var i = 0; i < len; i++) {
  6607. result += String.fromCharCode(buf[i]);
  6608. }
  6609. return result;
  6610. }
  6611. // Convert byte array to binary string
  6612. exports.buf2binstring = function (buf) {
  6613. return buf2binstring(buf, buf.length);
  6614. };
  6615. // Convert binary string (typed, when possible)
  6616. exports.binstring2buf = function (str) {
  6617. var buf = new utils.Buf8(str.length);
  6618. for (var i = 0, len = buf.length; i < len; i++) {
  6619. buf[i] = str.charCodeAt(i);
  6620. }
  6621. return buf;
  6622. };
  6623. // convert array to string
  6624. exports.buf2string = function (buf, max) {
  6625. var i, out, c, c_len;
  6626. var len = max || buf.length;
  6627. // Reserve max possible length (2 words per char)
  6628. // NB: by unknown reasons, Array is significantly faster for
  6629. // String.fromCharCode.apply than Uint16Array.
  6630. var utf16buf = new Array(len * 2);
  6631. for (out = 0, i = 0; i < len;) {
  6632. c = buf[i++];
  6633. // quick process ascii
  6634. if (c < 0x80) { utf16buf[out++] = c; continue; }
  6635. c_len = _utf8len[c];
  6636. // skip 5 & 6 byte codes
  6637. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  6638. // apply mask on first byte
  6639. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  6640. // join the rest
  6641. while (c_len > 1 && i < len) {
  6642. c = (c << 6) | (buf[i++] & 0x3f);
  6643. c_len--;
  6644. }
  6645. // terminated by end of string?
  6646. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  6647. if (c < 0x10000) {
  6648. utf16buf[out++] = c;
  6649. } else {
  6650. c -= 0x10000;
  6651. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  6652. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  6653. }
  6654. }
  6655. return buf2binstring(utf16buf, out);
  6656. };
  6657. // Calculate max possible position in utf8 buffer,
  6658. // that will not break sequence. If that's not possible
  6659. // - (very small limits) return max size as is.
  6660. //
  6661. // buf[] - utf8 bytes array
  6662. // max - length limit (mandatory);
  6663. exports.utf8border = function (buf, max) {
  6664. var pos;
  6665. max = max || buf.length;
  6666. if (max > buf.length) { max = buf.length; }
  6667. // go back from last position, until start of sequence found
  6668. pos = max - 1;
  6669. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  6670. // Fuckup - very small and broken sequence,
  6671. // return max, because we should return something anyway.
  6672. if (pos < 0) { return max; }
  6673. // If we came to start of buffer - that means vuffer is too small,
  6674. // return max too.
  6675. if (pos === 0) { return max; }
  6676. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  6677. };
  6678. },{"./common":32}],34:[function(_dereq_,module,exports){
  6679. 'use strict';
  6680. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  6681. // It doesn't worth to make additional optimizationa as in original.
  6682. // Small size is preferable.
  6683. function adler32(adler, buf, len, pos) {
  6684. var s1 = (adler & 0xffff) |0,
  6685. s2 = ((adler >>> 16) & 0xffff) |0,
  6686. n = 0;
  6687. while (len !== 0) {
  6688. // Set limit ~ twice less than 5552, to keep
  6689. // s2 in 31-bits, because we force signed ints.
  6690. // in other case %= will fail.
  6691. n = len > 2000 ? 2000 : len;
  6692. len -= n;
  6693. do {
  6694. s1 = (s1 + buf[pos++]) |0;
  6695. s2 = (s2 + s1) |0;
  6696. } while (--n);
  6697. s1 %= 65521;
  6698. s2 %= 65521;
  6699. }
  6700. return (s1 | (s2 << 16)) |0;
  6701. }
  6702. module.exports = adler32;
  6703. },{}],35:[function(_dereq_,module,exports){
  6704. 'use strict';
  6705. module.exports = {
  6706. /* Allowed flush values; see deflate() and inflate() below for details */
  6707. Z_NO_FLUSH: 0,
  6708. Z_PARTIAL_FLUSH: 1,
  6709. Z_SYNC_FLUSH: 2,
  6710. Z_FULL_FLUSH: 3,
  6711. Z_FINISH: 4,
  6712. Z_BLOCK: 5,
  6713. Z_TREES: 6,
  6714. /* Return codes for the compression/decompression functions. Negative values
  6715. * are errors, positive values are used for special but normal events.
  6716. */
  6717. Z_OK: 0,
  6718. Z_STREAM_END: 1,
  6719. Z_NEED_DICT: 2,
  6720. Z_ERRNO: -1,
  6721. Z_STREAM_ERROR: -2,
  6722. Z_DATA_ERROR: -3,
  6723. //Z_MEM_ERROR: -4,
  6724. Z_BUF_ERROR: -5,
  6725. //Z_VERSION_ERROR: -6,
  6726. /* compression levels */
  6727. Z_NO_COMPRESSION: 0,
  6728. Z_BEST_SPEED: 1,
  6729. Z_BEST_COMPRESSION: 9,
  6730. Z_DEFAULT_COMPRESSION: -1,
  6731. Z_FILTERED: 1,
  6732. Z_HUFFMAN_ONLY: 2,
  6733. Z_RLE: 3,
  6734. Z_FIXED: 4,
  6735. Z_DEFAULT_STRATEGY: 0,
  6736. /* Possible values of the data_type field (though see inflate()) */
  6737. Z_BINARY: 0,
  6738. Z_TEXT: 1,
  6739. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  6740. Z_UNKNOWN: 2,
  6741. /* The deflate compression method */
  6742. Z_DEFLATED: 8
  6743. //Z_NULL: null // Use -1 or null inline, depending on var type
  6744. };
  6745. },{}],36:[function(_dereq_,module,exports){
  6746. 'use strict';
  6747. // Note: we can't get significant speed boost here.
  6748. // So write code to minimize size - no pregenerated tables
  6749. // and array tools dependencies.
  6750. // Use ordinary array, since untyped makes no boost here
  6751. function makeTable() {
  6752. var c, table = [];
  6753. for (var n = 0; n < 256; n++) {
  6754. c = n;
  6755. for (var k = 0; k < 8; k++) {
  6756. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  6757. }
  6758. table[n] = c;
  6759. }
  6760. return table;
  6761. }
  6762. // Create table on load. Just 255 signed longs. Not a problem.
  6763. var crcTable = makeTable();
  6764. function crc32(crc, buf, len, pos) {
  6765. var t = crcTable,
  6766. end = pos + len;
  6767. crc ^= -1;
  6768. for (var i = pos; i < end; i++) {
  6769. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  6770. }
  6771. return (crc ^ (-1)); // >>> 0;
  6772. }
  6773. module.exports = crc32;
  6774. },{}],37:[function(_dereq_,module,exports){
  6775. 'use strict';
  6776. var utils = _dereq_('../utils/common');
  6777. var trees = _dereq_('./trees');
  6778. var adler32 = _dereq_('./adler32');
  6779. var crc32 = _dereq_('./crc32');
  6780. var msg = _dereq_('./messages');
  6781. /* Public constants ==========================================================*/
  6782. /* ===========================================================================*/
  6783. /* Allowed flush values; see deflate() and inflate() below for details */
  6784. var Z_NO_FLUSH = 0;
  6785. var Z_PARTIAL_FLUSH = 1;
  6786. //var Z_SYNC_FLUSH = 2;
  6787. var Z_FULL_FLUSH = 3;
  6788. var Z_FINISH = 4;
  6789. var Z_BLOCK = 5;
  6790. //var Z_TREES = 6;
  6791. /* Return codes for the compression/decompression functions. Negative values
  6792. * are errors, positive values are used for special but normal events.
  6793. */
  6794. var Z_OK = 0;
  6795. var Z_STREAM_END = 1;
  6796. //var Z_NEED_DICT = 2;
  6797. //var Z_ERRNO = -1;
  6798. var Z_STREAM_ERROR = -2;
  6799. var Z_DATA_ERROR = -3;
  6800. //var Z_MEM_ERROR = -4;
  6801. var Z_BUF_ERROR = -5;
  6802. //var Z_VERSION_ERROR = -6;
  6803. /* compression levels */
  6804. //var Z_NO_COMPRESSION = 0;
  6805. //var Z_BEST_SPEED = 1;
  6806. //var Z_BEST_COMPRESSION = 9;
  6807. var Z_DEFAULT_COMPRESSION = -1;
  6808. var Z_FILTERED = 1;
  6809. var Z_HUFFMAN_ONLY = 2;
  6810. var Z_RLE = 3;
  6811. var Z_FIXED = 4;
  6812. var Z_DEFAULT_STRATEGY = 0;
  6813. /* Possible values of the data_type field (though see inflate()) */
  6814. //var Z_BINARY = 0;
  6815. //var Z_TEXT = 1;
  6816. //var Z_ASCII = 1; // = Z_TEXT
  6817. var Z_UNKNOWN = 2;
  6818. /* The deflate compression method */
  6819. var Z_DEFLATED = 8;
  6820. /*============================================================================*/
  6821. var MAX_MEM_LEVEL = 9;
  6822. /* Maximum value for memLevel in deflateInit2 */
  6823. var MAX_WBITS = 15;
  6824. /* 32K LZ77 window */
  6825. var DEF_MEM_LEVEL = 8;
  6826. var LENGTH_CODES = 29;
  6827. /* number of length codes, not counting the special END_BLOCK code */
  6828. var LITERALS = 256;
  6829. /* number of literal bytes 0..255 */
  6830. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  6831. /* number of Literal or Length codes, including the END_BLOCK code */
  6832. var D_CODES = 30;
  6833. /* number of distance codes */
  6834. var BL_CODES = 19;
  6835. /* number of codes used to transfer the bit lengths */
  6836. var HEAP_SIZE = 2 * L_CODES + 1;
  6837. /* maximum heap size */
  6838. var MAX_BITS = 15;
  6839. /* All codes must not exceed MAX_BITS bits */
  6840. var MIN_MATCH = 3;
  6841. var MAX_MATCH = 258;
  6842. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  6843. var PRESET_DICT = 0x20;
  6844. var INIT_STATE = 42;
  6845. var EXTRA_STATE = 69;
  6846. var NAME_STATE = 73;
  6847. var COMMENT_STATE = 91;
  6848. var HCRC_STATE = 103;
  6849. var BUSY_STATE = 113;
  6850. var FINISH_STATE = 666;
  6851. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  6852. var BS_BLOCK_DONE = 2; /* block flush performed */
  6853. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  6854. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  6855. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  6856. function err(strm, errorCode) {
  6857. strm.msg = msg[errorCode];
  6858. return errorCode;
  6859. }
  6860. function rank(f) {
  6861. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  6862. }
  6863. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6864. /* =========================================================================
  6865. * Flush as much pending output as possible. All deflate() output goes
  6866. * through this function so some applications may wish to modify it
  6867. * to avoid allocating a large strm->output buffer and copying into it.
  6868. * (See also read_buf()).
  6869. */
  6870. function flush_pending(strm) {
  6871. var s = strm.state;
  6872. //_tr_flush_bits(s);
  6873. var len = s.pending;
  6874. if (len > strm.avail_out) {
  6875. len = strm.avail_out;
  6876. }
  6877. if (len === 0) { return; }
  6878. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  6879. strm.next_out += len;
  6880. s.pending_out += len;
  6881. strm.total_out += len;
  6882. strm.avail_out -= len;
  6883. s.pending -= len;
  6884. if (s.pending === 0) {
  6885. s.pending_out = 0;
  6886. }
  6887. }
  6888. function flush_block_only(s, last) {
  6889. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  6890. s.block_start = s.strstart;
  6891. flush_pending(s.strm);
  6892. }
  6893. function put_byte(s, b) {
  6894. s.pending_buf[s.pending++] = b;
  6895. }
  6896. /* =========================================================================
  6897. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  6898. * IN assertion: the stream state is correct and there is enough room in
  6899. * pending_buf.
  6900. */
  6901. function putShortMSB(s, b) {
  6902. // put_byte(s, (Byte)(b >> 8));
  6903. // put_byte(s, (Byte)(b & 0xff));
  6904. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  6905. s.pending_buf[s.pending++] = b & 0xff;
  6906. }
  6907. /* ===========================================================================
  6908. * Read a new buffer from the current input stream, update the adler32
  6909. * and total number of bytes read. All deflate() input goes through
  6910. * this function so some applications may wish to modify it to avoid
  6911. * allocating a large strm->input buffer and copying from it.
  6912. * (See also flush_pending()).
  6913. */
  6914. function read_buf(strm, buf, start, size) {
  6915. var len = strm.avail_in;
  6916. if (len > size) { len = size; }
  6917. if (len === 0) { return 0; }
  6918. strm.avail_in -= len;
  6919. // zmemcpy(buf, strm->next_in, len);
  6920. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6921. if (strm.state.wrap === 1) {
  6922. strm.adler = adler32(strm.adler, buf, len, start);
  6923. }
  6924. else if (strm.state.wrap === 2) {
  6925. strm.adler = crc32(strm.adler, buf, len, start);
  6926. }
  6927. strm.next_in += len;
  6928. strm.total_in += len;
  6929. return len;
  6930. }
  6931. /* ===========================================================================
  6932. * Set match_start to the longest match starting at the given string and
  6933. * return its length. Matches shorter or equal to prev_length are discarded,
  6934. * in which case the result is equal to prev_length and match_start is
  6935. * garbage.
  6936. * IN assertions: cur_match is the head of the hash chain for the current
  6937. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6938. * OUT assertion: the match length is not greater than s->lookahead.
  6939. */
  6940. function longest_match(s, cur_match) {
  6941. var chain_length = s.max_chain_length; /* max hash chain length */
  6942. var scan = s.strstart; /* current string */
  6943. var match; /* matched string */
  6944. var len; /* length of current match */
  6945. var best_len = s.prev_length; /* best match length so far */
  6946. var nice_match = s.nice_match; /* stop if match long enough */
  6947. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6948. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6949. var _win = s.window; // shortcut
  6950. var wmask = s.w_mask;
  6951. var prev = s.prev;
  6952. /* Stop when cur_match becomes <= limit. To simplify the code,
  6953. * we prevent matches with the string of window index 0.
  6954. */
  6955. var strend = s.strstart + MAX_MATCH;
  6956. var scan_end1 = _win[scan + best_len - 1];
  6957. var scan_end = _win[scan + best_len];
  6958. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6959. * It is easy to get rid of this optimization if necessary.
  6960. */
  6961. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6962. /* Do not waste too much time if we already have a good match: */
  6963. if (s.prev_length >= s.good_match) {
  6964. chain_length >>= 2;
  6965. }
  6966. /* Do not look for matches beyond the end of the input. This is necessary
  6967. * to make deflate deterministic.
  6968. */
  6969. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6970. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6971. do {
  6972. // Assert(cur_match < s->strstart, "no future");
  6973. match = cur_match;
  6974. /* Skip to next match if the match length cannot increase
  6975. * or if the match length is less than 2. Note that the checks below
  6976. * for insufficient lookahead only occur occasionally for performance
  6977. * reasons. Therefore uninitialized memory will be accessed, and
  6978. * conditional jumps will be made that depend on those values.
  6979. * However the length of the match is limited to the lookahead, so
  6980. * the output of deflate is not affected by the uninitialized values.
  6981. */
  6982. if (_win[match + best_len] !== scan_end ||
  6983. _win[match + best_len - 1] !== scan_end1 ||
  6984. _win[match] !== _win[scan] ||
  6985. _win[++match] !== _win[scan + 1]) {
  6986. continue;
  6987. }
  6988. /* The check at best_len-1 can be removed because it will be made
  6989. * again later. (This heuristic is not always a win.)
  6990. * It is not necessary to compare scan[2] and match[2] since they
  6991. * are always equal when the other bytes match, given that
  6992. * the hash keys are equal and that HASH_BITS >= 8.
  6993. */
  6994. scan += 2;
  6995. match++;
  6996. // Assert(*scan == *match, "match[2]?");
  6997. /* We check for insufficient lookahead only every 8th comparison;
  6998. * the 256th check will be made at strstart+258.
  6999. */
  7000. do {
  7001. /*jshint noempty:false*/
  7002. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7003. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7004. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7005. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  7006. scan < strend);
  7007. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  7008. len = MAX_MATCH - (strend - scan);
  7009. scan = strend - MAX_MATCH;
  7010. if (len > best_len) {
  7011. s.match_start = cur_match;
  7012. best_len = len;
  7013. if (len >= nice_match) {
  7014. break;
  7015. }
  7016. scan_end1 = _win[scan + best_len - 1];
  7017. scan_end = _win[scan + best_len];
  7018. }
  7019. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  7020. if (best_len <= s.lookahead) {
  7021. return best_len;
  7022. }
  7023. return s.lookahead;
  7024. }
  7025. /* ===========================================================================
  7026. * Fill the window when the lookahead becomes insufficient.
  7027. * Updates strstart and lookahead.
  7028. *
  7029. * IN assertion: lookahead < MIN_LOOKAHEAD
  7030. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  7031. * At least one byte has been read, or avail_in == 0; reads are
  7032. * performed for at least two bytes (required for the zip translate_eol
  7033. * option -- not supported here).
  7034. */
  7035. function fill_window(s) {
  7036. var _w_size = s.w_size;
  7037. var p, n, m, more, str;
  7038. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  7039. do {
  7040. more = s.window_size - s.lookahead - s.strstart;
  7041. // JS ints have 32 bit, block below not needed
  7042. /* Deal with !@#$% 64K limit: */
  7043. //if (sizeof(int) <= 2) {
  7044. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  7045. // more = wsize;
  7046. //
  7047. // } else if (more == (unsigned)(-1)) {
  7048. // /* Very unlikely, but possible on 16 bit machine if
  7049. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  7050. // */
  7051. // more--;
  7052. // }
  7053. //}
  7054. /* If the window is almost full and there is insufficient lookahead,
  7055. * move the upper half to the lower one to make room in the upper half.
  7056. */
  7057. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  7058. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  7059. s.match_start -= _w_size;
  7060. s.strstart -= _w_size;
  7061. /* we now have strstart >= MAX_DIST */
  7062. s.block_start -= _w_size;
  7063. /* Slide the hash table (could be avoided with 32 bit values
  7064. at the expense of memory usage). We slide even when level == 0
  7065. to keep the hash table consistent if we switch back to level > 0
  7066. later. (Using level 0 permanently is not an optimal usage of
  7067. zlib, so we don't care about this pathological case.)
  7068. */
  7069. n = s.hash_size;
  7070. p = n;
  7071. do {
  7072. m = s.head[--p];
  7073. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  7074. } while (--n);
  7075. n = _w_size;
  7076. p = n;
  7077. do {
  7078. m = s.prev[--p];
  7079. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  7080. /* If n is not on any hash chain, prev[n] is garbage but
  7081. * its value will never be used.
  7082. */
  7083. } while (--n);
  7084. more += _w_size;
  7085. }
  7086. if (s.strm.avail_in === 0) {
  7087. break;
  7088. }
  7089. /* If there was no sliding:
  7090. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  7091. * more == window_size - lookahead - strstart
  7092. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  7093. * => more >= window_size - 2*WSIZE + 2
  7094. * In the BIG_MEM or MMAP case (not yet supported),
  7095. * window_size == input_size + MIN_LOOKAHEAD &&
  7096. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  7097. * Otherwise, window_size == 2*WSIZE so more >= 2.
  7098. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  7099. */
  7100. //Assert(more >= 2, "more < 2");
  7101. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  7102. s.lookahead += n;
  7103. /* Initialize the hash value now that we have some input: */
  7104. if (s.lookahead + s.insert >= MIN_MATCH) {
  7105. str = s.strstart - s.insert;
  7106. s.ins_h = s.window[str];
  7107. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  7108. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  7109. //#if MIN_MATCH != 3
  7110. // Call update_hash() MIN_MATCH-3 more times
  7111. //#endif
  7112. while (s.insert) {
  7113. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  7114. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  7115. s.prev[str & s.w_mask] = s.head[s.ins_h];
  7116. s.head[s.ins_h] = str;
  7117. str++;
  7118. s.insert--;
  7119. if (s.lookahead + s.insert < MIN_MATCH) {
  7120. break;
  7121. }
  7122. }
  7123. }
  7124. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  7125. * but this is not important since only literal bytes will be emitted.
  7126. */
  7127. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  7128. /* If the WIN_INIT bytes after the end of the current data have never been
  7129. * written, then zero those bytes in order to avoid memory check reports of
  7130. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  7131. * the longest match routines. Update the high water mark for the next
  7132. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  7133. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  7134. */
  7135. // if (s.high_water < s.window_size) {
  7136. // var curr = s.strstart + s.lookahead;
  7137. // var init = 0;
  7138. //
  7139. // if (s.high_water < curr) {
  7140. // /* Previous high water mark below current data -- zero WIN_INIT
  7141. // * bytes or up to end of window, whichever is less.
  7142. // */
  7143. // init = s.window_size - curr;
  7144. // if (init > WIN_INIT)
  7145. // init = WIN_INIT;
  7146. // zmemzero(s->window + curr, (unsigned)init);
  7147. // s->high_water = curr + init;
  7148. // }
  7149. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  7150. // /* High water mark at or above current data, but below current data
  7151. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  7152. // * to end of window, whichever is less.
  7153. // */
  7154. // init = (ulg)curr + WIN_INIT - s->high_water;
  7155. // if (init > s->window_size - s->high_water)
  7156. // init = s->window_size - s->high_water;
  7157. // zmemzero(s->window + s->high_water, (unsigned)init);
  7158. // s->high_water += init;
  7159. // }
  7160. // }
  7161. //
  7162. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  7163. // "not enough room for search");
  7164. }
  7165. /* ===========================================================================
  7166. * Copy without compression as much as possible from the input stream, return
  7167. * the current block state.
  7168. * This function does not insert new strings in the dictionary since
  7169. * uncompressible data is probably not useful. This function is used
  7170. * only for the level=0 compression option.
  7171. * NOTE: this function should be optimized to avoid extra copying from
  7172. * window to pending_buf.
  7173. */
  7174. function deflate_stored(s, flush) {
  7175. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  7176. * to pending_buf_size, and each stored block has a 5 byte header:
  7177. */
  7178. var max_block_size = 0xffff;
  7179. if (max_block_size > s.pending_buf_size - 5) {
  7180. max_block_size = s.pending_buf_size - 5;
  7181. }
  7182. /* Copy as much as possible from input to output: */
  7183. for (;;) {
  7184. /* Fill the window as much as possible: */
  7185. if (s.lookahead <= 1) {
  7186. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  7187. // s->block_start >= (long)s->w_size, "slide too late");
  7188. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  7189. // s.block_start >= s.w_size)) {
  7190. // throw new Error("slide too late");
  7191. // }
  7192. fill_window(s);
  7193. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  7194. return BS_NEED_MORE;
  7195. }
  7196. if (s.lookahead === 0) {
  7197. break;
  7198. }
  7199. /* flush the current block */
  7200. }
  7201. //Assert(s->block_start >= 0L, "block gone");
  7202. // if (s.block_start < 0) throw new Error("block gone");
  7203. s.strstart += s.lookahead;
  7204. s.lookahead = 0;
  7205. /* Emit a stored block if pending_buf will be full: */
  7206. var max_start = s.block_start + max_block_size;
  7207. if (s.strstart === 0 || s.strstart >= max_start) {
  7208. /* strstart == 0 is possible when wraparound on 16-bit machine */
  7209. s.lookahead = s.strstart - max_start;
  7210. s.strstart = max_start;
  7211. /*** FLUSH_BLOCK(s, 0); ***/
  7212. flush_block_only(s, false);
  7213. if (s.strm.avail_out === 0) {
  7214. return BS_NEED_MORE;
  7215. }
  7216. /***/
  7217. }
  7218. /* Flush if we may have to slide, otherwise block_start may become
  7219. * negative and the data will be gone:
  7220. */
  7221. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  7222. /*** FLUSH_BLOCK(s, 0); ***/
  7223. flush_block_only(s, false);
  7224. if (s.strm.avail_out === 0) {
  7225. return BS_NEED_MORE;
  7226. }
  7227. /***/
  7228. }
  7229. }
  7230. s.insert = 0;
  7231. if (flush === Z_FINISH) {
  7232. /*** FLUSH_BLOCK(s, 1); ***/
  7233. flush_block_only(s, true);
  7234. if (s.strm.avail_out === 0) {
  7235. return BS_FINISH_STARTED;
  7236. }
  7237. /***/
  7238. return BS_FINISH_DONE;
  7239. }
  7240. if (s.strstart > s.block_start) {
  7241. /*** FLUSH_BLOCK(s, 0); ***/
  7242. flush_block_only(s, false);
  7243. if (s.strm.avail_out === 0) {
  7244. return BS_NEED_MORE;
  7245. }
  7246. /***/
  7247. }
  7248. return BS_NEED_MORE;
  7249. }
  7250. /* ===========================================================================
  7251. * Compress as much as possible from the input stream, return the current
  7252. * block state.
  7253. * This function does not perform lazy evaluation of matches and inserts
  7254. * new strings in the dictionary only for unmatched strings or for short
  7255. * matches. It is used only for the fast compression options.
  7256. */
  7257. function deflate_fast(s, flush) {
  7258. var hash_head; /* head of the hash chain */
  7259. var bflush; /* set if current block must be flushed */
  7260. for (;;) {
  7261. /* Make sure that we always have enough lookahead, except
  7262. * at the end of the input file. We need MAX_MATCH bytes
  7263. * for the next match, plus MIN_MATCH bytes to insert the
  7264. * string following the next match.
  7265. */
  7266. if (s.lookahead < MIN_LOOKAHEAD) {
  7267. fill_window(s);
  7268. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  7269. return BS_NEED_MORE;
  7270. }
  7271. if (s.lookahead === 0) {
  7272. break; /* flush the current block */
  7273. }
  7274. }
  7275. /* Insert the string window[strstart .. strstart+2] in the
  7276. * dictionary, and set hash_head to the head of the hash chain:
  7277. */
  7278. hash_head = 0/*NIL*/;
  7279. if (s.lookahead >= MIN_MATCH) {
  7280. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7281. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7282. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7283. s.head[s.ins_h] = s.strstart;
  7284. /***/
  7285. }
  7286. /* Find the longest match, discarding those <= prev_length.
  7287. * At this point we have always match_length < MIN_MATCH
  7288. */
  7289. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  7290. /* To simplify the code, we prevent matches with the string
  7291. * of window index 0 (in particular we have to avoid a match
  7292. * of the string with itself at the start of the input file).
  7293. */
  7294. s.match_length = longest_match(s, hash_head);
  7295. /* longest_match() sets match_start */
  7296. }
  7297. if (s.match_length >= MIN_MATCH) {
  7298. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  7299. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  7300. s.match_length - MIN_MATCH, bflush); ***/
  7301. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  7302. s.lookahead -= s.match_length;
  7303. /* Insert new strings in the hash table only if the match length
  7304. * is not too large. This saves time but degrades compression.
  7305. */
  7306. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  7307. s.match_length--; /* string at strstart already in table */
  7308. do {
  7309. s.strstart++;
  7310. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7311. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7312. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7313. s.head[s.ins_h] = s.strstart;
  7314. /***/
  7315. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  7316. * always MIN_MATCH bytes ahead.
  7317. */
  7318. } while (--s.match_length !== 0);
  7319. s.strstart++;
  7320. } else
  7321. {
  7322. s.strstart += s.match_length;
  7323. s.match_length = 0;
  7324. s.ins_h = s.window[s.strstart];
  7325. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  7326. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  7327. //#if MIN_MATCH != 3
  7328. // Call UPDATE_HASH() MIN_MATCH-3 more times
  7329. //#endif
  7330. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  7331. * matter since it will be recomputed at next deflate call.
  7332. */
  7333. }
  7334. } else {
  7335. /* No match, output a literal byte */
  7336. //Tracevv((stderr,"%c", s.window[s.strstart]));
  7337. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7338. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7339. s.lookahead--;
  7340. s.strstart++;
  7341. }
  7342. if (bflush) {
  7343. /*** FLUSH_BLOCK(s, 0); ***/
  7344. flush_block_only(s, false);
  7345. if (s.strm.avail_out === 0) {
  7346. return BS_NEED_MORE;
  7347. }
  7348. /***/
  7349. }
  7350. }
  7351. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  7352. if (flush === Z_FINISH) {
  7353. /*** FLUSH_BLOCK(s, 1); ***/
  7354. flush_block_only(s, true);
  7355. if (s.strm.avail_out === 0) {
  7356. return BS_FINISH_STARTED;
  7357. }
  7358. /***/
  7359. return BS_FINISH_DONE;
  7360. }
  7361. if (s.last_lit) {
  7362. /*** FLUSH_BLOCK(s, 0); ***/
  7363. flush_block_only(s, false);
  7364. if (s.strm.avail_out === 0) {
  7365. return BS_NEED_MORE;
  7366. }
  7367. /***/
  7368. }
  7369. return BS_BLOCK_DONE;
  7370. }
  7371. /* ===========================================================================
  7372. * Same as above, but achieves better compression. We use a lazy
  7373. * evaluation for matches: a match is finally adopted only if there is
  7374. * no better match at the next window position.
  7375. */
  7376. function deflate_slow(s, flush) {
  7377. var hash_head; /* head of hash chain */
  7378. var bflush; /* set if current block must be flushed */
  7379. var max_insert;
  7380. /* Process the input block. */
  7381. for (;;) {
  7382. /* Make sure that we always have enough lookahead, except
  7383. * at the end of the input file. We need MAX_MATCH bytes
  7384. * for the next match, plus MIN_MATCH bytes to insert the
  7385. * string following the next match.
  7386. */
  7387. if (s.lookahead < MIN_LOOKAHEAD) {
  7388. fill_window(s);
  7389. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  7390. return BS_NEED_MORE;
  7391. }
  7392. if (s.lookahead === 0) { break; } /* flush the current block */
  7393. }
  7394. /* Insert the string window[strstart .. strstart+2] in the
  7395. * dictionary, and set hash_head to the head of the hash chain:
  7396. */
  7397. hash_head = 0/*NIL*/;
  7398. if (s.lookahead >= MIN_MATCH) {
  7399. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7400. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7401. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7402. s.head[s.ins_h] = s.strstart;
  7403. /***/
  7404. }
  7405. /* Find the longest match, discarding those <= prev_length.
  7406. */
  7407. s.prev_length = s.match_length;
  7408. s.prev_match = s.match_start;
  7409. s.match_length = MIN_MATCH - 1;
  7410. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  7411. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  7412. /* To simplify the code, we prevent matches with the string
  7413. * of window index 0 (in particular we have to avoid a match
  7414. * of the string with itself at the start of the input file).
  7415. */
  7416. s.match_length = longest_match(s, hash_head);
  7417. /* longest_match() sets match_start */
  7418. if (s.match_length <= 5 &&
  7419. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  7420. /* If prev_match is also MIN_MATCH, match_start is garbage
  7421. * but we will ignore the current match anyway.
  7422. */
  7423. s.match_length = MIN_MATCH - 1;
  7424. }
  7425. }
  7426. /* If there was a match at the previous step and the current
  7427. * match is not better, output the previous match:
  7428. */
  7429. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  7430. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  7431. /* Do not insert strings in hash table beyond this. */
  7432. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  7433. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  7434. s.prev_length - MIN_MATCH, bflush);***/
  7435. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  7436. /* Insert in hash table all strings up to the end of the match.
  7437. * strstart-1 and strstart are already inserted. If there is not
  7438. * enough lookahead, the last two strings are not inserted in
  7439. * the hash table.
  7440. */
  7441. s.lookahead -= s.prev_length - 1;
  7442. s.prev_length -= 2;
  7443. do {
  7444. if (++s.strstart <= max_insert) {
  7445. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  7446. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  7447. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  7448. s.head[s.ins_h] = s.strstart;
  7449. /***/
  7450. }
  7451. } while (--s.prev_length !== 0);
  7452. s.match_available = 0;
  7453. s.match_length = MIN_MATCH - 1;
  7454. s.strstart++;
  7455. if (bflush) {
  7456. /*** FLUSH_BLOCK(s, 0); ***/
  7457. flush_block_only(s, false);
  7458. if (s.strm.avail_out === 0) {
  7459. return BS_NEED_MORE;
  7460. }
  7461. /***/
  7462. }
  7463. } else if (s.match_available) {
  7464. /* If there was no match at the previous position, output a
  7465. * single literal. If there was a match but the current match
  7466. * is longer, truncate the previous match to a single literal.
  7467. */
  7468. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  7469. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  7470. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  7471. if (bflush) {
  7472. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  7473. flush_block_only(s, false);
  7474. /***/
  7475. }
  7476. s.strstart++;
  7477. s.lookahead--;
  7478. if (s.strm.avail_out === 0) {
  7479. return BS_NEED_MORE;
  7480. }
  7481. } else {
  7482. /* There is no previous match to compare with, wait for
  7483. * the next step to decide.
  7484. */
  7485. s.match_available = 1;
  7486. s.strstart++;
  7487. s.lookahead--;
  7488. }
  7489. }
  7490. //Assert (flush != Z_NO_FLUSH, "no flush?");
  7491. if (s.match_available) {
  7492. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  7493. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  7494. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  7495. s.match_available = 0;
  7496. }
  7497. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  7498. if (flush === Z_FINISH) {
  7499. /*** FLUSH_BLOCK(s, 1); ***/
  7500. flush_block_only(s, true);
  7501. if (s.strm.avail_out === 0) {
  7502. return BS_FINISH_STARTED;
  7503. }
  7504. /***/
  7505. return BS_FINISH_DONE;
  7506. }
  7507. if (s.last_lit) {
  7508. /*** FLUSH_BLOCK(s, 0); ***/
  7509. flush_block_only(s, false);
  7510. if (s.strm.avail_out === 0) {
  7511. return BS_NEED_MORE;
  7512. }
  7513. /***/
  7514. }
  7515. return BS_BLOCK_DONE;
  7516. }
  7517. /* ===========================================================================
  7518. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  7519. * one. Do not maintain a hash table. (It will be regenerated if this run of
  7520. * deflate switches away from Z_RLE.)
  7521. */
  7522. function deflate_rle(s, flush) {
  7523. var bflush; /* set if current block must be flushed */
  7524. var prev; /* byte at distance one to match */
  7525. var scan, strend; /* scan goes up to strend for length of run */
  7526. var _win = s.window;
  7527. for (;;) {
  7528. /* Make sure that we always have enough lookahead, except
  7529. * at the end of the input file. We need MAX_MATCH bytes
  7530. * for the longest run, plus one for the unrolled loop.
  7531. */
  7532. if (s.lookahead <= MAX_MATCH) {
  7533. fill_window(s);
  7534. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  7535. return BS_NEED_MORE;
  7536. }
  7537. if (s.lookahead === 0) { break; } /* flush the current block */
  7538. }
  7539. /* See how many times the previous byte repeats */
  7540. s.match_length = 0;
  7541. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  7542. scan = s.strstart - 1;
  7543. prev = _win[scan];
  7544. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  7545. strend = s.strstart + MAX_MATCH;
  7546. do {
  7547. /*jshint noempty:false*/
  7548. } while (prev === _win[++scan] && prev === _win[++scan] &&
  7549. prev === _win[++scan] && prev === _win[++scan] &&
  7550. prev === _win[++scan] && prev === _win[++scan] &&
  7551. prev === _win[++scan] && prev === _win[++scan] &&
  7552. scan < strend);
  7553. s.match_length = MAX_MATCH - (strend - scan);
  7554. if (s.match_length > s.lookahead) {
  7555. s.match_length = s.lookahead;
  7556. }
  7557. }
  7558. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  7559. }
  7560. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  7561. if (s.match_length >= MIN_MATCH) {
  7562. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  7563. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  7564. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  7565. s.lookahead -= s.match_length;
  7566. s.strstart += s.match_length;
  7567. s.match_length = 0;
  7568. } else {
  7569. /* No match, output a literal byte */
  7570. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7571. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7572. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7573. s.lookahead--;
  7574. s.strstart++;
  7575. }
  7576. if (bflush) {
  7577. /*** FLUSH_BLOCK(s, 0); ***/
  7578. flush_block_only(s, false);
  7579. if (s.strm.avail_out === 0) {
  7580. return BS_NEED_MORE;
  7581. }
  7582. /***/
  7583. }
  7584. }
  7585. s.insert = 0;
  7586. if (flush === Z_FINISH) {
  7587. /*** FLUSH_BLOCK(s, 1); ***/
  7588. flush_block_only(s, true);
  7589. if (s.strm.avail_out === 0) {
  7590. return BS_FINISH_STARTED;
  7591. }
  7592. /***/
  7593. return BS_FINISH_DONE;
  7594. }
  7595. if (s.last_lit) {
  7596. /*** FLUSH_BLOCK(s, 0); ***/
  7597. flush_block_only(s, false);
  7598. if (s.strm.avail_out === 0) {
  7599. return BS_NEED_MORE;
  7600. }
  7601. /***/
  7602. }
  7603. return BS_BLOCK_DONE;
  7604. }
  7605. /* ===========================================================================
  7606. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  7607. * (It will be regenerated if this run of deflate switches away from Huffman.)
  7608. */
  7609. function deflate_huff(s, flush) {
  7610. var bflush; /* set if current block must be flushed */
  7611. for (;;) {
  7612. /* Make sure that we have a literal to write. */
  7613. if (s.lookahead === 0) {
  7614. fill_window(s);
  7615. if (s.lookahead === 0) {
  7616. if (flush === Z_NO_FLUSH) {
  7617. return BS_NEED_MORE;
  7618. }
  7619. break; /* flush the current block */
  7620. }
  7621. }
  7622. /* Output a literal byte */
  7623. s.match_length = 0;
  7624. //Tracevv((stderr,"%c", s->window[s->strstart]));
  7625. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7626. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7627. s.lookahead--;
  7628. s.strstart++;
  7629. if (bflush) {
  7630. /*** FLUSH_BLOCK(s, 0); ***/
  7631. flush_block_only(s, false);
  7632. if (s.strm.avail_out === 0) {
  7633. return BS_NEED_MORE;
  7634. }
  7635. /***/
  7636. }
  7637. }
  7638. s.insert = 0;
  7639. if (flush === Z_FINISH) {
  7640. /*** FLUSH_BLOCK(s, 1); ***/
  7641. flush_block_only(s, true);
  7642. if (s.strm.avail_out === 0) {
  7643. return BS_FINISH_STARTED;
  7644. }
  7645. /***/
  7646. return BS_FINISH_DONE;
  7647. }
  7648. if (s.last_lit) {
  7649. /*** FLUSH_BLOCK(s, 0); ***/
  7650. flush_block_only(s, false);
  7651. if (s.strm.avail_out === 0) {
  7652. return BS_NEED_MORE;
  7653. }
  7654. /***/
  7655. }
  7656. return BS_BLOCK_DONE;
  7657. }
  7658. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  7659. * the desired pack level (0..9). The values given below have been tuned to
  7660. * exclude worst case performance for pathological files. Better values may be
  7661. * found for specific files.
  7662. */
  7663. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  7664. this.good_length = good_length;
  7665. this.max_lazy = max_lazy;
  7666. this.nice_length = nice_length;
  7667. this.max_chain = max_chain;
  7668. this.func = func;
  7669. }
  7670. var configuration_table;
  7671. configuration_table = [
  7672. /* good lazy nice chain */
  7673. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  7674. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  7675. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  7676. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  7677. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  7678. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  7679. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  7680. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  7681. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  7682. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  7683. ];
  7684. /* ===========================================================================
  7685. * Initialize the "longest match" routines for a new zlib stream
  7686. */
  7687. function lm_init(s) {
  7688. s.window_size = 2 * s.w_size;
  7689. /*** CLEAR_HASH(s); ***/
  7690. zero(s.head); // Fill with NIL (= 0);
  7691. /* Set the default configuration parameters:
  7692. */
  7693. s.max_lazy_match = configuration_table[s.level].max_lazy;
  7694. s.good_match = configuration_table[s.level].good_length;
  7695. s.nice_match = configuration_table[s.level].nice_length;
  7696. s.max_chain_length = configuration_table[s.level].max_chain;
  7697. s.strstart = 0;
  7698. s.block_start = 0;
  7699. s.lookahead = 0;
  7700. s.insert = 0;
  7701. s.match_length = s.prev_length = MIN_MATCH - 1;
  7702. s.match_available = 0;
  7703. s.ins_h = 0;
  7704. }
  7705. function DeflateState() {
  7706. this.strm = null; /* pointer back to this zlib stream */
  7707. this.status = 0; /* as the name implies */
  7708. this.pending_buf = null; /* output still pending */
  7709. this.pending_buf_size = 0; /* size of pending_buf */
  7710. this.pending_out = 0; /* next pending byte to output to the stream */
  7711. this.pending = 0; /* nb of bytes in the pending buffer */
  7712. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7713. this.gzhead = null; /* gzip header information to write */
  7714. this.gzindex = 0; /* where in extra, name, or comment */
  7715. this.method = Z_DEFLATED; /* can only be DEFLATED */
  7716. this.last_flush = -1; /* value of flush param for previous deflate call */
  7717. this.w_size = 0; /* LZ77 window size (32K by default) */
  7718. this.w_bits = 0; /* log2(w_size) (8..16) */
  7719. this.w_mask = 0; /* w_size - 1 */
  7720. this.window = null;
  7721. /* Sliding window. Input bytes are read into the second half of the window,
  7722. * and move to the first half later to keep a dictionary of at least wSize
  7723. * bytes. With this organization, matches are limited to a distance of
  7724. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  7725. * performed with a length multiple of the block size.
  7726. */
  7727. this.window_size = 0;
  7728. /* Actual size of window: 2*wSize, except when the user input buffer
  7729. * is directly used as sliding window.
  7730. */
  7731. this.prev = null;
  7732. /* Link to older string with same hash index. To limit the size of this
  7733. * array to 64K, this link is maintained only for the last 32K strings.
  7734. * An index in this array is thus a window index modulo 32K.
  7735. */
  7736. this.head = null; /* Heads of the hash chains or NIL. */
  7737. this.ins_h = 0; /* hash index of string to be inserted */
  7738. this.hash_size = 0; /* number of elements in hash table */
  7739. this.hash_bits = 0; /* log2(hash_size) */
  7740. this.hash_mask = 0; /* hash_size-1 */
  7741. this.hash_shift = 0;
  7742. /* Number of bits by which ins_h must be shifted at each input
  7743. * step. It must be such that after MIN_MATCH steps, the oldest
  7744. * byte no longer takes part in the hash key, that is:
  7745. * hash_shift * MIN_MATCH >= hash_bits
  7746. */
  7747. this.block_start = 0;
  7748. /* Window position at the beginning of the current output block. Gets
  7749. * negative when the window is moved backwards.
  7750. */
  7751. this.match_length = 0; /* length of best match */
  7752. this.prev_match = 0; /* previous match */
  7753. this.match_available = 0; /* set if previous match exists */
  7754. this.strstart = 0; /* start of string to insert */
  7755. this.match_start = 0; /* start of matching string */
  7756. this.lookahead = 0; /* number of valid bytes ahead in window */
  7757. this.prev_length = 0;
  7758. /* Length of the best match at previous step. Matches not greater than this
  7759. * are discarded. This is used in the lazy match evaluation.
  7760. */
  7761. this.max_chain_length = 0;
  7762. /* To speed up deflation, hash chains are never searched beyond this
  7763. * length. A higher limit improves compression ratio but degrades the
  7764. * speed.
  7765. */
  7766. this.max_lazy_match = 0;
  7767. /* Attempt to find a better match only when the current match is strictly
  7768. * smaller than this value. This mechanism is used only for compression
  7769. * levels >= 4.
  7770. */
  7771. // That's alias to max_lazy_match, don't use directly
  7772. //this.max_insert_length = 0;
  7773. /* Insert new strings in the hash table only if the match length is not
  7774. * greater than this length. This saves time but degrades compression.
  7775. * max_insert_length is used only for compression levels <= 3.
  7776. */
  7777. this.level = 0; /* compression level (1..9) */
  7778. this.strategy = 0; /* favor or force Huffman coding*/
  7779. this.good_match = 0;
  7780. /* Use a faster search when the previous match is longer than this */
  7781. this.nice_match = 0; /* Stop searching when current match exceeds this */
  7782. /* used by trees.c: */
  7783. /* Didn't use ct_data typedef below to suppress compiler warning */
  7784. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  7785. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  7786. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  7787. // Use flat array of DOUBLE size, with interleaved fata,
  7788. // because JS does not support effective
  7789. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  7790. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  7791. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  7792. zero(this.dyn_ltree);
  7793. zero(this.dyn_dtree);
  7794. zero(this.bl_tree);
  7795. this.l_desc = null; /* desc. for literal tree */
  7796. this.d_desc = null; /* desc. for distance tree */
  7797. this.bl_desc = null; /* desc. for bit length tree */
  7798. //ush bl_count[MAX_BITS+1];
  7799. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  7800. /* number of codes at each bit length for an optimal tree */
  7801. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  7802. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  7803. zero(this.heap);
  7804. this.heap_len = 0; /* number of elements in the heap */
  7805. this.heap_max = 0; /* element of largest frequency */
  7806. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  7807. * The same heap array is used to build all trees.
  7808. */
  7809. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  7810. zero(this.depth);
  7811. /* Depth of each subtree used as tie breaker for trees of equal frequency
  7812. */
  7813. this.l_buf = 0; /* buffer index for literals or lengths */
  7814. this.lit_bufsize = 0;
  7815. /* Size of match buffer for literals/lengths. There are 4 reasons for
  7816. * limiting lit_bufsize to 64K:
  7817. * - frequencies can be kept in 16 bit counters
  7818. * - if compression is not successful for the first block, all input
  7819. * data is still in the window so we can still emit a stored block even
  7820. * when input comes from standard input. (This can also be done for
  7821. * all blocks if lit_bufsize is not greater than 32K.)
  7822. * - if compression is not successful for a file smaller than 64K, we can
  7823. * even emit a stored file instead of a stored block (saving 5 bytes).
  7824. * This is applicable only for zip (not gzip or zlib).
  7825. * - creating new Huffman trees less frequently may not provide fast
  7826. * adaptation to changes in the input data statistics. (Take for
  7827. * example a binary file with poorly compressible code followed by
  7828. * a highly compressible string table.) Smaller buffer sizes give
  7829. * fast adaptation but have of course the overhead of transmitting
  7830. * trees more frequently.
  7831. * - I can't count above 4
  7832. */
  7833. this.last_lit = 0; /* running index in l_buf */
  7834. this.d_buf = 0;
  7835. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  7836. * the same number of elements. To use different lengths, an extra flag
  7837. * array would be necessary.
  7838. */
  7839. this.opt_len = 0; /* bit length of current block with optimal trees */
  7840. this.static_len = 0; /* bit length of current block with static trees */
  7841. this.matches = 0; /* number of string matches in current block */
  7842. this.insert = 0; /* bytes at end of window left to insert */
  7843. this.bi_buf = 0;
  7844. /* Output buffer. bits are inserted starting at the bottom (least
  7845. * significant bits).
  7846. */
  7847. this.bi_valid = 0;
  7848. /* Number of valid bits in bi_buf. All bits above the last valid bit
  7849. * are always zero.
  7850. */
  7851. // Used for window memory init. We safely ignore it for JS. That makes
  7852. // sense only for pointers and memory check tools.
  7853. //this.high_water = 0;
  7854. /* High water mark offset in window for initialized bytes -- bytes above
  7855. * this are set to zero in order to avoid memory check warnings when
  7856. * longest match routines access bytes past the input. This is then
  7857. * updated to the new high water mark.
  7858. */
  7859. }
  7860. function deflateResetKeep(strm) {
  7861. var s;
  7862. if (!strm || !strm.state) {
  7863. return err(strm, Z_STREAM_ERROR);
  7864. }
  7865. strm.total_in = strm.total_out = 0;
  7866. strm.data_type = Z_UNKNOWN;
  7867. s = strm.state;
  7868. s.pending = 0;
  7869. s.pending_out = 0;
  7870. if (s.wrap < 0) {
  7871. s.wrap = -s.wrap;
  7872. /* was made negative by deflate(..., Z_FINISH); */
  7873. }
  7874. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  7875. strm.adler = (s.wrap === 2) ?
  7876. 0 // crc32(0, Z_NULL, 0)
  7877. :
  7878. 1; // adler32(0, Z_NULL, 0)
  7879. s.last_flush = Z_NO_FLUSH;
  7880. trees._tr_init(s);
  7881. return Z_OK;
  7882. }
  7883. function deflateReset(strm) {
  7884. var ret = deflateResetKeep(strm);
  7885. if (ret === Z_OK) {
  7886. lm_init(strm.state);
  7887. }
  7888. return ret;
  7889. }
  7890. function deflateSetHeader(strm, head) {
  7891. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7892. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  7893. strm.state.gzhead = head;
  7894. return Z_OK;
  7895. }
  7896. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  7897. if (!strm) { // === Z_NULL
  7898. return Z_STREAM_ERROR;
  7899. }
  7900. var wrap = 1;
  7901. if (level === Z_DEFAULT_COMPRESSION) {
  7902. level = 6;
  7903. }
  7904. if (windowBits < 0) { /* suppress zlib wrapper */
  7905. wrap = 0;
  7906. windowBits = -windowBits;
  7907. }
  7908. else if (windowBits > 15) {
  7909. wrap = 2; /* write gzip wrapper instead */
  7910. windowBits -= 16;
  7911. }
  7912. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7913. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7914. strategy < 0 || strategy > Z_FIXED) {
  7915. return err(strm, Z_STREAM_ERROR);
  7916. }
  7917. if (windowBits === 8) {
  7918. windowBits = 9;
  7919. }
  7920. /* until 256-byte window bug fixed */
  7921. var s = new DeflateState();
  7922. strm.state = s;
  7923. s.strm = strm;
  7924. s.wrap = wrap;
  7925. s.gzhead = null;
  7926. s.w_bits = windowBits;
  7927. s.w_size = 1 << s.w_bits;
  7928. s.w_mask = s.w_size - 1;
  7929. s.hash_bits = memLevel + 7;
  7930. s.hash_size = 1 << s.hash_bits;
  7931. s.hash_mask = s.hash_size - 1;
  7932. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7933. s.window = new utils.Buf8(s.w_size * 2);
  7934. s.head = new utils.Buf16(s.hash_size);
  7935. s.prev = new utils.Buf16(s.w_size);
  7936. // Don't need mem init magic for JS.
  7937. //s.high_water = 0; /* nothing written to s->window yet */
  7938. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7939. s.pending_buf_size = s.lit_bufsize * 4;
  7940. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7941. s.d_buf = s.lit_bufsize >> 1;
  7942. s.l_buf = (1 + 2) * s.lit_bufsize;
  7943. s.level = level;
  7944. s.strategy = strategy;
  7945. s.method = method;
  7946. return deflateReset(strm);
  7947. }
  7948. function deflateInit(strm, level) {
  7949. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7950. }
  7951. function deflate(strm, flush) {
  7952. var old_flush, s;
  7953. var beg, val; // for gzip header write only
  7954. if (!strm || !strm.state ||
  7955. flush > Z_BLOCK || flush < 0) {
  7956. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7957. }
  7958. s = strm.state;
  7959. if (!strm.output ||
  7960. (!strm.input && strm.avail_in !== 0) ||
  7961. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7962. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7963. }
  7964. s.strm = strm; /* just in case */
  7965. old_flush = s.last_flush;
  7966. s.last_flush = flush;
  7967. /* Write the header */
  7968. if (s.status === INIT_STATE) {
  7969. if (s.wrap === 2) { // GZIP header
  7970. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7971. put_byte(s, 31);
  7972. put_byte(s, 139);
  7973. put_byte(s, 8);
  7974. if (!s.gzhead) { // s->gzhead == Z_NULL
  7975. put_byte(s, 0);
  7976. put_byte(s, 0);
  7977. put_byte(s, 0);
  7978. put_byte(s, 0);
  7979. put_byte(s, 0);
  7980. put_byte(s, s.level === 9 ? 2 :
  7981. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7982. 4 : 0));
  7983. put_byte(s, OS_CODE);
  7984. s.status = BUSY_STATE;
  7985. }
  7986. else {
  7987. put_byte(s, (s.gzhead.text ? 1 : 0) +
  7988. (s.gzhead.hcrc ? 2 : 0) +
  7989. (!s.gzhead.extra ? 0 : 4) +
  7990. (!s.gzhead.name ? 0 : 8) +
  7991. (!s.gzhead.comment ? 0 : 16)
  7992. );
  7993. put_byte(s, s.gzhead.time & 0xff);
  7994. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7995. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7996. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7997. put_byte(s, s.level === 9 ? 2 :
  7998. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7999. 4 : 0));
  8000. put_byte(s, s.gzhead.os & 0xff);
  8001. if (s.gzhead.extra && s.gzhead.extra.length) {
  8002. put_byte(s, s.gzhead.extra.length & 0xff);
  8003. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  8004. }
  8005. if (s.gzhead.hcrc) {
  8006. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  8007. }
  8008. s.gzindex = 0;
  8009. s.status = EXTRA_STATE;
  8010. }
  8011. }
  8012. else // DEFLATE header
  8013. {
  8014. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  8015. var level_flags = -1;
  8016. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  8017. level_flags = 0;
  8018. } else if (s.level < 6) {
  8019. level_flags = 1;
  8020. } else if (s.level === 6) {
  8021. level_flags = 2;
  8022. } else {
  8023. level_flags = 3;
  8024. }
  8025. header |= (level_flags << 6);
  8026. if (s.strstart !== 0) { header |= PRESET_DICT; }
  8027. header += 31 - (header % 31);
  8028. s.status = BUSY_STATE;
  8029. putShortMSB(s, header);
  8030. /* Save the adler32 of the preset dictionary: */
  8031. if (s.strstart !== 0) {
  8032. putShortMSB(s, strm.adler >>> 16);
  8033. putShortMSB(s, strm.adler & 0xffff);
  8034. }
  8035. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  8036. }
  8037. }
  8038. //#ifdef GZIP
  8039. if (s.status === EXTRA_STATE) {
  8040. if (s.gzhead.extra/* != Z_NULL*/) {
  8041. beg = s.pending; /* start of bytes to update crc */
  8042. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  8043. if (s.pending === s.pending_buf_size) {
  8044. if (s.gzhead.hcrc && s.pending > beg) {
  8045. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8046. }
  8047. flush_pending(strm);
  8048. beg = s.pending;
  8049. if (s.pending === s.pending_buf_size) {
  8050. break;
  8051. }
  8052. }
  8053. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  8054. s.gzindex++;
  8055. }
  8056. if (s.gzhead.hcrc && s.pending > beg) {
  8057. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8058. }
  8059. if (s.gzindex === s.gzhead.extra.length) {
  8060. s.gzindex = 0;
  8061. s.status = NAME_STATE;
  8062. }
  8063. }
  8064. else {
  8065. s.status = NAME_STATE;
  8066. }
  8067. }
  8068. if (s.status === NAME_STATE) {
  8069. if (s.gzhead.name/* != Z_NULL*/) {
  8070. beg = s.pending; /* start of bytes to update crc */
  8071. //int val;
  8072. do {
  8073. if (s.pending === s.pending_buf_size) {
  8074. if (s.gzhead.hcrc && s.pending > beg) {
  8075. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8076. }
  8077. flush_pending(strm);
  8078. beg = s.pending;
  8079. if (s.pending === s.pending_buf_size) {
  8080. val = 1;
  8081. break;
  8082. }
  8083. }
  8084. // JS specific: little magic to add zero terminator to end of string
  8085. if (s.gzindex < s.gzhead.name.length) {
  8086. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  8087. } else {
  8088. val = 0;
  8089. }
  8090. put_byte(s, val);
  8091. } while (val !== 0);
  8092. if (s.gzhead.hcrc && s.pending > beg) {
  8093. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8094. }
  8095. if (val === 0) {
  8096. s.gzindex = 0;
  8097. s.status = COMMENT_STATE;
  8098. }
  8099. }
  8100. else {
  8101. s.status = COMMENT_STATE;
  8102. }
  8103. }
  8104. if (s.status === COMMENT_STATE) {
  8105. if (s.gzhead.comment/* != Z_NULL*/) {
  8106. beg = s.pending; /* start of bytes to update crc */
  8107. //int val;
  8108. do {
  8109. if (s.pending === s.pending_buf_size) {
  8110. if (s.gzhead.hcrc && s.pending > beg) {
  8111. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8112. }
  8113. flush_pending(strm);
  8114. beg = s.pending;
  8115. if (s.pending === s.pending_buf_size) {
  8116. val = 1;
  8117. break;
  8118. }
  8119. }
  8120. // JS specific: little magic to add zero terminator to end of string
  8121. if (s.gzindex < s.gzhead.comment.length) {
  8122. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  8123. } else {
  8124. val = 0;
  8125. }
  8126. put_byte(s, val);
  8127. } while (val !== 0);
  8128. if (s.gzhead.hcrc && s.pending > beg) {
  8129. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  8130. }
  8131. if (val === 0) {
  8132. s.status = HCRC_STATE;
  8133. }
  8134. }
  8135. else {
  8136. s.status = HCRC_STATE;
  8137. }
  8138. }
  8139. if (s.status === HCRC_STATE) {
  8140. if (s.gzhead.hcrc) {
  8141. if (s.pending + 2 > s.pending_buf_size) {
  8142. flush_pending(strm);
  8143. }
  8144. if (s.pending + 2 <= s.pending_buf_size) {
  8145. put_byte(s, strm.adler & 0xff);
  8146. put_byte(s, (strm.adler >> 8) & 0xff);
  8147. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  8148. s.status = BUSY_STATE;
  8149. }
  8150. }
  8151. else {
  8152. s.status = BUSY_STATE;
  8153. }
  8154. }
  8155. //#endif
  8156. /* Flush as much pending output as possible */
  8157. if (s.pending !== 0) {
  8158. flush_pending(strm);
  8159. if (strm.avail_out === 0) {
  8160. /* Since avail_out is 0, deflate will be called again with
  8161. * more output space, but possibly with both pending and
  8162. * avail_in equal to zero. There won't be anything to do,
  8163. * but this is not an error situation so make sure we
  8164. * return OK instead of BUF_ERROR at next call of deflate:
  8165. */
  8166. s.last_flush = -1;
  8167. return Z_OK;
  8168. }
  8169. /* Make sure there is something to do and avoid duplicate consecutive
  8170. * flushes. For repeated and useless calls with Z_FINISH, we keep
  8171. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  8172. */
  8173. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  8174. flush !== Z_FINISH) {
  8175. return err(strm, Z_BUF_ERROR);
  8176. }
  8177. /* User must not provide more input after the first FINISH: */
  8178. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  8179. return err(strm, Z_BUF_ERROR);
  8180. }
  8181. /* Start a new block or continue the current one.
  8182. */
  8183. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  8184. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  8185. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  8186. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  8187. configuration_table[s.level].func(s, flush));
  8188. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  8189. s.status = FINISH_STATE;
  8190. }
  8191. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  8192. if (strm.avail_out === 0) {
  8193. s.last_flush = -1;
  8194. /* avoid BUF_ERROR next call, see above */
  8195. }
  8196. return Z_OK;
  8197. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  8198. * of deflate should use the same flush parameter to make sure
  8199. * that the flush is complete. So we don't have to output an
  8200. * empty block here, this will be done at next call. This also
  8201. * ensures that for a very small output buffer, we emit at most
  8202. * one empty block.
  8203. */
  8204. }
  8205. if (bstate === BS_BLOCK_DONE) {
  8206. if (flush === Z_PARTIAL_FLUSH) {
  8207. trees._tr_align(s);
  8208. }
  8209. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  8210. trees._tr_stored_block(s, 0, 0, false);
  8211. /* For a full flush, this empty block will be recognized
  8212. * as a special marker by inflate_sync().
  8213. */
  8214. if (flush === Z_FULL_FLUSH) {
  8215. /*** CLEAR_HASH(s); ***/ /* forget history */
  8216. zero(s.head); // Fill with NIL (= 0);
  8217. if (s.lookahead === 0) {
  8218. s.strstart = 0;
  8219. s.block_start = 0;
  8220. s.insert = 0;
  8221. }
  8222. }
  8223. }
  8224. flush_pending(strm);
  8225. if (strm.avail_out === 0) {
  8226. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  8227. return Z_OK;
  8228. }
  8229. }
  8230. }
  8231. //Assert(strm->avail_out > 0, "bug2");
  8232. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  8233. if (flush !== Z_FINISH) { return Z_OK; }
  8234. if (s.wrap <= 0) { return Z_STREAM_END; }
  8235. /* Write the trailer */
  8236. if (s.wrap === 2) {
  8237. put_byte(s, strm.adler & 0xff);
  8238. put_byte(s, (strm.adler >> 8) & 0xff);
  8239. put_byte(s, (strm.adler >> 16) & 0xff);
  8240. put_byte(s, (strm.adler >> 24) & 0xff);
  8241. put_byte(s, strm.total_in & 0xff);
  8242. put_byte(s, (strm.total_in >> 8) & 0xff);
  8243. put_byte(s, (strm.total_in >> 16) & 0xff);
  8244. put_byte(s, (strm.total_in >> 24) & 0xff);
  8245. }
  8246. else
  8247. {
  8248. putShortMSB(s, strm.adler >>> 16);
  8249. putShortMSB(s, strm.adler & 0xffff);
  8250. }
  8251. flush_pending(strm);
  8252. /* If avail_out is zero, the application will call deflate again
  8253. * to flush the rest.
  8254. */
  8255. if (s.wrap > 0) { s.wrap = -s.wrap; }
  8256. /* write the trailer only once! */
  8257. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  8258. }
  8259. function deflateEnd(strm) {
  8260. var status;
  8261. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  8262. return Z_STREAM_ERROR;
  8263. }
  8264. status = strm.state.status;
  8265. if (status !== INIT_STATE &&
  8266. status !== EXTRA_STATE &&
  8267. status !== NAME_STATE &&
  8268. status !== COMMENT_STATE &&
  8269. status !== HCRC_STATE &&
  8270. status !== BUSY_STATE &&
  8271. status !== FINISH_STATE
  8272. ) {
  8273. return err(strm, Z_STREAM_ERROR);
  8274. }
  8275. strm.state = null;
  8276. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  8277. }
  8278. /* =========================================================================
  8279. * Initializes the compression dictionary from the given byte
  8280. * sequence without producing any compressed output.
  8281. */
  8282. function deflateSetDictionary(strm, dictionary) {
  8283. var dictLength = dictionary.length;
  8284. var s;
  8285. var str, n;
  8286. var wrap;
  8287. var avail;
  8288. var next;
  8289. var input;
  8290. var tmpDict;
  8291. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  8292. return Z_STREAM_ERROR;
  8293. }
  8294. s = strm.state;
  8295. wrap = s.wrap;
  8296. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  8297. return Z_STREAM_ERROR;
  8298. }
  8299. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  8300. if (wrap === 1) {
  8301. /* adler32(strm->adler, dictionary, dictLength); */
  8302. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  8303. }
  8304. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  8305. /* if dictionary would fill window, just replace the history */
  8306. if (dictLength >= s.w_size) {
  8307. if (wrap === 0) { /* already empty otherwise */
  8308. /*** CLEAR_HASH(s); ***/
  8309. zero(s.head); // Fill with NIL (= 0);
  8310. s.strstart = 0;
  8311. s.block_start = 0;
  8312. s.insert = 0;
  8313. }
  8314. /* use the tail */
  8315. // dictionary = dictionary.slice(dictLength - s.w_size);
  8316. tmpDict = new utils.Buf8(s.w_size);
  8317. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  8318. dictionary = tmpDict;
  8319. dictLength = s.w_size;
  8320. }
  8321. /* insert dictionary into window and hash */
  8322. avail = strm.avail_in;
  8323. next = strm.next_in;
  8324. input = strm.input;
  8325. strm.avail_in = dictLength;
  8326. strm.next_in = 0;
  8327. strm.input = dictionary;
  8328. fill_window(s);
  8329. while (s.lookahead >= MIN_MATCH) {
  8330. str = s.strstart;
  8331. n = s.lookahead - (MIN_MATCH - 1);
  8332. do {
  8333. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  8334. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  8335. s.prev[str & s.w_mask] = s.head[s.ins_h];
  8336. s.head[s.ins_h] = str;
  8337. str++;
  8338. } while (--n);
  8339. s.strstart = str;
  8340. s.lookahead = MIN_MATCH - 1;
  8341. fill_window(s);
  8342. }
  8343. s.strstart += s.lookahead;
  8344. s.block_start = s.strstart;
  8345. s.insert = s.lookahead;
  8346. s.lookahead = 0;
  8347. s.match_length = s.prev_length = MIN_MATCH - 1;
  8348. s.match_available = 0;
  8349. strm.next_in = next;
  8350. strm.input = input;
  8351. strm.avail_in = avail;
  8352. s.wrap = wrap;
  8353. return Z_OK;
  8354. }
  8355. exports.deflateInit = deflateInit;
  8356. exports.deflateInit2 = deflateInit2;
  8357. exports.deflateReset = deflateReset;
  8358. exports.deflateResetKeep = deflateResetKeep;
  8359. exports.deflateSetHeader = deflateSetHeader;
  8360. exports.deflate = deflate;
  8361. exports.deflateEnd = deflateEnd;
  8362. exports.deflateSetDictionary = deflateSetDictionary;
  8363. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  8364. /* Not implemented
  8365. exports.deflateBound = deflateBound;
  8366. exports.deflateCopy = deflateCopy;
  8367. exports.deflateParams = deflateParams;
  8368. exports.deflatePending = deflatePending;
  8369. exports.deflatePrime = deflatePrime;
  8370. exports.deflateTune = deflateTune;
  8371. */
  8372. },{"../utils/common":32,"./adler32":34,"./crc32":36,"./messages":42,"./trees":43}],38:[function(_dereq_,module,exports){
  8373. 'use strict';
  8374. function GZheader() {
  8375. /* true if compressed data believed to be text */
  8376. this.text = 0;
  8377. /* modification time */
  8378. this.time = 0;
  8379. /* extra flags (not used when writing a gzip file) */
  8380. this.xflags = 0;
  8381. /* operating system */
  8382. this.os = 0;
  8383. /* pointer to extra field or Z_NULL if none */
  8384. this.extra = null;
  8385. /* extra field length (valid if extra != Z_NULL) */
  8386. this.extra_len = 0; // Actually, we don't need it in JS,
  8387. // but leave for few code modifications
  8388. //
  8389. // Setup limits is not necessary because in js we should not preallocate memory
  8390. // for inflate use constant limit in 65536 bytes
  8391. //
  8392. /* space at extra (only when reading header) */
  8393. // this.extra_max = 0;
  8394. /* pointer to zero-terminated file name or Z_NULL */
  8395. this.name = '';
  8396. /* space at name (only when reading header) */
  8397. // this.name_max = 0;
  8398. /* pointer to zero-terminated comment or Z_NULL */
  8399. this.comment = '';
  8400. /* space at comment (only when reading header) */
  8401. // this.comm_max = 0;
  8402. /* true if there was or will be a header crc */
  8403. this.hcrc = 0;
  8404. /* true when done reading gzip header (not used when writing a gzip file) */
  8405. this.done = false;
  8406. }
  8407. module.exports = GZheader;
  8408. },{}],39:[function(_dereq_,module,exports){
  8409. 'use strict';
  8410. // See state defs from inflate.js
  8411. var BAD = 30; /* got a data error -- remain here until reset */
  8412. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8413. /*
  8414. Decode literal, length, and distance codes and write out the resulting
  8415. literal and match bytes until either not enough input or output is
  8416. available, an end-of-block is encountered, or a data error is encountered.
  8417. When large enough input and output buffers are supplied to inflate(), for
  8418. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  8419. inflate execution time is spent in this routine.
  8420. Entry assumptions:
  8421. state.mode === LEN
  8422. strm.avail_in >= 6
  8423. strm.avail_out >= 258
  8424. start >= strm.avail_out
  8425. state.bits < 8
  8426. On return, state.mode is one of:
  8427. LEN -- ran out of enough output space or enough available input
  8428. TYPE -- reached end of block code, inflate() to interpret next block
  8429. BAD -- error in block data
  8430. Notes:
  8431. - The maximum input bits used by a length/distance pair is 15 bits for the
  8432. length code, 5 bits for the length extra, 15 bits for the distance code,
  8433. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  8434. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  8435. checking for available input while decoding.
  8436. - The maximum bytes that a single length/distance pair can output is 258
  8437. bytes, which is the maximum length that can be coded. inflate_fast()
  8438. requires strm.avail_out >= 258 for each loop to avoid checking for
  8439. output space.
  8440. */
  8441. module.exports = function inflate_fast(strm, start) {
  8442. var state;
  8443. var _in; /* local strm.input */
  8444. var last; /* have enough input while in < last */
  8445. var _out; /* local strm.output */
  8446. var beg; /* inflate()'s initial strm.output */
  8447. var end; /* while out < end, enough space available */
  8448. //#ifdef INFLATE_STRICT
  8449. var dmax; /* maximum distance from zlib header */
  8450. //#endif
  8451. var wsize; /* window size or zero if not using window */
  8452. var whave; /* valid bytes in the window */
  8453. var wnext; /* window write index */
  8454. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  8455. var s_window; /* allocated sliding window, if wsize != 0 */
  8456. var hold; /* local strm.hold */
  8457. var bits; /* local strm.bits */
  8458. var lcode; /* local strm.lencode */
  8459. var dcode; /* local strm.distcode */
  8460. var lmask; /* mask for first level of length codes */
  8461. var dmask; /* mask for first level of distance codes */
  8462. var here; /* retrieved table entry */
  8463. var op; /* code bits, operation, extra bits, or */
  8464. /* window position, window bytes to copy */
  8465. var len; /* match length, unused bytes */
  8466. var dist; /* match distance */
  8467. var from; /* where to copy match from */
  8468. var from_source;
  8469. var input, output; // JS specific, because we have no pointers
  8470. /* copy state to local variables */
  8471. state = strm.state;
  8472. //here = state.here;
  8473. _in = strm.next_in;
  8474. input = strm.input;
  8475. last = _in + (strm.avail_in - 5);
  8476. _out = strm.next_out;
  8477. output = strm.output;
  8478. beg = _out - (start - strm.avail_out);
  8479. end = _out + (strm.avail_out - 257);
  8480. //#ifdef INFLATE_STRICT
  8481. dmax = state.dmax;
  8482. //#endif
  8483. wsize = state.wsize;
  8484. whave = state.whave;
  8485. wnext = state.wnext;
  8486. s_window = state.window;
  8487. hold = state.hold;
  8488. bits = state.bits;
  8489. lcode = state.lencode;
  8490. dcode = state.distcode;
  8491. lmask = (1 << state.lenbits) - 1;
  8492. dmask = (1 << state.distbits) - 1;
  8493. /* decode literals and length/distances until end-of-block or not enough
  8494. input data or output space */
  8495. top:
  8496. do {
  8497. if (bits < 15) {
  8498. hold += input[_in++] << bits;
  8499. bits += 8;
  8500. hold += input[_in++] << bits;
  8501. bits += 8;
  8502. }
  8503. here = lcode[hold & lmask];
  8504. dolen:
  8505. for (;;) { // Goto emulation
  8506. op = here >>> 24/*here.bits*/;
  8507. hold >>>= op;
  8508. bits -= op;
  8509. op = (here >>> 16) & 0xff/*here.op*/;
  8510. if (op === 0) { /* literal */
  8511. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8512. // "inflate: literal '%c'\n" :
  8513. // "inflate: literal 0x%02x\n", here.val));
  8514. output[_out++] = here & 0xffff/*here.val*/;
  8515. }
  8516. else if (op & 16) { /* length base */
  8517. len = here & 0xffff/*here.val*/;
  8518. op &= 15; /* number of extra bits */
  8519. if (op) {
  8520. if (bits < op) {
  8521. hold += input[_in++] << bits;
  8522. bits += 8;
  8523. }
  8524. len += hold & ((1 << op) - 1);
  8525. hold >>>= op;
  8526. bits -= op;
  8527. }
  8528. //Tracevv((stderr, "inflate: length %u\n", len));
  8529. if (bits < 15) {
  8530. hold += input[_in++] << bits;
  8531. bits += 8;
  8532. hold += input[_in++] << bits;
  8533. bits += 8;
  8534. }
  8535. here = dcode[hold & dmask];
  8536. dodist:
  8537. for (;;) { // goto emulation
  8538. op = here >>> 24/*here.bits*/;
  8539. hold >>>= op;
  8540. bits -= op;
  8541. op = (here >>> 16) & 0xff/*here.op*/;
  8542. if (op & 16) { /* distance base */
  8543. dist = here & 0xffff/*here.val*/;
  8544. op &= 15; /* number of extra bits */
  8545. if (bits < op) {
  8546. hold += input[_in++] << bits;
  8547. bits += 8;
  8548. if (bits < op) {
  8549. hold += input[_in++] << bits;
  8550. bits += 8;
  8551. }
  8552. }
  8553. dist += hold & ((1 << op) - 1);
  8554. //#ifdef INFLATE_STRICT
  8555. if (dist > dmax) {
  8556. strm.msg = 'invalid distance too far back';
  8557. state.mode = BAD;
  8558. break top;
  8559. }
  8560. //#endif
  8561. hold >>>= op;
  8562. bits -= op;
  8563. //Tracevv((stderr, "inflate: distance %u\n", dist));
  8564. op = _out - beg; /* max distance in output */
  8565. if (dist > op) { /* see if copy from window */
  8566. op = dist - op; /* distance back in window */
  8567. if (op > whave) {
  8568. if (state.sane) {
  8569. strm.msg = 'invalid distance too far back';
  8570. state.mode = BAD;
  8571. break top;
  8572. }
  8573. // (!) This block is disabled in zlib defailts,
  8574. // don't enable it for binary compatibility
  8575. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8576. // if (len <= op - whave) {
  8577. // do {
  8578. // output[_out++] = 0;
  8579. // } while (--len);
  8580. // continue top;
  8581. // }
  8582. // len -= op - whave;
  8583. // do {
  8584. // output[_out++] = 0;
  8585. // } while (--op > whave);
  8586. // if (op === 0) {
  8587. // from = _out - dist;
  8588. // do {
  8589. // output[_out++] = output[from++];
  8590. // } while (--len);
  8591. // continue top;
  8592. // }
  8593. //#endif
  8594. }
  8595. from = 0; // window index
  8596. from_source = s_window;
  8597. if (wnext === 0) { /* very common case */
  8598. from += wsize - op;
  8599. if (op < len) { /* some from window */
  8600. len -= op;
  8601. do {
  8602. output[_out++] = s_window[from++];
  8603. } while (--op);
  8604. from = _out - dist; /* rest from output */
  8605. from_source = output;
  8606. }
  8607. }
  8608. else if (wnext < op) { /* wrap around window */
  8609. from += wsize + wnext - op;
  8610. op -= wnext;
  8611. if (op < len) { /* some from end of window */
  8612. len -= op;
  8613. do {
  8614. output[_out++] = s_window[from++];
  8615. } while (--op);
  8616. from = 0;
  8617. if (wnext < len) { /* some from start of window */
  8618. op = wnext;
  8619. len -= op;
  8620. do {
  8621. output[_out++] = s_window[from++];
  8622. } while (--op);
  8623. from = _out - dist; /* rest from output */
  8624. from_source = output;
  8625. }
  8626. }
  8627. }
  8628. else { /* contiguous in window */
  8629. from += wnext - op;
  8630. if (op < len) { /* some from window */
  8631. len -= op;
  8632. do {
  8633. output[_out++] = s_window[from++];
  8634. } while (--op);
  8635. from = _out - dist; /* rest from output */
  8636. from_source = output;
  8637. }
  8638. }
  8639. while (len > 2) {
  8640. output[_out++] = from_source[from++];
  8641. output[_out++] = from_source[from++];
  8642. output[_out++] = from_source[from++];
  8643. len -= 3;
  8644. }
  8645. if (len) {
  8646. output[_out++] = from_source[from++];
  8647. if (len > 1) {
  8648. output[_out++] = from_source[from++];
  8649. }
  8650. }
  8651. }
  8652. else {
  8653. from = _out - dist; /* copy direct from output */
  8654. do { /* minimum length is three */
  8655. output[_out++] = output[from++];
  8656. output[_out++] = output[from++];
  8657. output[_out++] = output[from++];
  8658. len -= 3;
  8659. } while (len > 2);
  8660. if (len) {
  8661. output[_out++] = output[from++];
  8662. if (len > 1) {
  8663. output[_out++] = output[from++];
  8664. }
  8665. }
  8666. }
  8667. }
  8668. else if ((op & 64) === 0) { /* 2nd level distance code */
  8669. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8670. continue dodist;
  8671. }
  8672. else {
  8673. strm.msg = 'invalid distance code';
  8674. state.mode = BAD;
  8675. break top;
  8676. }
  8677. break; // need to emulate goto via "continue"
  8678. }
  8679. }
  8680. else if ((op & 64) === 0) { /* 2nd level length code */
  8681. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8682. continue dolen;
  8683. }
  8684. else if (op & 32) { /* end-of-block */
  8685. //Tracevv((stderr, "inflate: end of block\n"));
  8686. state.mode = TYPE;
  8687. break top;
  8688. }
  8689. else {
  8690. strm.msg = 'invalid literal/length code';
  8691. state.mode = BAD;
  8692. break top;
  8693. }
  8694. break; // need to emulate goto via "continue"
  8695. }
  8696. } while (_in < last && _out < end);
  8697. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  8698. len = bits >> 3;
  8699. _in -= len;
  8700. bits -= len << 3;
  8701. hold &= (1 << bits) - 1;
  8702. /* update state and return */
  8703. strm.next_in = _in;
  8704. strm.next_out = _out;
  8705. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  8706. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  8707. state.hold = hold;
  8708. state.bits = bits;
  8709. return;
  8710. };
  8711. },{}],40:[function(_dereq_,module,exports){
  8712. 'use strict';
  8713. var utils = _dereq_('../utils/common');
  8714. var adler32 = _dereq_('./adler32');
  8715. var crc32 = _dereq_('./crc32');
  8716. var inflate_fast = _dereq_('./inffast');
  8717. var inflate_table = _dereq_('./inftrees');
  8718. var CODES = 0;
  8719. var LENS = 1;
  8720. var DISTS = 2;
  8721. /* Public constants ==========================================================*/
  8722. /* ===========================================================================*/
  8723. /* Allowed flush values; see deflate() and inflate() below for details */
  8724. //var Z_NO_FLUSH = 0;
  8725. //var Z_PARTIAL_FLUSH = 1;
  8726. //var Z_SYNC_FLUSH = 2;
  8727. //var Z_FULL_FLUSH = 3;
  8728. var Z_FINISH = 4;
  8729. var Z_BLOCK = 5;
  8730. var Z_TREES = 6;
  8731. /* Return codes for the compression/decompression functions. Negative values
  8732. * are errors, positive values are used for special but normal events.
  8733. */
  8734. var Z_OK = 0;
  8735. var Z_STREAM_END = 1;
  8736. var Z_NEED_DICT = 2;
  8737. //var Z_ERRNO = -1;
  8738. var Z_STREAM_ERROR = -2;
  8739. var Z_DATA_ERROR = -3;
  8740. var Z_MEM_ERROR = -4;
  8741. var Z_BUF_ERROR = -5;
  8742. //var Z_VERSION_ERROR = -6;
  8743. /* The deflate compression method */
  8744. var Z_DEFLATED = 8;
  8745. /* STATES ====================================================================*/
  8746. /* ===========================================================================*/
  8747. var HEAD = 1; /* i: waiting for magic header */
  8748. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  8749. var TIME = 3; /* i: waiting for modification time (gzip) */
  8750. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  8751. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  8752. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  8753. var NAME = 7; /* i: waiting for end of file name (gzip) */
  8754. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  8755. var HCRC = 9; /* i: waiting for header crc (gzip) */
  8756. var DICTID = 10; /* i: waiting for dictionary check value */
  8757. var DICT = 11; /* waiting for inflateSetDictionary() call */
  8758. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  8759. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  8760. var STORED = 14; /* i: waiting for stored size (length and complement) */
  8761. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  8762. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  8763. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  8764. var LENLENS = 18; /* i: waiting for code length code lengths */
  8765. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  8766. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  8767. var LEN = 21; /* i: waiting for length/lit/eob code */
  8768. var LENEXT = 22; /* i: waiting for length extra bits */
  8769. var DIST = 23; /* i: waiting for distance code */
  8770. var DISTEXT = 24; /* i: waiting for distance extra bits */
  8771. var MATCH = 25; /* o: waiting for output space to copy string */
  8772. var LIT = 26; /* o: waiting for output space to write literal */
  8773. var CHECK = 27; /* i: waiting for 32-bit check value */
  8774. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  8775. var DONE = 29; /* finished check, done -- remain here until reset */
  8776. var BAD = 30; /* got a data error -- remain here until reset */
  8777. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  8778. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  8779. /* ===========================================================================*/
  8780. var ENOUGH_LENS = 852;
  8781. var ENOUGH_DISTS = 592;
  8782. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  8783. var MAX_WBITS = 15;
  8784. /* 32K LZ77 window */
  8785. var DEF_WBITS = MAX_WBITS;
  8786. function zswap32(q) {
  8787. return (((q >>> 24) & 0xff) +
  8788. ((q >>> 8) & 0xff00) +
  8789. ((q & 0xff00) << 8) +
  8790. ((q & 0xff) << 24));
  8791. }
  8792. function InflateState() {
  8793. this.mode = 0; /* current inflate mode */
  8794. this.last = false; /* true if processing last block */
  8795. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  8796. this.havedict = false; /* true if dictionary provided */
  8797. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  8798. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  8799. this.check = 0; /* protected copy of check value */
  8800. this.total = 0; /* protected copy of output count */
  8801. // TODO: may be {}
  8802. this.head = null; /* where to save gzip header information */
  8803. /* sliding window */
  8804. this.wbits = 0; /* log base 2 of requested window size */
  8805. this.wsize = 0; /* window size or zero if not using window */
  8806. this.whave = 0; /* valid bytes in the window */
  8807. this.wnext = 0; /* window write index */
  8808. this.window = null; /* allocated sliding window, if needed */
  8809. /* bit accumulator */
  8810. this.hold = 0; /* input bit accumulator */
  8811. this.bits = 0; /* number of bits in "in" */
  8812. /* for string and stored block copying */
  8813. this.length = 0; /* literal or length of data to copy */
  8814. this.offset = 0; /* distance back to copy string from */
  8815. /* for table and code decoding */
  8816. this.extra = 0; /* extra bits needed */
  8817. /* fixed and dynamic code tables */
  8818. this.lencode = null; /* starting table for length/literal codes */
  8819. this.distcode = null; /* starting table for distance codes */
  8820. this.lenbits = 0; /* index bits for lencode */
  8821. this.distbits = 0; /* index bits for distcode */
  8822. /* dynamic table building */
  8823. this.ncode = 0; /* number of code length code lengths */
  8824. this.nlen = 0; /* number of length code lengths */
  8825. this.ndist = 0; /* number of distance code lengths */
  8826. this.have = 0; /* number of code lengths in lens[] */
  8827. this.next = null; /* next available space in codes[] */
  8828. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  8829. this.work = new utils.Buf16(288); /* work area for code table building */
  8830. /*
  8831. because we don't have pointers in js, we use lencode and distcode directly
  8832. as buffers so we don't need codes
  8833. */
  8834. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  8835. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  8836. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  8837. this.sane = 0; /* if false, allow invalid distance too far */
  8838. this.back = 0; /* bits back of last unprocessed length/lit */
  8839. this.was = 0; /* initial length of match */
  8840. }
  8841. function inflateResetKeep(strm) {
  8842. var state;
  8843. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8844. state = strm.state;
  8845. strm.total_in = strm.total_out = state.total = 0;
  8846. strm.msg = ''; /*Z_NULL*/
  8847. if (state.wrap) { /* to support ill-conceived Java test suite */
  8848. strm.adler = state.wrap & 1;
  8849. }
  8850. state.mode = HEAD;
  8851. state.last = 0;
  8852. state.havedict = 0;
  8853. state.dmax = 32768;
  8854. state.head = null/*Z_NULL*/;
  8855. state.hold = 0;
  8856. state.bits = 0;
  8857. //state.lencode = state.distcode = state.next = state.codes;
  8858. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  8859. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  8860. state.sane = 1;
  8861. state.back = -1;
  8862. //Tracev((stderr, "inflate: reset\n"));
  8863. return Z_OK;
  8864. }
  8865. function inflateReset(strm) {
  8866. var state;
  8867. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8868. state = strm.state;
  8869. state.wsize = 0;
  8870. state.whave = 0;
  8871. state.wnext = 0;
  8872. return inflateResetKeep(strm);
  8873. }
  8874. function inflateReset2(strm, windowBits) {
  8875. var wrap;
  8876. var state;
  8877. /* get the state */
  8878. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8879. state = strm.state;
  8880. /* extract wrap request from windowBits parameter */
  8881. if (windowBits < 0) {
  8882. wrap = 0;
  8883. windowBits = -windowBits;
  8884. }
  8885. else {
  8886. wrap = (windowBits >> 4) + 1;
  8887. if (windowBits < 48) {
  8888. windowBits &= 15;
  8889. }
  8890. }
  8891. /* set number of window bits, free window if different */
  8892. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  8893. return Z_STREAM_ERROR;
  8894. }
  8895. if (state.window !== null && state.wbits !== windowBits) {
  8896. state.window = null;
  8897. }
  8898. /* update state and reset the rest of it */
  8899. state.wrap = wrap;
  8900. state.wbits = windowBits;
  8901. return inflateReset(strm);
  8902. }
  8903. function inflateInit2(strm, windowBits) {
  8904. var ret;
  8905. var state;
  8906. if (!strm) { return Z_STREAM_ERROR; }
  8907. //strm.msg = Z_NULL; /* in case we return an error */
  8908. state = new InflateState();
  8909. //if (state === Z_NULL) return Z_MEM_ERROR;
  8910. //Tracev((stderr, "inflate: allocated\n"));
  8911. strm.state = state;
  8912. state.window = null/*Z_NULL*/;
  8913. ret = inflateReset2(strm, windowBits);
  8914. if (ret !== Z_OK) {
  8915. strm.state = null/*Z_NULL*/;
  8916. }
  8917. return ret;
  8918. }
  8919. function inflateInit(strm) {
  8920. return inflateInit2(strm, DEF_WBITS);
  8921. }
  8922. /*
  8923. Return state with length and distance decoding tables and index sizes set to
  8924. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  8925. If BUILDFIXED is defined, then instead this routine builds the tables the
  8926. first time it's called, and returns those tables the first time and
  8927. thereafter. This reduces the size of the code by about 2K bytes, in
  8928. exchange for a little execution time. However, BUILDFIXED should not be
  8929. used for threaded applications, since the rewriting of the tables and virgin
  8930. may not be thread-safe.
  8931. */
  8932. var virgin = true;
  8933. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  8934. function fixedtables(state) {
  8935. /* build fixed huffman tables if first call (may not be thread safe) */
  8936. if (virgin) {
  8937. var sym;
  8938. lenfix = new utils.Buf32(512);
  8939. distfix = new utils.Buf32(32);
  8940. /* literal/length table */
  8941. sym = 0;
  8942. while (sym < 144) { state.lens[sym++] = 8; }
  8943. while (sym < 256) { state.lens[sym++] = 9; }
  8944. while (sym < 280) { state.lens[sym++] = 7; }
  8945. while (sym < 288) { state.lens[sym++] = 8; }
  8946. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  8947. /* distance table */
  8948. sym = 0;
  8949. while (sym < 32) { state.lens[sym++] = 5; }
  8950. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  8951. /* do this just once */
  8952. virgin = false;
  8953. }
  8954. state.lencode = lenfix;
  8955. state.lenbits = 9;
  8956. state.distcode = distfix;
  8957. state.distbits = 5;
  8958. }
  8959. /*
  8960. Update the window with the last wsize (normally 32K) bytes written before
  8961. returning. If window does not exist yet, create it. This is only called
  8962. when a window is already in use, or when output has been written during this
  8963. inflate call, but the end of the deflate stream has not been reached yet.
  8964. It is also called to create a window for dictionary data when a dictionary
  8965. is loaded.
  8966. Providing output buffers larger than 32K to inflate() should provide a speed
  8967. advantage, since only the last 32K of output is copied to the sliding window
  8968. upon return from inflate(), and since all distances after the first 32K of
  8969. output will fall in the output data, making match copies simpler and faster.
  8970. The advantage may be dependent on the size of the processor's data caches.
  8971. */
  8972. function updatewindow(strm, src, end, copy) {
  8973. var dist;
  8974. var state = strm.state;
  8975. /* if it hasn't been done already, allocate space for the window */
  8976. if (state.window === null) {
  8977. state.wsize = 1 << state.wbits;
  8978. state.wnext = 0;
  8979. state.whave = 0;
  8980. state.window = new utils.Buf8(state.wsize);
  8981. }
  8982. /* copy state->wsize or less output bytes into the circular window */
  8983. if (copy >= state.wsize) {
  8984. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  8985. state.wnext = 0;
  8986. state.whave = state.wsize;
  8987. }
  8988. else {
  8989. dist = state.wsize - state.wnext;
  8990. if (dist > copy) {
  8991. dist = copy;
  8992. }
  8993. //zmemcpy(state->window + state->wnext, end - copy, dist);
  8994. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  8995. copy -= dist;
  8996. if (copy) {
  8997. //zmemcpy(state->window, end - copy, copy);
  8998. utils.arraySet(state.window, src, end - copy, copy, 0);
  8999. state.wnext = copy;
  9000. state.whave = state.wsize;
  9001. }
  9002. else {
  9003. state.wnext += dist;
  9004. if (state.wnext === state.wsize) { state.wnext = 0; }
  9005. if (state.whave < state.wsize) { state.whave += dist; }
  9006. }
  9007. }
  9008. return 0;
  9009. }
  9010. function inflate(strm, flush) {
  9011. var state;
  9012. var input, output; // input/output buffers
  9013. var next; /* next input INDEX */
  9014. var put; /* next output INDEX */
  9015. var have, left; /* available input and output */
  9016. var hold; /* bit buffer */
  9017. var bits; /* bits in bit buffer */
  9018. var _in, _out; /* save starting available input and output */
  9019. var copy; /* number of stored or match bytes to copy */
  9020. var from; /* where to copy match bytes from */
  9021. var from_source;
  9022. var here = 0; /* current decoding table entry */
  9023. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  9024. //var last; /* parent table entry */
  9025. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  9026. var len; /* length to copy for repeats, bits to drop */
  9027. var ret; /* return code */
  9028. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  9029. var opts;
  9030. var n; // temporary var for NEED_BITS
  9031. var order = /* permutation of code lengths */
  9032. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  9033. if (!strm || !strm.state || !strm.output ||
  9034. (!strm.input && strm.avail_in !== 0)) {
  9035. return Z_STREAM_ERROR;
  9036. }
  9037. state = strm.state;
  9038. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  9039. //--- LOAD() ---
  9040. put = strm.next_out;
  9041. output = strm.output;
  9042. left = strm.avail_out;
  9043. next = strm.next_in;
  9044. input = strm.input;
  9045. have = strm.avail_in;
  9046. hold = state.hold;
  9047. bits = state.bits;
  9048. //---
  9049. _in = have;
  9050. _out = left;
  9051. ret = Z_OK;
  9052. inf_leave: // goto emulation
  9053. for (;;) {
  9054. switch (state.mode) {
  9055. case HEAD:
  9056. if (state.wrap === 0) {
  9057. state.mode = TYPEDO;
  9058. break;
  9059. }
  9060. //=== NEEDBITS(16);
  9061. while (bits < 16) {
  9062. if (have === 0) { break inf_leave; }
  9063. have--;
  9064. hold += input[next++] << bits;
  9065. bits += 8;
  9066. }
  9067. //===//
  9068. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  9069. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  9070. //=== CRC2(state.check, hold);
  9071. hbuf[0] = hold & 0xff;
  9072. hbuf[1] = (hold >>> 8) & 0xff;
  9073. state.check = crc32(state.check, hbuf, 2, 0);
  9074. //===//
  9075. //=== INITBITS();
  9076. hold = 0;
  9077. bits = 0;
  9078. //===//
  9079. state.mode = FLAGS;
  9080. break;
  9081. }
  9082. state.flags = 0; /* expect zlib header */
  9083. if (state.head) {
  9084. state.head.done = false;
  9085. }
  9086. if (!(state.wrap & 1) || /* check if zlib header allowed */
  9087. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  9088. strm.msg = 'incorrect header check';
  9089. state.mode = BAD;
  9090. break;
  9091. }
  9092. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  9093. strm.msg = 'unknown compression method';
  9094. state.mode = BAD;
  9095. break;
  9096. }
  9097. //--- DROPBITS(4) ---//
  9098. hold >>>= 4;
  9099. bits -= 4;
  9100. //---//
  9101. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  9102. if (state.wbits === 0) {
  9103. state.wbits = len;
  9104. }
  9105. else if (len > state.wbits) {
  9106. strm.msg = 'invalid window size';
  9107. state.mode = BAD;
  9108. break;
  9109. }
  9110. state.dmax = 1 << len;
  9111. //Tracev((stderr, "inflate: zlib header ok\n"));
  9112. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  9113. state.mode = hold & 0x200 ? DICTID : TYPE;
  9114. //=== INITBITS();
  9115. hold = 0;
  9116. bits = 0;
  9117. //===//
  9118. break;
  9119. case FLAGS:
  9120. //=== NEEDBITS(16); */
  9121. while (bits < 16) {
  9122. if (have === 0) { break inf_leave; }
  9123. have--;
  9124. hold += input[next++] << bits;
  9125. bits += 8;
  9126. }
  9127. //===//
  9128. state.flags = hold;
  9129. if ((state.flags & 0xff) !== Z_DEFLATED) {
  9130. strm.msg = 'unknown compression method';
  9131. state.mode = BAD;
  9132. break;
  9133. }
  9134. if (state.flags & 0xe000) {
  9135. strm.msg = 'unknown header flags set';
  9136. state.mode = BAD;
  9137. break;
  9138. }
  9139. if (state.head) {
  9140. state.head.text = ((hold >> 8) & 1);
  9141. }
  9142. if (state.flags & 0x0200) {
  9143. //=== CRC2(state.check, hold);
  9144. hbuf[0] = hold & 0xff;
  9145. hbuf[1] = (hold >>> 8) & 0xff;
  9146. state.check = crc32(state.check, hbuf, 2, 0);
  9147. //===//
  9148. }
  9149. //=== INITBITS();
  9150. hold = 0;
  9151. bits = 0;
  9152. //===//
  9153. state.mode = TIME;
  9154. /* falls through */
  9155. case TIME:
  9156. //=== NEEDBITS(32); */
  9157. while (bits < 32) {
  9158. if (have === 0) { break inf_leave; }
  9159. have--;
  9160. hold += input[next++] << bits;
  9161. bits += 8;
  9162. }
  9163. //===//
  9164. if (state.head) {
  9165. state.head.time = hold;
  9166. }
  9167. if (state.flags & 0x0200) {
  9168. //=== CRC4(state.check, hold)
  9169. hbuf[0] = hold & 0xff;
  9170. hbuf[1] = (hold >>> 8) & 0xff;
  9171. hbuf[2] = (hold >>> 16) & 0xff;
  9172. hbuf[3] = (hold >>> 24) & 0xff;
  9173. state.check = crc32(state.check, hbuf, 4, 0);
  9174. //===
  9175. }
  9176. //=== INITBITS();
  9177. hold = 0;
  9178. bits = 0;
  9179. //===//
  9180. state.mode = OS;
  9181. /* falls through */
  9182. case OS:
  9183. //=== NEEDBITS(16); */
  9184. while (bits < 16) {
  9185. if (have === 0) { break inf_leave; }
  9186. have--;
  9187. hold += input[next++] << bits;
  9188. bits += 8;
  9189. }
  9190. //===//
  9191. if (state.head) {
  9192. state.head.xflags = (hold & 0xff);
  9193. state.head.os = (hold >> 8);
  9194. }
  9195. if (state.flags & 0x0200) {
  9196. //=== CRC2(state.check, hold);
  9197. hbuf[0] = hold & 0xff;
  9198. hbuf[1] = (hold >>> 8) & 0xff;
  9199. state.check = crc32(state.check, hbuf, 2, 0);
  9200. //===//
  9201. }
  9202. //=== INITBITS();
  9203. hold = 0;
  9204. bits = 0;
  9205. //===//
  9206. state.mode = EXLEN;
  9207. /* falls through */
  9208. case EXLEN:
  9209. if (state.flags & 0x0400) {
  9210. //=== NEEDBITS(16); */
  9211. while (bits < 16) {
  9212. if (have === 0) { break inf_leave; }
  9213. have--;
  9214. hold += input[next++] << bits;
  9215. bits += 8;
  9216. }
  9217. //===//
  9218. state.length = hold;
  9219. if (state.head) {
  9220. state.head.extra_len = hold;
  9221. }
  9222. if (state.flags & 0x0200) {
  9223. //=== CRC2(state.check, hold);
  9224. hbuf[0] = hold & 0xff;
  9225. hbuf[1] = (hold >>> 8) & 0xff;
  9226. state.check = crc32(state.check, hbuf, 2, 0);
  9227. //===//
  9228. }
  9229. //=== INITBITS();
  9230. hold = 0;
  9231. bits = 0;
  9232. //===//
  9233. }
  9234. else if (state.head) {
  9235. state.head.extra = null/*Z_NULL*/;
  9236. }
  9237. state.mode = EXTRA;
  9238. /* falls through */
  9239. case EXTRA:
  9240. if (state.flags & 0x0400) {
  9241. copy = state.length;
  9242. if (copy > have) { copy = have; }
  9243. if (copy) {
  9244. if (state.head) {
  9245. len = state.head.extra_len - state.length;
  9246. if (!state.head.extra) {
  9247. // Use untyped array for more conveniend processing later
  9248. state.head.extra = new Array(state.head.extra_len);
  9249. }
  9250. utils.arraySet(
  9251. state.head.extra,
  9252. input,
  9253. next,
  9254. // extra field is limited to 65536 bytes
  9255. // - no need for additional size check
  9256. copy,
  9257. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  9258. len
  9259. );
  9260. //zmemcpy(state.head.extra + len, next,
  9261. // len + copy > state.head.extra_max ?
  9262. // state.head.extra_max - len : copy);
  9263. }
  9264. if (state.flags & 0x0200) {
  9265. state.check = crc32(state.check, input, copy, next);
  9266. }
  9267. have -= copy;
  9268. next += copy;
  9269. state.length -= copy;
  9270. }
  9271. if (state.length) { break inf_leave; }
  9272. }
  9273. state.length = 0;
  9274. state.mode = NAME;
  9275. /* falls through */
  9276. case NAME:
  9277. if (state.flags & 0x0800) {
  9278. if (have === 0) { break inf_leave; }
  9279. copy = 0;
  9280. do {
  9281. // TODO: 2 or 1 bytes?
  9282. len = input[next + copy++];
  9283. /* use constant limit because in js we should not preallocate memory */
  9284. if (state.head && len &&
  9285. (state.length < 65536 /*state.head.name_max*/)) {
  9286. state.head.name += String.fromCharCode(len);
  9287. }
  9288. } while (len && copy < have);
  9289. if (state.flags & 0x0200) {
  9290. state.check = crc32(state.check, input, copy, next);
  9291. }
  9292. have -= copy;
  9293. next += copy;
  9294. if (len) { break inf_leave; }
  9295. }
  9296. else if (state.head) {
  9297. state.head.name = null;
  9298. }
  9299. state.length = 0;
  9300. state.mode = COMMENT;
  9301. /* falls through */
  9302. case COMMENT:
  9303. if (state.flags & 0x1000) {
  9304. if (have === 0) { break inf_leave; }
  9305. copy = 0;
  9306. do {
  9307. len = input[next + copy++];
  9308. /* use constant limit because in js we should not preallocate memory */
  9309. if (state.head && len &&
  9310. (state.length < 65536 /*state.head.comm_max*/)) {
  9311. state.head.comment += String.fromCharCode(len);
  9312. }
  9313. } while (len && copy < have);
  9314. if (state.flags & 0x0200) {
  9315. state.check = crc32(state.check, input, copy, next);
  9316. }
  9317. have -= copy;
  9318. next += copy;
  9319. if (len) { break inf_leave; }
  9320. }
  9321. else if (state.head) {
  9322. state.head.comment = null;
  9323. }
  9324. state.mode = HCRC;
  9325. /* falls through */
  9326. case HCRC:
  9327. if (state.flags & 0x0200) {
  9328. //=== NEEDBITS(16); */
  9329. while (bits < 16) {
  9330. if (have === 0) { break inf_leave; }
  9331. have--;
  9332. hold += input[next++] << bits;
  9333. bits += 8;
  9334. }
  9335. //===//
  9336. if (hold !== (state.check & 0xffff)) {
  9337. strm.msg = 'header crc mismatch';
  9338. state.mode = BAD;
  9339. break;
  9340. }
  9341. //=== INITBITS();
  9342. hold = 0;
  9343. bits = 0;
  9344. //===//
  9345. }
  9346. if (state.head) {
  9347. state.head.hcrc = ((state.flags >> 9) & 1);
  9348. state.head.done = true;
  9349. }
  9350. strm.adler = state.check = 0;
  9351. state.mode = TYPE;
  9352. break;
  9353. case DICTID:
  9354. //=== NEEDBITS(32); */
  9355. while (bits < 32) {
  9356. if (have === 0) { break inf_leave; }
  9357. have--;
  9358. hold += input[next++] << bits;
  9359. bits += 8;
  9360. }
  9361. //===//
  9362. strm.adler = state.check = zswap32(hold);
  9363. //=== INITBITS();
  9364. hold = 0;
  9365. bits = 0;
  9366. //===//
  9367. state.mode = DICT;
  9368. /* falls through */
  9369. case DICT:
  9370. if (state.havedict === 0) {
  9371. //--- RESTORE() ---
  9372. strm.next_out = put;
  9373. strm.avail_out = left;
  9374. strm.next_in = next;
  9375. strm.avail_in = have;
  9376. state.hold = hold;
  9377. state.bits = bits;
  9378. //---
  9379. return Z_NEED_DICT;
  9380. }
  9381. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  9382. state.mode = TYPE;
  9383. /* falls through */
  9384. case TYPE:
  9385. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  9386. /* falls through */
  9387. case TYPEDO:
  9388. if (state.last) {
  9389. //--- BYTEBITS() ---//
  9390. hold >>>= bits & 7;
  9391. bits -= bits & 7;
  9392. //---//
  9393. state.mode = CHECK;
  9394. break;
  9395. }
  9396. //=== NEEDBITS(3); */
  9397. while (bits < 3) {
  9398. if (have === 0) { break inf_leave; }
  9399. have--;
  9400. hold += input[next++] << bits;
  9401. bits += 8;
  9402. }
  9403. //===//
  9404. state.last = (hold & 0x01)/*BITS(1)*/;
  9405. //--- DROPBITS(1) ---//
  9406. hold >>>= 1;
  9407. bits -= 1;
  9408. //---//
  9409. switch ((hold & 0x03)/*BITS(2)*/) {
  9410. case 0: /* stored block */
  9411. //Tracev((stderr, "inflate: stored block%s\n",
  9412. // state.last ? " (last)" : ""));
  9413. state.mode = STORED;
  9414. break;
  9415. case 1: /* fixed block */
  9416. fixedtables(state);
  9417. //Tracev((stderr, "inflate: fixed codes block%s\n",
  9418. // state.last ? " (last)" : ""));
  9419. state.mode = LEN_; /* decode codes */
  9420. if (flush === Z_TREES) {
  9421. //--- DROPBITS(2) ---//
  9422. hold >>>= 2;
  9423. bits -= 2;
  9424. //---//
  9425. break inf_leave;
  9426. }
  9427. break;
  9428. case 2: /* dynamic block */
  9429. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  9430. // state.last ? " (last)" : ""));
  9431. state.mode = TABLE;
  9432. break;
  9433. case 3:
  9434. strm.msg = 'invalid block type';
  9435. state.mode = BAD;
  9436. }
  9437. //--- DROPBITS(2) ---//
  9438. hold >>>= 2;
  9439. bits -= 2;
  9440. //---//
  9441. break;
  9442. case STORED:
  9443. //--- BYTEBITS() ---// /* go to byte boundary */
  9444. hold >>>= bits & 7;
  9445. bits -= bits & 7;
  9446. //---//
  9447. //=== NEEDBITS(32); */
  9448. while (bits < 32) {
  9449. if (have === 0) { break inf_leave; }
  9450. have--;
  9451. hold += input[next++] << bits;
  9452. bits += 8;
  9453. }
  9454. //===//
  9455. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  9456. strm.msg = 'invalid stored block lengths';
  9457. state.mode = BAD;
  9458. break;
  9459. }
  9460. state.length = hold & 0xffff;
  9461. //Tracev((stderr, "inflate: stored length %u\n",
  9462. // state.length));
  9463. //=== INITBITS();
  9464. hold = 0;
  9465. bits = 0;
  9466. //===//
  9467. state.mode = COPY_;
  9468. if (flush === Z_TREES) { break inf_leave; }
  9469. /* falls through */
  9470. case COPY_:
  9471. state.mode = COPY;
  9472. /* falls through */
  9473. case COPY:
  9474. copy = state.length;
  9475. if (copy) {
  9476. if (copy > have) { copy = have; }
  9477. if (copy > left) { copy = left; }
  9478. if (copy === 0) { break inf_leave; }
  9479. //--- zmemcpy(put, next, copy); ---
  9480. utils.arraySet(output, input, next, copy, put);
  9481. //---//
  9482. have -= copy;
  9483. next += copy;
  9484. left -= copy;
  9485. put += copy;
  9486. state.length -= copy;
  9487. break;
  9488. }
  9489. //Tracev((stderr, "inflate: stored end\n"));
  9490. state.mode = TYPE;
  9491. break;
  9492. case TABLE:
  9493. //=== NEEDBITS(14); */
  9494. while (bits < 14) {
  9495. if (have === 0) { break inf_leave; }
  9496. have--;
  9497. hold += input[next++] << bits;
  9498. bits += 8;
  9499. }
  9500. //===//
  9501. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  9502. //--- DROPBITS(5) ---//
  9503. hold >>>= 5;
  9504. bits -= 5;
  9505. //---//
  9506. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  9507. //--- DROPBITS(5) ---//
  9508. hold >>>= 5;
  9509. bits -= 5;
  9510. //---//
  9511. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  9512. //--- DROPBITS(4) ---//
  9513. hold >>>= 4;
  9514. bits -= 4;
  9515. //---//
  9516. //#ifndef PKZIP_BUG_WORKAROUND
  9517. if (state.nlen > 286 || state.ndist > 30) {
  9518. strm.msg = 'too many length or distance symbols';
  9519. state.mode = BAD;
  9520. break;
  9521. }
  9522. //#endif
  9523. //Tracev((stderr, "inflate: table sizes ok\n"));
  9524. state.have = 0;
  9525. state.mode = LENLENS;
  9526. /* falls through */
  9527. case LENLENS:
  9528. while (state.have < state.ncode) {
  9529. //=== NEEDBITS(3);
  9530. while (bits < 3) {
  9531. if (have === 0) { break inf_leave; }
  9532. have--;
  9533. hold += input[next++] << bits;
  9534. bits += 8;
  9535. }
  9536. //===//
  9537. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  9538. //--- DROPBITS(3) ---//
  9539. hold >>>= 3;
  9540. bits -= 3;
  9541. //---//
  9542. }
  9543. while (state.have < 19) {
  9544. state.lens[order[state.have++]] = 0;
  9545. }
  9546. // We have separate tables & no pointers. 2 commented lines below not needed.
  9547. //state.next = state.codes;
  9548. //state.lencode = state.next;
  9549. // Switch to use dynamic table
  9550. state.lencode = state.lendyn;
  9551. state.lenbits = 7;
  9552. opts = { bits: state.lenbits };
  9553. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  9554. state.lenbits = opts.bits;
  9555. if (ret) {
  9556. strm.msg = 'invalid code lengths set';
  9557. state.mode = BAD;
  9558. break;
  9559. }
  9560. //Tracev((stderr, "inflate: code lengths ok\n"));
  9561. state.have = 0;
  9562. state.mode = CODELENS;
  9563. /* falls through */
  9564. case CODELENS:
  9565. while (state.have < state.nlen + state.ndist) {
  9566. for (;;) {
  9567. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  9568. here_bits = here >>> 24;
  9569. here_op = (here >>> 16) & 0xff;
  9570. here_val = here & 0xffff;
  9571. if ((here_bits) <= bits) { break; }
  9572. //--- PULLBYTE() ---//
  9573. if (have === 0) { break inf_leave; }
  9574. have--;
  9575. hold += input[next++] << bits;
  9576. bits += 8;
  9577. //---//
  9578. }
  9579. if (here_val < 16) {
  9580. //--- DROPBITS(here.bits) ---//
  9581. hold >>>= here_bits;
  9582. bits -= here_bits;
  9583. //---//
  9584. state.lens[state.have++] = here_val;
  9585. }
  9586. else {
  9587. if (here_val === 16) {
  9588. //=== NEEDBITS(here.bits + 2);
  9589. n = here_bits + 2;
  9590. while (bits < n) {
  9591. if (have === 0) { break inf_leave; }
  9592. have--;
  9593. hold += input[next++] << bits;
  9594. bits += 8;
  9595. }
  9596. //===//
  9597. //--- DROPBITS(here.bits) ---//
  9598. hold >>>= here_bits;
  9599. bits -= here_bits;
  9600. //---//
  9601. if (state.have === 0) {
  9602. strm.msg = 'invalid bit length repeat';
  9603. state.mode = BAD;
  9604. break;
  9605. }
  9606. len = state.lens[state.have - 1];
  9607. copy = 3 + (hold & 0x03);//BITS(2);
  9608. //--- DROPBITS(2) ---//
  9609. hold >>>= 2;
  9610. bits -= 2;
  9611. //---//
  9612. }
  9613. else if (here_val === 17) {
  9614. //=== NEEDBITS(here.bits + 3);
  9615. n = here_bits + 3;
  9616. while (bits < n) {
  9617. if (have === 0) { break inf_leave; }
  9618. have--;
  9619. hold += input[next++] << bits;
  9620. bits += 8;
  9621. }
  9622. //===//
  9623. //--- DROPBITS(here.bits) ---//
  9624. hold >>>= here_bits;
  9625. bits -= here_bits;
  9626. //---//
  9627. len = 0;
  9628. copy = 3 + (hold & 0x07);//BITS(3);
  9629. //--- DROPBITS(3) ---//
  9630. hold >>>= 3;
  9631. bits -= 3;
  9632. //---//
  9633. }
  9634. else {
  9635. //=== NEEDBITS(here.bits + 7);
  9636. n = here_bits + 7;
  9637. while (bits < n) {
  9638. if (have === 0) { break inf_leave; }
  9639. have--;
  9640. hold += input[next++] << bits;
  9641. bits += 8;
  9642. }
  9643. //===//
  9644. //--- DROPBITS(here.bits) ---//
  9645. hold >>>= here_bits;
  9646. bits -= here_bits;
  9647. //---//
  9648. len = 0;
  9649. copy = 11 + (hold & 0x7f);//BITS(7);
  9650. //--- DROPBITS(7) ---//
  9651. hold >>>= 7;
  9652. bits -= 7;
  9653. //---//
  9654. }
  9655. if (state.have + copy > state.nlen + state.ndist) {
  9656. strm.msg = 'invalid bit length repeat';
  9657. state.mode = BAD;
  9658. break;
  9659. }
  9660. while (copy--) {
  9661. state.lens[state.have++] = len;
  9662. }
  9663. }
  9664. }
  9665. /* handle error breaks in while */
  9666. if (state.mode === BAD) { break; }
  9667. /* check for end-of-block code (better have one) */
  9668. if (state.lens[256] === 0) {
  9669. strm.msg = 'invalid code -- missing end-of-block';
  9670. state.mode = BAD;
  9671. break;
  9672. }
  9673. /* build code tables -- note: do not change the lenbits or distbits
  9674. values here (9 and 6) without reading the comments in inftrees.h
  9675. concerning the ENOUGH constants, which depend on those values */
  9676. state.lenbits = 9;
  9677. opts = { bits: state.lenbits };
  9678. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  9679. // We have separate tables & no pointers. 2 commented lines below not needed.
  9680. // state.next_index = opts.table_index;
  9681. state.lenbits = opts.bits;
  9682. // state.lencode = state.next;
  9683. if (ret) {
  9684. strm.msg = 'invalid literal/lengths set';
  9685. state.mode = BAD;
  9686. break;
  9687. }
  9688. state.distbits = 6;
  9689. //state.distcode.copy(state.codes);
  9690. // Switch to use dynamic table
  9691. state.distcode = state.distdyn;
  9692. opts = { bits: state.distbits };
  9693. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  9694. // We have separate tables & no pointers. 2 commented lines below not needed.
  9695. // state.next_index = opts.table_index;
  9696. state.distbits = opts.bits;
  9697. // state.distcode = state.next;
  9698. if (ret) {
  9699. strm.msg = 'invalid distances set';
  9700. state.mode = BAD;
  9701. break;
  9702. }
  9703. //Tracev((stderr, 'inflate: codes ok\n'));
  9704. state.mode = LEN_;
  9705. if (flush === Z_TREES) { break inf_leave; }
  9706. /* falls through */
  9707. case LEN_:
  9708. state.mode = LEN;
  9709. /* falls through */
  9710. case LEN:
  9711. if (have >= 6 && left >= 258) {
  9712. //--- RESTORE() ---
  9713. strm.next_out = put;
  9714. strm.avail_out = left;
  9715. strm.next_in = next;
  9716. strm.avail_in = have;
  9717. state.hold = hold;
  9718. state.bits = bits;
  9719. //---
  9720. inflate_fast(strm, _out);
  9721. //--- LOAD() ---
  9722. put = strm.next_out;
  9723. output = strm.output;
  9724. left = strm.avail_out;
  9725. next = strm.next_in;
  9726. input = strm.input;
  9727. have = strm.avail_in;
  9728. hold = state.hold;
  9729. bits = state.bits;
  9730. //---
  9731. if (state.mode === TYPE) {
  9732. state.back = -1;
  9733. }
  9734. break;
  9735. }
  9736. state.back = 0;
  9737. for (;;) {
  9738. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  9739. here_bits = here >>> 24;
  9740. here_op = (here >>> 16) & 0xff;
  9741. here_val = here & 0xffff;
  9742. if (here_bits <= bits) { break; }
  9743. //--- PULLBYTE() ---//
  9744. if (have === 0) { break inf_leave; }
  9745. have--;
  9746. hold += input[next++] << bits;
  9747. bits += 8;
  9748. //---//
  9749. }
  9750. if (here_op && (here_op & 0xf0) === 0) {
  9751. last_bits = here_bits;
  9752. last_op = here_op;
  9753. last_val = here_val;
  9754. for (;;) {
  9755. here = state.lencode[last_val +
  9756. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9757. here_bits = here >>> 24;
  9758. here_op = (here >>> 16) & 0xff;
  9759. here_val = here & 0xffff;
  9760. if ((last_bits + here_bits) <= bits) { break; }
  9761. //--- PULLBYTE() ---//
  9762. if (have === 0) { break inf_leave; }
  9763. have--;
  9764. hold += input[next++] << bits;
  9765. bits += 8;
  9766. //---//
  9767. }
  9768. //--- DROPBITS(last.bits) ---//
  9769. hold >>>= last_bits;
  9770. bits -= last_bits;
  9771. //---//
  9772. state.back += last_bits;
  9773. }
  9774. //--- DROPBITS(here.bits) ---//
  9775. hold >>>= here_bits;
  9776. bits -= here_bits;
  9777. //---//
  9778. state.back += here_bits;
  9779. state.length = here_val;
  9780. if (here_op === 0) {
  9781. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  9782. // "inflate: literal '%c'\n" :
  9783. // "inflate: literal 0x%02x\n", here.val));
  9784. state.mode = LIT;
  9785. break;
  9786. }
  9787. if (here_op & 32) {
  9788. //Tracevv((stderr, "inflate: end of block\n"));
  9789. state.back = -1;
  9790. state.mode = TYPE;
  9791. break;
  9792. }
  9793. if (here_op & 64) {
  9794. strm.msg = 'invalid literal/length code';
  9795. state.mode = BAD;
  9796. break;
  9797. }
  9798. state.extra = here_op & 15;
  9799. state.mode = LENEXT;
  9800. /* falls through */
  9801. case LENEXT:
  9802. if (state.extra) {
  9803. //=== NEEDBITS(state.extra);
  9804. n = state.extra;
  9805. while (bits < n) {
  9806. if (have === 0) { break inf_leave; }
  9807. have--;
  9808. hold += input[next++] << bits;
  9809. bits += 8;
  9810. }
  9811. //===//
  9812. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9813. //--- DROPBITS(state.extra) ---//
  9814. hold >>>= state.extra;
  9815. bits -= state.extra;
  9816. //---//
  9817. state.back += state.extra;
  9818. }
  9819. //Tracevv((stderr, "inflate: length %u\n", state.length));
  9820. state.was = state.length;
  9821. state.mode = DIST;
  9822. /* falls through */
  9823. case DIST:
  9824. for (;;) {
  9825. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  9826. here_bits = here >>> 24;
  9827. here_op = (here >>> 16) & 0xff;
  9828. here_val = here & 0xffff;
  9829. if ((here_bits) <= bits) { break; }
  9830. //--- PULLBYTE() ---//
  9831. if (have === 0) { break inf_leave; }
  9832. have--;
  9833. hold += input[next++] << bits;
  9834. bits += 8;
  9835. //---//
  9836. }
  9837. if ((here_op & 0xf0) === 0) {
  9838. last_bits = here_bits;
  9839. last_op = here_op;
  9840. last_val = here_val;
  9841. for (;;) {
  9842. here = state.distcode[last_val +
  9843. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9844. here_bits = here >>> 24;
  9845. here_op = (here >>> 16) & 0xff;
  9846. here_val = here & 0xffff;
  9847. if ((last_bits + here_bits) <= bits) { break; }
  9848. //--- PULLBYTE() ---//
  9849. if (have === 0) { break inf_leave; }
  9850. have--;
  9851. hold += input[next++] << bits;
  9852. bits += 8;
  9853. //---//
  9854. }
  9855. //--- DROPBITS(last.bits) ---//
  9856. hold >>>= last_bits;
  9857. bits -= last_bits;
  9858. //---//
  9859. state.back += last_bits;
  9860. }
  9861. //--- DROPBITS(here.bits) ---//
  9862. hold >>>= here_bits;
  9863. bits -= here_bits;
  9864. //---//
  9865. state.back += here_bits;
  9866. if (here_op & 64) {
  9867. strm.msg = 'invalid distance code';
  9868. state.mode = BAD;
  9869. break;
  9870. }
  9871. state.offset = here_val;
  9872. state.extra = (here_op) & 15;
  9873. state.mode = DISTEXT;
  9874. /* falls through */
  9875. case DISTEXT:
  9876. if (state.extra) {
  9877. //=== NEEDBITS(state.extra);
  9878. n = state.extra;
  9879. while (bits < n) {
  9880. if (have === 0) { break inf_leave; }
  9881. have--;
  9882. hold += input[next++] << bits;
  9883. bits += 8;
  9884. }
  9885. //===//
  9886. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9887. //--- DROPBITS(state.extra) ---//
  9888. hold >>>= state.extra;
  9889. bits -= state.extra;
  9890. //---//
  9891. state.back += state.extra;
  9892. }
  9893. //#ifdef INFLATE_STRICT
  9894. if (state.offset > state.dmax) {
  9895. strm.msg = 'invalid distance too far back';
  9896. state.mode = BAD;
  9897. break;
  9898. }
  9899. //#endif
  9900. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  9901. state.mode = MATCH;
  9902. /* falls through */
  9903. case MATCH:
  9904. if (left === 0) { break inf_leave; }
  9905. copy = _out - left;
  9906. if (state.offset > copy) { /* copy from window */
  9907. copy = state.offset - copy;
  9908. if (copy > state.whave) {
  9909. if (state.sane) {
  9910. strm.msg = 'invalid distance too far back';
  9911. state.mode = BAD;
  9912. break;
  9913. }
  9914. // (!) This block is disabled in zlib defailts,
  9915. // don't enable it for binary compatibility
  9916. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9917. // Trace((stderr, "inflate.c too far\n"));
  9918. // copy -= state.whave;
  9919. // if (copy > state.length) { copy = state.length; }
  9920. // if (copy > left) { copy = left; }
  9921. // left -= copy;
  9922. // state.length -= copy;
  9923. // do {
  9924. // output[put++] = 0;
  9925. // } while (--copy);
  9926. // if (state.length === 0) { state.mode = LEN; }
  9927. // break;
  9928. //#endif
  9929. }
  9930. if (copy > state.wnext) {
  9931. copy -= state.wnext;
  9932. from = state.wsize - copy;
  9933. }
  9934. else {
  9935. from = state.wnext - copy;
  9936. }
  9937. if (copy > state.length) { copy = state.length; }
  9938. from_source = state.window;
  9939. }
  9940. else { /* copy from output */
  9941. from_source = output;
  9942. from = put - state.offset;
  9943. copy = state.length;
  9944. }
  9945. if (copy > left) { copy = left; }
  9946. left -= copy;
  9947. state.length -= copy;
  9948. do {
  9949. output[put++] = from_source[from++];
  9950. } while (--copy);
  9951. if (state.length === 0) { state.mode = LEN; }
  9952. break;
  9953. case LIT:
  9954. if (left === 0) { break inf_leave; }
  9955. output[put++] = state.length;
  9956. left--;
  9957. state.mode = LEN;
  9958. break;
  9959. case CHECK:
  9960. if (state.wrap) {
  9961. //=== NEEDBITS(32);
  9962. while (bits < 32) {
  9963. if (have === 0) { break inf_leave; }
  9964. have--;
  9965. // Use '|' insdead of '+' to make sure that result is signed
  9966. hold |= input[next++] << bits;
  9967. bits += 8;
  9968. }
  9969. //===//
  9970. _out -= left;
  9971. strm.total_out += _out;
  9972. state.total += _out;
  9973. if (_out) {
  9974. strm.adler = state.check =
  9975. /*UPDATE(state.check, put - _out, _out);*/
  9976. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  9977. }
  9978. _out = left;
  9979. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  9980. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  9981. strm.msg = 'incorrect data check';
  9982. state.mode = BAD;
  9983. break;
  9984. }
  9985. //=== INITBITS();
  9986. hold = 0;
  9987. bits = 0;
  9988. //===//
  9989. //Tracev((stderr, "inflate: check matches trailer\n"));
  9990. }
  9991. state.mode = LENGTH;
  9992. /* falls through */
  9993. case LENGTH:
  9994. if (state.wrap && state.flags) {
  9995. //=== NEEDBITS(32);
  9996. while (bits < 32) {
  9997. if (have === 0) { break inf_leave; }
  9998. have--;
  9999. hold += input[next++] << bits;
  10000. bits += 8;
  10001. }
  10002. //===//
  10003. if (hold !== (state.total & 0xffffffff)) {
  10004. strm.msg = 'incorrect length check';
  10005. state.mode = BAD;
  10006. break;
  10007. }
  10008. //=== INITBITS();
  10009. hold = 0;
  10010. bits = 0;
  10011. //===//
  10012. //Tracev((stderr, "inflate: length matches trailer\n"));
  10013. }
  10014. state.mode = DONE;
  10015. /* falls through */
  10016. case DONE:
  10017. ret = Z_STREAM_END;
  10018. break inf_leave;
  10019. case BAD:
  10020. ret = Z_DATA_ERROR;
  10021. break inf_leave;
  10022. case MEM:
  10023. return Z_MEM_ERROR;
  10024. case SYNC:
  10025. /* falls through */
  10026. default:
  10027. return Z_STREAM_ERROR;
  10028. }
  10029. }
  10030. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  10031. /*
  10032. Return from inflate(), updating the total counts and the check value.
  10033. If there was no progress during the inflate() call, return a buffer
  10034. error. Call updatewindow() to create and/or update the window state.
  10035. Note: a memory error from inflate() is non-recoverable.
  10036. */
  10037. //--- RESTORE() ---
  10038. strm.next_out = put;
  10039. strm.avail_out = left;
  10040. strm.next_in = next;
  10041. strm.avail_in = have;
  10042. state.hold = hold;
  10043. state.bits = bits;
  10044. //---
  10045. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  10046. (state.mode < CHECK || flush !== Z_FINISH))) {
  10047. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  10048. state.mode = MEM;
  10049. return Z_MEM_ERROR;
  10050. }
  10051. }
  10052. _in -= strm.avail_in;
  10053. _out -= strm.avail_out;
  10054. strm.total_in += _in;
  10055. strm.total_out += _out;
  10056. state.total += _out;
  10057. if (state.wrap && _out) {
  10058. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  10059. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  10060. }
  10061. strm.data_type = state.bits + (state.last ? 64 : 0) +
  10062. (state.mode === TYPE ? 128 : 0) +
  10063. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  10064. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  10065. ret = Z_BUF_ERROR;
  10066. }
  10067. return ret;
  10068. }
  10069. function inflateEnd(strm) {
  10070. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  10071. return Z_STREAM_ERROR;
  10072. }
  10073. var state = strm.state;
  10074. if (state.window) {
  10075. state.window = null;
  10076. }
  10077. strm.state = null;
  10078. return Z_OK;
  10079. }
  10080. function inflateGetHeader(strm, head) {
  10081. var state;
  10082. /* check state */
  10083. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  10084. state = strm.state;
  10085. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  10086. /* save header structure */
  10087. state.head = head;
  10088. head.done = false;
  10089. return Z_OK;
  10090. }
  10091. function inflateSetDictionary(strm, dictionary) {
  10092. var dictLength = dictionary.length;
  10093. var state;
  10094. var dictid;
  10095. var ret;
  10096. /* check state */
  10097. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  10098. state = strm.state;
  10099. if (state.wrap !== 0 && state.mode !== DICT) {
  10100. return Z_STREAM_ERROR;
  10101. }
  10102. /* check for correct dictionary identifier */
  10103. if (state.mode === DICT) {
  10104. dictid = 1; /* adler32(0, null, 0)*/
  10105. /* dictid = adler32(dictid, dictionary, dictLength); */
  10106. dictid = adler32(dictid, dictionary, dictLength, 0);
  10107. if (dictid !== state.check) {
  10108. return Z_DATA_ERROR;
  10109. }
  10110. }
  10111. /* copy dictionary to window using updatewindow(), which will amend the
  10112. existing dictionary if appropriate */
  10113. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  10114. if (ret) {
  10115. state.mode = MEM;
  10116. return Z_MEM_ERROR;
  10117. }
  10118. state.havedict = 1;
  10119. // Tracev((stderr, "inflate: dictionary set\n"));
  10120. return Z_OK;
  10121. }
  10122. exports.inflateReset = inflateReset;
  10123. exports.inflateReset2 = inflateReset2;
  10124. exports.inflateResetKeep = inflateResetKeep;
  10125. exports.inflateInit = inflateInit;
  10126. exports.inflateInit2 = inflateInit2;
  10127. exports.inflate = inflate;
  10128. exports.inflateEnd = inflateEnd;
  10129. exports.inflateGetHeader = inflateGetHeader;
  10130. exports.inflateSetDictionary = inflateSetDictionary;
  10131. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  10132. /* Not implemented
  10133. exports.inflateCopy = inflateCopy;
  10134. exports.inflateGetDictionary = inflateGetDictionary;
  10135. exports.inflateMark = inflateMark;
  10136. exports.inflatePrime = inflatePrime;
  10137. exports.inflateSync = inflateSync;
  10138. exports.inflateSyncPoint = inflateSyncPoint;
  10139. exports.inflateUndermine = inflateUndermine;
  10140. */
  10141. },{"../utils/common":32,"./adler32":34,"./crc32":36,"./inffast":39,"./inftrees":41}],41:[function(_dereq_,module,exports){
  10142. 'use strict';
  10143. var utils = _dereq_('../utils/common');
  10144. var MAXBITS = 15;
  10145. var ENOUGH_LENS = 852;
  10146. var ENOUGH_DISTS = 592;
  10147. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  10148. var CODES = 0;
  10149. var LENS = 1;
  10150. var DISTS = 2;
  10151. var lbase = [ /* Length codes 257..285 base */
  10152. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  10153. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  10154. ];
  10155. var lext = [ /* Length codes 257..285 extra */
  10156. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  10157. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  10158. ];
  10159. var dbase = [ /* Distance codes 0..29 base */
  10160. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  10161. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  10162. 8193, 12289, 16385, 24577, 0, 0
  10163. ];
  10164. var dext = [ /* Distance codes 0..29 extra */
  10165. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  10166. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  10167. 28, 28, 29, 29, 64, 64
  10168. ];
  10169. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  10170. {
  10171. var bits = opts.bits;
  10172. //here = opts.here; /* table entry for duplication */
  10173. var len = 0; /* a code's length in bits */
  10174. var sym = 0; /* index of code symbols */
  10175. var min = 0, max = 0; /* minimum and maximum code lengths */
  10176. var root = 0; /* number of index bits for root table */
  10177. var curr = 0; /* number of index bits for current table */
  10178. var drop = 0; /* code bits to drop for sub-table */
  10179. var left = 0; /* number of prefix codes available */
  10180. var used = 0; /* code entries in table used */
  10181. var huff = 0; /* Huffman code */
  10182. var incr; /* for incrementing code, index */
  10183. var fill; /* index for replicating entries */
  10184. var low; /* low bits for current root entry */
  10185. var mask; /* mask for low root bits */
  10186. var next; /* next available space in table */
  10187. var base = null; /* base value table to use */
  10188. var base_index = 0;
  10189. // var shoextra; /* extra bits table to use */
  10190. var end; /* use base and extra for symbol > end */
  10191. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  10192. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  10193. var extra = null;
  10194. var extra_index = 0;
  10195. var here_bits, here_op, here_val;
  10196. /*
  10197. Process a set of code lengths to create a canonical Huffman code. The
  10198. code lengths are lens[0..codes-1]. Each length corresponds to the
  10199. symbols 0..codes-1. The Huffman code is generated by first sorting the
  10200. symbols by length from short to long, and retaining the symbol order
  10201. for codes with equal lengths. Then the code starts with all zero bits
  10202. for the first code of the shortest length, and the codes are integer
  10203. increments for the same length, and zeros are appended as the length
  10204. increases. For the deflate format, these bits are stored backwards
  10205. from their more natural integer increment ordering, and so when the
  10206. decoding tables are built in the large loop below, the integer codes
  10207. are incremented backwards.
  10208. This routine assumes, but does not check, that all of the entries in
  10209. lens[] are in the range 0..MAXBITS. The caller must assure this.
  10210. 1..MAXBITS is interpreted as that code length. zero means that that
  10211. symbol does not occur in this code.
  10212. The codes are sorted by computing a count of codes for each length,
  10213. creating from that a table of starting indices for each length in the
  10214. sorted table, and then entering the symbols in order in the sorted
  10215. table. The sorted table is work[], with that space being provided by
  10216. the caller.
  10217. The length counts are used for other purposes as well, i.e. finding
  10218. the minimum and maximum length codes, determining if there are any
  10219. codes at all, checking for a valid set of lengths, and looking ahead
  10220. at length counts to determine sub-table sizes when building the
  10221. decoding tables.
  10222. */
  10223. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  10224. for (len = 0; len <= MAXBITS; len++) {
  10225. count[len] = 0;
  10226. }
  10227. for (sym = 0; sym < codes; sym++) {
  10228. count[lens[lens_index + sym]]++;
  10229. }
  10230. /* bound code lengths, force root to be within code lengths */
  10231. root = bits;
  10232. for (max = MAXBITS; max >= 1; max--) {
  10233. if (count[max] !== 0) { break; }
  10234. }
  10235. if (root > max) {
  10236. root = max;
  10237. }
  10238. if (max === 0) { /* no symbols to code at all */
  10239. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  10240. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  10241. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  10242. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  10243. //table.op[opts.table_index] = 64;
  10244. //table.bits[opts.table_index] = 1;
  10245. //table.val[opts.table_index++] = 0;
  10246. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  10247. opts.bits = 1;
  10248. return 0; /* no symbols, but wait for decoding to report error */
  10249. }
  10250. for (min = 1; min < max; min++) {
  10251. if (count[min] !== 0) { break; }
  10252. }
  10253. if (root < min) {
  10254. root = min;
  10255. }
  10256. /* check for an over-subscribed or incomplete set of lengths */
  10257. left = 1;
  10258. for (len = 1; len <= MAXBITS; len++) {
  10259. left <<= 1;
  10260. left -= count[len];
  10261. if (left < 0) {
  10262. return -1;
  10263. } /* over-subscribed */
  10264. }
  10265. if (left > 0 && (type === CODES || max !== 1)) {
  10266. return -1; /* incomplete set */
  10267. }
  10268. /* generate offsets into symbol table for each length for sorting */
  10269. offs[1] = 0;
  10270. for (len = 1; len < MAXBITS; len++) {
  10271. offs[len + 1] = offs[len] + count[len];
  10272. }
  10273. /* sort symbols by length, by symbol order within each length */
  10274. for (sym = 0; sym < codes; sym++) {
  10275. if (lens[lens_index + sym] !== 0) {
  10276. work[offs[lens[lens_index + sym]]++] = sym;
  10277. }
  10278. }
  10279. /*
  10280. Create and fill in decoding tables. In this loop, the table being
  10281. filled is at next and has curr index bits. The code being used is huff
  10282. with length len. That code is converted to an index by dropping drop
  10283. bits off of the bottom. For codes where len is less than drop + curr,
  10284. those top drop + curr - len bits are incremented through all values to
  10285. fill the table with replicated entries.
  10286. root is the number of index bits for the root table. When len exceeds
  10287. root, sub-tables are created pointed to by the root entry with an index
  10288. of the low root bits of huff. This is saved in low to check for when a
  10289. new sub-table should be started. drop is zero when the root table is
  10290. being filled, and drop is root when sub-tables are being filled.
  10291. When a new sub-table is needed, it is necessary to look ahead in the
  10292. code lengths to determine what size sub-table is needed. The length
  10293. counts are used for this, and so count[] is decremented as codes are
  10294. entered in the tables.
  10295. used keeps track of how many table entries have been allocated from the
  10296. provided *table space. It is checked for LENS and DIST tables against
  10297. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  10298. the initial root table size constants. See the comments in inftrees.h
  10299. for more information.
  10300. sym increments through all symbols, and the loop terminates when
  10301. all codes of length max, i.e. all codes, have been processed. This
  10302. routine permits incomplete codes, so another loop after this one fills
  10303. in the rest of the decoding tables with invalid code markers.
  10304. */
  10305. /* set up for code type */
  10306. // poor man optimization - use if-else instead of switch,
  10307. // to avoid deopts in old v8
  10308. if (type === CODES) {
  10309. base = extra = work; /* dummy value--not used */
  10310. end = 19;
  10311. } else if (type === LENS) {
  10312. base = lbase;
  10313. base_index -= 257;
  10314. extra = lext;
  10315. extra_index -= 257;
  10316. end = 256;
  10317. } else { /* DISTS */
  10318. base = dbase;
  10319. extra = dext;
  10320. end = -1;
  10321. }
  10322. /* initialize opts for loop */
  10323. huff = 0; /* starting code */
  10324. sym = 0; /* starting code symbol */
  10325. len = min; /* starting code length */
  10326. next = table_index; /* current table to fill in */
  10327. curr = root; /* current table index bits */
  10328. drop = 0; /* current bits to drop from code for index */
  10329. low = -1; /* trigger new sub-table when len > root */
  10330. used = 1 << root; /* use root table entries */
  10331. mask = used - 1; /* mask for comparing low */
  10332. /* check available table space */
  10333. if ((type === LENS && used > ENOUGH_LENS) ||
  10334. (type === DISTS && used > ENOUGH_DISTS)) {
  10335. return 1;
  10336. }
  10337. var i = 0;
  10338. /* process all codes and make table entries */
  10339. for (;;) {
  10340. i++;
  10341. /* create table entry */
  10342. here_bits = len - drop;
  10343. if (work[sym] < end) {
  10344. here_op = 0;
  10345. here_val = work[sym];
  10346. }
  10347. else if (work[sym] > end) {
  10348. here_op = extra[extra_index + work[sym]];
  10349. here_val = base[base_index + work[sym]];
  10350. }
  10351. else {
  10352. here_op = 32 + 64; /* end of block */
  10353. here_val = 0;
  10354. }
  10355. /* replicate for those indices with low len bits equal to huff */
  10356. incr = 1 << (len - drop);
  10357. fill = 1 << curr;
  10358. min = fill; /* save offset to next table */
  10359. do {
  10360. fill -= incr;
  10361. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  10362. } while (fill !== 0);
  10363. /* backwards increment the len-bit code huff */
  10364. incr = 1 << (len - 1);
  10365. while (huff & incr) {
  10366. incr >>= 1;
  10367. }
  10368. if (incr !== 0) {
  10369. huff &= incr - 1;
  10370. huff += incr;
  10371. } else {
  10372. huff = 0;
  10373. }
  10374. /* go to next symbol, update count, len */
  10375. sym++;
  10376. if (--count[len] === 0) {
  10377. if (len === max) { break; }
  10378. len = lens[lens_index + work[sym]];
  10379. }
  10380. /* create new sub-table if needed */
  10381. if (len > root && (huff & mask) !== low) {
  10382. /* if first time, transition to sub-tables */
  10383. if (drop === 0) {
  10384. drop = root;
  10385. }
  10386. /* increment past last table */
  10387. next += min; /* here min is 1 << curr */
  10388. /* determine length of next table */
  10389. curr = len - drop;
  10390. left = 1 << curr;
  10391. while (curr + drop < max) {
  10392. left -= count[curr + drop];
  10393. if (left <= 0) { break; }
  10394. curr++;
  10395. left <<= 1;
  10396. }
  10397. /* check for enough space */
  10398. used += 1 << curr;
  10399. if ((type === LENS && used > ENOUGH_LENS) ||
  10400. (type === DISTS && used > ENOUGH_DISTS)) {
  10401. return 1;
  10402. }
  10403. /* point entry in root table to sub-table */
  10404. low = huff & mask;
  10405. /*table.op[low] = curr;
  10406. table.bits[low] = root;
  10407. table.val[low] = next - opts.table_index;*/
  10408. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  10409. }
  10410. }
  10411. /* fill in remaining table entry if code is incomplete (guaranteed to have
  10412. at most one remaining entry, since if the code is incomplete, the
  10413. maximum code length that was allowed to get this far is one bit) */
  10414. if (huff !== 0) {
  10415. //table.op[next + huff] = 64; /* invalid code marker */
  10416. //table.bits[next + huff] = len - drop;
  10417. //table.val[next + huff] = 0;
  10418. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  10419. }
  10420. /* set return parameters */
  10421. //opts.table_index += used;
  10422. opts.bits = root;
  10423. return 0;
  10424. };
  10425. },{"../utils/common":32}],42:[function(_dereq_,module,exports){
  10426. 'use strict';
  10427. module.exports = {
  10428. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  10429. 1: 'stream end', /* Z_STREAM_END 1 */
  10430. 0: '', /* Z_OK 0 */
  10431. '-1': 'file error', /* Z_ERRNO (-1) */
  10432. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  10433. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  10434. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  10435. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  10436. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  10437. };
  10438. },{}],43:[function(_dereq_,module,exports){
  10439. 'use strict';
  10440. var utils = _dereq_('../utils/common');
  10441. /* Public constants ==========================================================*/
  10442. /* ===========================================================================*/
  10443. //var Z_FILTERED = 1;
  10444. //var Z_HUFFMAN_ONLY = 2;
  10445. //var Z_RLE = 3;
  10446. var Z_FIXED = 4;
  10447. //var Z_DEFAULT_STRATEGY = 0;
  10448. /* Possible values of the data_type field (though see inflate()) */
  10449. var Z_BINARY = 0;
  10450. var Z_TEXT = 1;
  10451. //var Z_ASCII = 1; // = Z_TEXT
  10452. var Z_UNKNOWN = 2;
  10453. /*============================================================================*/
  10454. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  10455. // From zutil.h
  10456. var STORED_BLOCK = 0;
  10457. var STATIC_TREES = 1;
  10458. var DYN_TREES = 2;
  10459. /* The three kinds of block type */
  10460. var MIN_MATCH = 3;
  10461. var MAX_MATCH = 258;
  10462. /* The minimum and maximum match lengths */
  10463. // From deflate.h
  10464. /* ===========================================================================
  10465. * Internal compression state.
  10466. */
  10467. var LENGTH_CODES = 29;
  10468. /* number of length codes, not counting the special END_BLOCK code */
  10469. var LITERALS = 256;
  10470. /* number of literal bytes 0..255 */
  10471. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  10472. /* number of Literal or Length codes, including the END_BLOCK code */
  10473. var D_CODES = 30;
  10474. /* number of distance codes */
  10475. var BL_CODES = 19;
  10476. /* number of codes used to transfer the bit lengths */
  10477. var HEAP_SIZE = 2 * L_CODES + 1;
  10478. /* maximum heap size */
  10479. var MAX_BITS = 15;
  10480. /* All codes must not exceed MAX_BITS bits */
  10481. var Buf_size = 16;
  10482. /* size of bit buffer in bi_buf */
  10483. /* ===========================================================================
  10484. * Constants
  10485. */
  10486. var MAX_BL_BITS = 7;
  10487. /* Bit length codes must not exceed MAX_BL_BITS bits */
  10488. var END_BLOCK = 256;
  10489. /* end of block literal code */
  10490. var REP_3_6 = 16;
  10491. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  10492. var REPZ_3_10 = 17;
  10493. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  10494. var REPZ_11_138 = 18;
  10495. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  10496. /* eslint-disable comma-spacing,array-bracket-spacing */
  10497. var extra_lbits = /* extra bits for each length code */
  10498. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  10499. var extra_dbits = /* extra bits for each distance code */
  10500. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  10501. var extra_blbits = /* extra bits for each bit length code */
  10502. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  10503. var bl_order =
  10504. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  10505. /* eslint-enable comma-spacing,array-bracket-spacing */
  10506. /* The lengths of the bit length codes are sent in order of decreasing
  10507. * probability, to avoid transmitting the lengths for unused bit length codes.
  10508. */
  10509. /* ===========================================================================
  10510. * Local data. These are initialized only once.
  10511. */
  10512. // We pre-fill arrays with 0 to avoid uninitialized gaps
  10513. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  10514. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  10515. var static_ltree = new Array((L_CODES + 2) * 2);
  10516. zero(static_ltree);
  10517. /* The static literal tree. Since the bit lengths are imposed, there is no
  10518. * need for the L_CODES extra codes used during heap construction. However
  10519. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  10520. * below).
  10521. */
  10522. var static_dtree = new Array(D_CODES * 2);
  10523. zero(static_dtree);
  10524. /* The static distance tree. (Actually a trivial tree since all codes use
  10525. * 5 bits.)
  10526. */
  10527. var _dist_code = new Array(DIST_CODE_LEN);
  10528. zero(_dist_code);
  10529. /* Distance codes. The first 256 values correspond to the distances
  10530. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  10531. * the 15 bit distances.
  10532. */
  10533. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  10534. zero(_length_code);
  10535. /* length code for each normalized match length (0 == MIN_MATCH) */
  10536. var base_length = new Array(LENGTH_CODES);
  10537. zero(base_length);
  10538. /* First normalized length for each code (0 = MIN_MATCH) */
  10539. var base_dist = new Array(D_CODES);
  10540. zero(base_dist);
  10541. /* First normalized distance for each code (0 = distance of 1) */
  10542. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  10543. this.static_tree = static_tree; /* static tree or NULL */
  10544. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  10545. this.extra_base = extra_base; /* base index for extra_bits */
  10546. this.elems = elems; /* max number of elements in the tree */
  10547. this.max_length = max_length; /* max bit length for the codes */
  10548. // show if `static_tree` has data or dummy - needed for monomorphic objects
  10549. this.has_stree = static_tree && static_tree.length;
  10550. }
  10551. var static_l_desc;
  10552. var static_d_desc;
  10553. var static_bl_desc;
  10554. function TreeDesc(dyn_tree, stat_desc) {
  10555. this.dyn_tree = dyn_tree; /* the dynamic tree */
  10556. this.max_code = 0; /* largest code with non zero frequency */
  10557. this.stat_desc = stat_desc; /* the corresponding static tree */
  10558. }
  10559. function d_code(dist) {
  10560. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  10561. }
  10562. /* ===========================================================================
  10563. * Output a short LSB first on the stream.
  10564. * IN assertion: there is enough room in pendingBuf.
  10565. */
  10566. function put_short(s, w) {
  10567. // put_byte(s, (uch)((w) & 0xff));
  10568. // put_byte(s, (uch)((ush)(w) >> 8));
  10569. s.pending_buf[s.pending++] = (w) & 0xff;
  10570. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  10571. }
  10572. /* ===========================================================================
  10573. * Send a value on a given number of bits.
  10574. * IN assertion: length <= 16 and value fits in length bits.
  10575. */
  10576. function send_bits(s, value, length) {
  10577. if (s.bi_valid > (Buf_size - length)) {
  10578. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10579. put_short(s, s.bi_buf);
  10580. s.bi_buf = value >> (Buf_size - s.bi_valid);
  10581. s.bi_valid += length - Buf_size;
  10582. } else {
  10583. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10584. s.bi_valid += length;
  10585. }
  10586. }
  10587. function send_code(s, c, tree) {
  10588. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  10589. }
  10590. /* ===========================================================================
  10591. * Reverse the first len bits of a code, using straightforward code (a faster
  10592. * method would use a table)
  10593. * IN assertion: 1 <= len <= 15
  10594. */
  10595. function bi_reverse(code, len) {
  10596. var res = 0;
  10597. do {
  10598. res |= code & 1;
  10599. code >>>= 1;
  10600. res <<= 1;
  10601. } while (--len > 0);
  10602. return res >>> 1;
  10603. }
  10604. /* ===========================================================================
  10605. * Flush the bit buffer, keeping at most 7 bits in it.
  10606. */
  10607. function bi_flush(s) {
  10608. if (s.bi_valid === 16) {
  10609. put_short(s, s.bi_buf);
  10610. s.bi_buf = 0;
  10611. s.bi_valid = 0;
  10612. } else if (s.bi_valid >= 8) {
  10613. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  10614. s.bi_buf >>= 8;
  10615. s.bi_valid -= 8;
  10616. }
  10617. }
  10618. /* ===========================================================================
  10619. * Compute the optimal bit lengths for a tree and update the total bit length
  10620. * for the current block.
  10621. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  10622. * above are the tree nodes sorted by increasing frequency.
  10623. * OUT assertions: the field len is set to the optimal bit length, the
  10624. * array bl_count contains the frequencies for each bit length.
  10625. * The length opt_len is updated; static_len is also updated if stree is
  10626. * not null.
  10627. */
  10628. function gen_bitlen(s, desc)
  10629. // deflate_state *s;
  10630. // tree_desc *desc; /* the tree descriptor */
  10631. {
  10632. var tree = desc.dyn_tree;
  10633. var max_code = desc.max_code;
  10634. var stree = desc.stat_desc.static_tree;
  10635. var has_stree = desc.stat_desc.has_stree;
  10636. var extra = desc.stat_desc.extra_bits;
  10637. var base = desc.stat_desc.extra_base;
  10638. var max_length = desc.stat_desc.max_length;
  10639. var h; /* heap index */
  10640. var n, m; /* iterate over the tree elements */
  10641. var bits; /* bit length */
  10642. var xbits; /* extra bits */
  10643. var f; /* frequency */
  10644. var overflow = 0; /* number of elements with bit length too large */
  10645. for (bits = 0; bits <= MAX_BITS; bits++) {
  10646. s.bl_count[bits] = 0;
  10647. }
  10648. /* In a first pass, compute the optimal bit lengths (which may
  10649. * overflow in the case of the bit length tree).
  10650. */
  10651. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  10652. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  10653. n = s.heap[h];
  10654. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  10655. if (bits > max_length) {
  10656. bits = max_length;
  10657. overflow++;
  10658. }
  10659. tree[n * 2 + 1]/*.Len*/ = bits;
  10660. /* We overwrite tree[n].Dad which is no longer needed */
  10661. if (n > max_code) { continue; } /* not a leaf node */
  10662. s.bl_count[bits]++;
  10663. xbits = 0;
  10664. if (n >= base) {
  10665. xbits = extra[n - base];
  10666. }
  10667. f = tree[n * 2]/*.Freq*/;
  10668. s.opt_len += f * (bits + xbits);
  10669. if (has_stree) {
  10670. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  10671. }
  10672. }
  10673. if (overflow === 0) { return; }
  10674. // Trace((stderr,"\nbit length overflow\n"));
  10675. /* This happens for example on obj2 and pic of the Calgary corpus */
  10676. /* Find the first bit length which could increase: */
  10677. do {
  10678. bits = max_length - 1;
  10679. while (s.bl_count[bits] === 0) { bits--; }
  10680. s.bl_count[bits]--; /* move one leaf down the tree */
  10681. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  10682. s.bl_count[max_length]--;
  10683. /* The brother of the overflow item also moves one step up,
  10684. * but this does not affect bl_count[max_length]
  10685. */
  10686. overflow -= 2;
  10687. } while (overflow > 0);
  10688. /* Now recompute all bit lengths, scanning in increasing frequency.
  10689. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  10690. * lengths instead of fixing only the wrong ones. This idea is taken
  10691. * from 'ar' written by Haruhiko Okumura.)
  10692. */
  10693. for (bits = max_length; bits !== 0; bits--) {
  10694. n = s.bl_count[bits];
  10695. while (n !== 0) {
  10696. m = s.heap[--h];
  10697. if (m > max_code) { continue; }
  10698. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  10699. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  10700. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  10701. tree[m * 2 + 1]/*.Len*/ = bits;
  10702. }
  10703. n--;
  10704. }
  10705. }
  10706. }
  10707. /* ===========================================================================
  10708. * Generate the codes for a given tree and bit counts (which need not be
  10709. * optimal).
  10710. * IN assertion: the array bl_count contains the bit length statistics for
  10711. * the given tree and the field len is set for all tree elements.
  10712. * OUT assertion: the field code is set for all tree elements of non
  10713. * zero code length.
  10714. */
  10715. function gen_codes(tree, max_code, bl_count)
  10716. // ct_data *tree; /* the tree to decorate */
  10717. // int max_code; /* largest code with non zero frequency */
  10718. // ushf *bl_count; /* number of codes at each bit length */
  10719. {
  10720. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  10721. var code = 0; /* running code value */
  10722. var bits; /* bit index */
  10723. var n; /* code index */
  10724. /* The distribution counts are first used to generate the code values
  10725. * without bit reversal.
  10726. */
  10727. for (bits = 1; bits <= MAX_BITS; bits++) {
  10728. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  10729. }
  10730. /* Check that the bit counts in bl_count are consistent. The last code
  10731. * must be all ones.
  10732. */
  10733. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  10734. // "inconsistent bit counts");
  10735. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  10736. for (n = 0; n <= max_code; n++) {
  10737. var len = tree[n * 2 + 1]/*.Len*/;
  10738. if (len === 0) { continue; }
  10739. /* Now reverse the bits */
  10740. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  10741. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  10742. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  10743. }
  10744. }
  10745. /* ===========================================================================
  10746. * Initialize the various 'constant' tables.
  10747. */
  10748. function tr_static_init() {
  10749. var n; /* iterates over tree elements */
  10750. var bits; /* bit counter */
  10751. var length; /* length value */
  10752. var code; /* code value */
  10753. var dist; /* distance index */
  10754. var bl_count = new Array(MAX_BITS + 1);
  10755. /* number of codes at each bit length for an optimal tree */
  10756. // do check in _tr_init()
  10757. //if (static_init_done) return;
  10758. /* For some embedded targets, global variables are not initialized: */
  10759. /*#ifdef NO_INIT_GLOBAL_POINTERS
  10760. static_l_desc.static_tree = static_ltree;
  10761. static_l_desc.extra_bits = extra_lbits;
  10762. static_d_desc.static_tree = static_dtree;
  10763. static_d_desc.extra_bits = extra_dbits;
  10764. static_bl_desc.extra_bits = extra_blbits;
  10765. #endif*/
  10766. /* Initialize the mapping length (0..255) -> length code (0..28) */
  10767. length = 0;
  10768. for (code = 0; code < LENGTH_CODES - 1; code++) {
  10769. base_length[code] = length;
  10770. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  10771. _length_code[length++] = code;
  10772. }
  10773. }
  10774. //Assert (length == 256, "tr_static_init: length != 256");
  10775. /* Note that the length 255 (match length 258) can be represented
  10776. * in two different ways: code 284 + 5 bits or code 285, so we
  10777. * overwrite length_code[255] to use the best encoding:
  10778. */
  10779. _length_code[length - 1] = code;
  10780. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  10781. dist = 0;
  10782. for (code = 0; code < 16; code++) {
  10783. base_dist[code] = dist;
  10784. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  10785. _dist_code[dist++] = code;
  10786. }
  10787. }
  10788. //Assert (dist == 256, "tr_static_init: dist != 256");
  10789. dist >>= 7; /* from now on, all distances are divided by 128 */
  10790. for (; code < D_CODES; code++) {
  10791. base_dist[code] = dist << 7;
  10792. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  10793. _dist_code[256 + dist++] = code;
  10794. }
  10795. }
  10796. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  10797. /* Construct the codes of the static literal tree */
  10798. for (bits = 0; bits <= MAX_BITS; bits++) {
  10799. bl_count[bits] = 0;
  10800. }
  10801. n = 0;
  10802. while (n <= 143) {
  10803. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10804. n++;
  10805. bl_count[8]++;
  10806. }
  10807. while (n <= 255) {
  10808. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  10809. n++;
  10810. bl_count[9]++;
  10811. }
  10812. while (n <= 279) {
  10813. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  10814. n++;
  10815. bl_count[7]++;
  10816. }
  10817. while (n <= 287) {
  10818. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10819. n++;
  10820. bl_count[8]++;
  10821. }
  10822. /* Codes 286 and 287 do not exist, but we must include them in the
  10823. * tree construction to get a canonical Huffman tree (longest code
  10824. * all ones)
  10825. */
  10826. gen_codes(static_ltree, L_CODES + 1, bl_count);
  10827. /* The static distance tree is trivial: */
  10828. for (n = 0; n < D_CODES; n++) {
  10829. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  10830. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  10831. }
  10832. // Now data ready and we can init static trees
  10833. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  10834. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  10835. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  10836. //static_init_done = true;
  10837. }
  10838. /* ===========================================================================
  10839. * Initialize a new block.
  10840. */
  10841. function init_block(s) {
  10842. var n; /* iterates over tree elements */
  10843. /* Initialize the trees. */
  10844. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  10845. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  10846. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  10847. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  10848. s.opt_len = s.static_len = 0;
  10849. s.last_lit = s.matches = 0;
  10850. }
  10851. /* ===========================================================================
  10852. * Flush the bit buffer and align the output on a byte boundary
  10853. */
  10854. function bi_windup(s)
  10855. {
  10856. if (s.bi_valid > 8) {
  10857. put_short(s, s.bi_buf);
  10858. } else if (s.bi_valid > 0) {
  10859. //put_byte(s, (Byte)s->bi_buf);
  10860. s.pending_buf[s.pending++] = s.bi_buf;
  10861. }
  10862. s.bi_buf = 0;
  10863. s.bi_valid = 0;
  10864. }
  10865. /* ===========================================================================
  10866. * Copy a stored block, storing first the length and its
  10867. * one's complement if requested.
  10868. */
  10869. function copy_block(s, buf, len, header)
  10870. //DeflateState *s;
  10871. //charf *buf; /* the input data */
  10872. //unsigned len; /* its length */
  10873. //int header; /* true if block header must be written */
  10874. {
  10875. bi_windup(s); /* align on byte boundary */
  10876. if (header) {
  10877. put_short(s, len);
  10878. put_short(s, ~len);
  10879. }
  10880. // while (len--) {
  10881. // put_byte(s, *buf++);
  10882. // }
  10883. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  10884. s.pending += len;
  10885. }
  10886. /* ===========================================================================
  10887. * Compares to subtrees, using the tree depth as tie breaker when
  10888. * the subtrees have equal frequency. This minimizes the worst case length.
  10889. */
  10890. function smaller(tree, n, m, depth) {
  10891. var _n2 = n * 2;
  10892. var _m2 = m * 2;
  10893. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  10894. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  10895. }
  10896. /* ===========================================================================
  10897. * Restore the heap property by moving down the tree starting at node k,
  10898. * exchanging a node with the smallest of its two sons if necessary, stopping
  10899. * when the heap property is re-established (each father smaller than its
  10900. * two sons).
  10901. */
  10902. function pqdownheap(s, tree, k)
  10903. // deflate_state *s;
  10904. // ct_data *tree; /* the tree to restore */
  10905. // int k; /* node to move down */
  10906. {
  10907. var v = s.heap[k];
  10908. var j = k << 1; /* left son of k */
  10909. while (j <= s.heap_len) {
  10910. /* Set j to the smallest of the two sons: */
  10911. if (j < s.heap_len &&
  10912. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  10913. j++;
  10914. }
  10915. /* Exit if v is smaller than both sons */
  10916. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  10917. /* Exchange v with the smallest son */
  10918. s.heap[k] = s.heap[j];
  10919. k = j;
  10920. /* And continue down the tree, setting j to the left son of k */
  10921. j <<= 1;
  10922. }
  10923. s.heap[k] = v;
  10924. }
  10925. // inlined manually
  10926. // var SMALLEST = 1;
  10927. /* ===========================================================================
  10928. * Send the block data compressed using the given Huffman trees
  10929. */
  10930. function compress_block(s, ltree, dtree)
  10931. // deflate_state *s;
  10932. // const ct_data *ltree; /* literal tree */
  10933. // const ct_data *dtree; /* distance tree */
  10934. {
  10935. var dist; /* distance of matched string */
  10936. var lc; /* match length or unmatched char (if dist == 0) */
  10937. var lx = 0; /* running index in l_buf */
  10938. var code; /* the code to send */
  10939. var extra; /* number of extra bits to send */
  10940. if (s.last_lit !== 0) {
  10941. do {
  10942. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  10943. lc = s.pending_buf[s.l_buf + lx];
  10944. lx++;
  10945. if (dist === 0) {
  10946. send_code(s, lc, ltree); /* send a literal byte */
  10947. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  10948. } else {
  10949. /* Here, lc is the match length - MIN_MATCH */
  10950. code = _length_code[lc];
  10951. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  10952. extra = extra_lbits[code];
  10953. if (extra !== 0) {
  10954. lc -= base_length[code];
  10955. send_bits(s, lc, extra); /* send the extra length bits */
  10956. }
  10957. dist--; /* dist is now the match distance - 1 */
  10958. code = d_code(dist);
  10959. //Assert (code < D_CODES, "bad d_code");
  10960. send_code(s, code, dtree); /* send the distance code */
  10961. extra = extra_dbits[code];
  10962. if (extra !== 0) {
  10963. dist -= base_dist[code];
  10964. send_bits(s, dist, extra); /* send the extra distance bits */
  10965. }
  10966. } /* literal or match pair ? */
  10967. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  10968. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  10969. // "pendingBuf overflow");
  10970. } while (lx < s.last_lit);
  10971. }
  10972. send_code(s, END_BLOCK, ltree);
  10973. }
  10974. /* ===========================================================================
  10975. * Construct one Huffman tree and assigns the code bit strings and lengths.
  10976. * Update the total bit length for the current block.
  10977. * IN assertion: the field freq is set for all tree elements.
  10978. * OUT assertions: the fields len and code are set to the optimal bit length
  10979. * and corresponding code. The length opt_len is updated; static_len is
  10980. * also updated if stree is not null. The field max_code is set.
  10981. */
  10982. function build_tree(s, desc)
  10983. // deflate_state *s;
  10984. // tree_desc *desc; /* the tree descriptor */
  10985. {
  10986. var tree = desc.dyn_tree;
  10987. var stree = desc.stat_desc.static_tree;
  10988. var has_stree = desc.stat_desc.has_stree;
  10989. var elems = desc.stat_desc.elems;
  10990. var n, m; /* iterate over heap elements */
  10991. var max_code = -1; /* largest code with non zero frequency */
  10992. var node; /* new node being created */
  10993. /* Construct the initial heap, with least frequent element in
  10994. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  10995. * heap[0] is not used.
  10996. */
  10997. s.heap_len = 0;
  10998. s.heap_max = HEAP_SIZE;
  10999. for (n = 0; n < elems; n++) {
  11000. if (tree[n * 2]/*.Freq*/ !== 0) {
  11001. s.heap[++s.heap_len] = max_code = n;
  11002. s.depth[n] = 0;
  11003. } else {
  11004. tree[n * 2 + 1]/*.Len*/ = 0;
  11005. }
  11006. }
  11007. /* The pkzip format requires that at least one distance code exists,
  11008. * and that at least one bit should be sent even if there is only one
  11009. * possible code. So to avoid special checks later on we force at least
  11010. * two codes of non zero frequency.
  11011. */
  11012. while (s.heap_len < 2) {
  11013. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  11014. tree[node * 2]/*.Freq*/ = 1;
  11015. s.depth[node] = 0;
  11016. s.opt_len--;
  11017. if (has_stree) {
  11018. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  11019. }
  11020. /* node is 0 or 1 so it does not have extra bits */
  11021. }
  11022. desc.max_code = max_code;
  11023. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  11024. * establish sub-heaps of increasing lengths:
  11025. */
  11026. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  11027. /* Construct the Huffman tree by repeatedly combining the least two
  11028. * frequent nodes.
  11029. */
  11030. node = elems; /* next internal node of the tree */
  11031. do {
  11032. //pqremove(s, tree, n); /* n = node of least frequency */
  11033. /*** pqremove ***/
  11034. n = s.heap[1/*SMALLEST*/];
  11035. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  11036. pqdownheap(s, tree, 1/*SMALLEST*/);
  11037. /***/
  11038. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  11039. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  11040. s.heap[--s.heap_max] = m;
  11041. /* Create a new node father of n and m */
  11042. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  11043. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  11044. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  11045. /* and insert the new node in the heap */
  11046. s.heap[1/*SMALLEST*/] = node++;
  11047. pqdownheap(s, tree, 1/*SMALLEST*/);
  11048. } while (s.heap_len >= 2);
  11049. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  11050. /* At this point, the fields freq and dad are set. We can now
  11051. * generate the bit lengths.
  11052. */
  11053. gen_bitlen(s, desc);
  11054. /* The field len is now set, we can generate the bit codes */
  11055. gen_codes(tree, max_code, s.bl_count);
  11056. }
  11057. /* ===========================================================================
  11058. * Scan a literal or distance tree to determine the frequencies of the codes
  11059. * in the bit length tree.
  11060. */
  11061. function scan_tree(s, tree, max_code)
  11062. // deflate_state *s;
  11063. // ct_data *tree; /* the tree to be scanned */
  11064. // int max_code; /* and its largest code of non zero frequency */
  11065. {
  11066. var n; /* iterates over all tree elements */
  11067. var prevlen = -1; /* last emitted length */
  11068. var curlen; /* length of current code */
  11069. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11070. var count = 0; /* repeat count of the current code */
  11071. var max_count = 7; /* max repeat count */
  11072. var min_count = 4; /* min repeat count */
  11073. if (nextlen === 0) {
  11074. max_count = 138;
  11075. min_count = 3;
  11076. }
  11077. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  11078. for (n = 0; n <= max_code; n++) {
  11079. curlen = nextlen;
  11080. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11081. if (++count < max_count && curlen === nextlen) {
  11082. continue;
  11083. } else if (count < min_count) {
  11084. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  11085. } else if (curlen !== 0) {
  11086. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  11087. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  11088. } else if (count <= 10) {
  11089. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  11090. } else {
  11091. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  11092. }
  11093. count = 0;
  11094. prevlen = curlen;
  11095. if (nextlen === 0) {
  11096. max_count = 138;
  11097. min_count = 3;
  11098. } else if (curlen === nextlen) {
  11099. max_count = 6;
  11100. min_count = 3;
  11101. } else {
  11102. max_count = 7;
  11103. min_count = 4;
  11104. }
  11105. }
  11106. }
  11107. /* ===========================================================================
  11108. * Send a literal or distance tree in compressed form, using the codes in
  11109. * bl_tree.
  11110. */
  11111. function send_tree(s, tree, max_code)
  11112. // deflate_state *s;
  11113. // ct_data *tree; /* the tree to be scanned */
  11114. // int max_code; /* and its largest code of non zero frequency */
  11115. {
  11116. var n; /* iterates over all tree elements */
  11117. var prevlen = -1; /* last emitted length */
  11118. var curlen; /* length of current code */
  11119. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  11120. var count = 0; /* repeat count of the current code */
  11121. var max_count = 7; /* max repeat count */
  11122. var min_count = 4; /* min repeat count */
  11123. /* tree[max_code+1].Len = -1; */ /* guard already set */
  11124. if (nextlen === 0) {
  11125. max_count = 138;
  11126. min_count = 3;
  11127. }
  11128. for (n = 0; n <= max_code; n++) {
  11129. curlen = nextlen;
  11130. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  11131. if (++count < max_count && curlen === nextlen) {
  11132. continue;
  11133. } else if (count < min_count) {
  11134. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  11135. } else if (curlen !== 0) {
  11136. if (curlen !== prevlen) {
  11137. send_code(s, curlen, s.bl_tree);
  11138. count--;
  11139. }
  11140. //Assert(count >= 3 && count <= 6, " 3_6?");
  11141. send_code(s, REP_3_6, s.bl_tree);
  11142. send_bits(s, count - 3, 2);
  11143. } else if (count <= 10) {
  11144. send_code(s, REPZ_3_10, s.bl_tree);
  11145. send_bits(s, count - 3, 3);
  11146. } else {
  11147. send_code(s, REPZ_11_138, s.bl_tree);
  11148. send_bits(s, count - 11, 7);
  11149. }
  11150. count = 0;
  11151. prevlen = curlen;
  11152. if (nextlen === 0) {
  11153. max_count = 138;
  11154. min_count = 3;
  11155. } else if (curlen === nextlen) {
  11156. max_count = 6;
  11157. min_count = 3;
  11158. } else {
  11159. max_count = 7;
  11160. min_count = 4;
  11161. }
  11162. }
  11163. }
  11164. /* ===========================================================================
  11165. * Construct the Huffman tree for the bit lengths and return the index in
  11166. * bl_order of the last bit length code to send.
  11167. */
  11168. function build_bl_tree(s) {
  11169. var max_blindex; /* index of last bit length code of non zero freq */
  11170. /* Determine the bit length frequencies for literal and distance trees */
  11171. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  11172. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  11173. /* Build the bit length tree: */
  11174. build_tree(s, s.bl_desc);
  11175. /* opt_len now includes the length of the tree representations, except
  11176. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  11177. */
  11178. /* Determine the number of bit length codes to send. The pkzip format
  11179. * requires that at least 4 bit length codes be sent. (appnote.txt says
  11180. * 3 but the actual value used is 4.)
  11181. */
  11182. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  11183. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  11184. break;
  11185. }
  11186. }
  11187. /* Update opt_len to include the bit length tree and counts */
  11188. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  11189. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  11190. // s->opt_len, s->static_len));
  11191. return max_blindex;
  11192. }
  11193. /* ===========================================================================
  11194. * Send the header for a block using dynamic Huffman trees: the counts, the
  11195. * lengths of the bit length codes, the literal tree and the distance tree.
  11196. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  11197. */
  11198. function send_all_trees(s, lcodes, dcodes, blcodes)
  11199. // deflate_state *s;
  11200. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  11201. {
  11202. var rank; /* index in bl_order */
  11203. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  11204. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  11205. // "too many codes");
  11206. //Tracev((stderr, "\nbl counts: "));
  11207. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  11208. send_bits(s, dcodes - 1, 5);
  11209. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  11210. for (rank = 0; rank < blcodes; rank++) {
  11211. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  11212. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  11213. }
  11214. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  11215. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  11216. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  11217. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  11218. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  11219. }
  11220. /* ===========================================================================
  11221. * Check if the data type is TEXT or BINARY, using the following algorithm:
  11222. * - TEXT if the two conditions below are satisfied:
  11223. * a) There are no non-portable control characters belonging to the
  11224. * "black list" (0..6, 14..25, 28..31).
  11225. * b) There is at least one printable character belonging to the
  11226. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  11227. * - BINARY otherwise.
  11228. * - The following partially-portable control characters form a
  11229. * "gray list" that is ignored in this detection algorithm:
  11230. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  11231. * IN assertion: the fields Freq of dyn_ltree are set.
  11232. */
  11233. function detect_data_type(s) {
  11234. /* black_mask is the bit mask of black-listed bytes
  11235. * set bits 0..6, 14..25, and 28..31
  11236. * 0xf3ffc07f = binary 11110011111111111100000001111111
  11237. */
  11238. var black_mask = 0xf3ffc07f;
  11239. var n;
  11240. /* Check for non-textual ("black-listed") bytes. */
  11241. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  11242. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  11243. return Z_BINARY;
  11244. }
  11245. }
  11246. /* Check for textual ("white-listed") bytes. */
  11247. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  11248. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  11249. return Z_TEXT;
  11250. }
  11251. for (n = 32; n < LITERALS; n++) {
  11252. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  11253. return Z_TEXT;
  11254. }
  11255. }
  11256. /* There are no "black-listed" or "white-listed" bytes:
  11257. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  11258. */
  11259. return Z_BINARY;
  11260. }
  11261. var static_init_done = false;
  11262. /* ===========================================================================
  11263. * Initialize the tree data structures for a new zlib stream.
  11264. */
  11265. function _tr_init(s)
  11266. {
  11267. if (!static_init_done) {
  11268. tr_static_init();
  11269. static_init_done = true;
  11270. }
  11271. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  11272. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  11273. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  11274. s.bi_buf = 0;
  11275. s.bi_valid = 0;
  11276. /* Initialize the first block of the first file: */
  11277. init_block(s);
  11278. }
  11279. /* ===========================================================================
  11280. * Send a stored block
  11281. */
  11282. function _tr_stored_block(s, buf, stored_len, last)
  11283. //DeflateState *s;
  11284. //charf *buf; /* input block */
  11285. //ulg stored_len; /* length of input block */
  11286. //int last; /* one if this is the last block for a file */
  11287. {
  11288. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  11289. copy_block(s, buf, stored_len, true); /* with header */
  11290. }
  11291. /* ===========================================================================
  11292. * Send one empty static block to give enough lookahead for inflate.
  11293. * This takes 10 bits, of which 7 may remain in the bit buffer.
  11294. */
  11295. function _tr_align(s) {
  11296. send_bits(s, STATIC_TREES << 1, 3);
  11297. send_code(s, END_BLOCK, static_ltree);
  11298. bi_flush(s);
  11299. }
  11300. /* ===========================================================================
  11301. * Determine the best encoding for the current block: dynamic trees, static
  11302. * trees or store, and output the encoded block to the zip file.
  11303. */
  11304. function _tr_flush_block(s, buf, stored_len, last)
  11305. //DeflateState *s;
  11306. //charf *buf; /* input block, or NULL if too old */
  11307. //ulg stored_len; /* length of input block */
  11308. //int last; /* one if this is the last block for a file */
  11309. {
  11310. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  11311. var max_blindex = 0; /* index of last bit length code of non zero freq */
  11312. /* Build the Huffman trees unless a stored block is forced */
  11313. if (s.level > 0) {
  11314. /* Check if the file is binary or text */
  11315. if (s.strm.data_type === Z_UNKNOWN) {
  11316. s.strm.data_type = detect_data_type(s);
  11317. }
  11318. /* Construct the literal and distance trees */
  11319. build_tree(s, s.l_desc);
  11320. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  11321. // s->static_len));
  11322. build_tree(s, s.d_desc);
  11323. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  11324. // s->static_len));
  11325. /* At this point, opt_len and static_len are the total bit lengths of
  11326. * the compressed block data, excluding the tree representations.
  11327. */
  11328. /* Build the bit length tree for the above two trees, and get the index
  11329. * in bl_order of the last bit length code to send.
  11330. */
  11331. max_blindex = build_bl_tree(s);
  11332. /* Determine the best encoding. Compute the block lengths in bytes. */
  11333. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  11334. static_lenb = (s.static_len + 3 + 7) >>> 3;
  11335. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  11336. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  11337. // s->last_lit));
  11338. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  11339. } else {
  11340. // Assert(buf != (char*)0, "lost buf");
  11341. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  11342. }
  11343. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  11344. /* 4: two words for the lengths */
  11345. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  11346. * Otherwise we can't have processed more than WSIZE input bytes since
  11347. * the last block flush, because compression would have been
  11348. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  11349. * transform a block into a stored block.
  11350. */
  11351. _tr_stored_block(s, buf, stored_len, last);
  11352. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  11353. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  11354. compress_block(s, static_ltree, static_dtree);
  11355. } else {
  11356. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  11357. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  11358. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  11359. }
  11360. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  11361. /* The above check is made mod 2^32, for files larger than 512 MB
  11362. * and uLong implemented on 32 bits.
  11363. */
  11364. init_block(s);
  11365. if (last) {
  11366. bi_windup(s);
  11367. }
  11368. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  11369. // s->compressed_len-7*last));
  11370. }
  11371. /* ===========================================================================
  11372. * Save the match info and tally the frequency counts. Return true if
  11373. * the current block must be flushed.
  11374. */
  11375. function _tr_tally(s, dist, lc)
  11376. // deflate_state *s;
  11377. // unsigned dist; /* distance of matched string */
  11378. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  11379. {
  11380. //var out_length, in_length, dcode;
  11381. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  11382. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  11383. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  11384. s.last_lit++;
  11385. if (dist === 0) {
  11386. /* lc is the unmatched char */
  11387. s.dyn_ltree[lc * 2]/*.Freq*/++;
  11388. } else {
  11389. s.matches++;
  11390. /* Here, lc is the match length - MIN_MATCH */
  11391. dist--; /* dist = match distance - 1 */
  11392. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  11393. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  11394. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  11395. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  11396. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  11397. }
  11398. // (!) This block is disabled in zlib defailts,
  11399. // don't enable it for binary compatibility
  11400. //#ifdef TRUNCATE_BLOCK
  11401. // /* Try to guess if it is profitable to stop the current block here */
  11402. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  11403. // /* Compute an upper bound for the compressed length */
  11404. // out_length = s.last_lit*8;
  11405. // in_length = s.strstart - s.block_start;
  11406. //
  11407. // for (dcode = 0; dcode < D_CODES; dcode++) {
  11408. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  11409. // }
  11410. // out_length >>>= 3;
  11411. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  11412. // // s->last_lit, in_length, out_length,
  11413. // // 100L - out_length*100L/in_length));
  11414. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  11415. // return true;
  11416. // }
  11417. // }
  11418. //#endif
  11419. return (s.last_lit === s.lit_bufsize - 1);
  11420. /* We avoid equality with lit_bufsize because of wraparound at 64K
  11421. * on 16 bit machines and because stored blocks are restricted to
  11422. * 64K-1 bytes.
  11423. */
  11424. }
  11425. exports._tr_init = _tr_init;
  11426. exports._tr_stored_block = _tr_stored_block;
  11427. exports._tr_flush_block = _tr_flush_block;
  11428. exports._tr_tally = _tr_tally;
  11429. exports._tr_align = _tr_align;
  11430. },{"../utils/common":32}],44:[function(_dereq_,module,exports){
  11431. 'use strict';
  11432. function ZStream() {
  11433. /* next input byte */
  11434. this.input = null; // JS specific, because we have no pointers
  11435. this.next_in = 0;
  11436. /* number of bytes available at input */
  11437. this.avail_in = 0;
  11438. /* total number of input bytes read so far */
  11439. this.total_in = 0;
  11440. /* next output byte should be put there */
  11441. this.output = null; // JS specific, because we have no pointers
  11442. this.next_out = 0;
  11443. /* remaining free space at output */
  11444. this.avail_out = 0;
  11445. /* total number of bytes output so far */
  11446. this.total_out = 0;
  11447. /* last error message, NULL if no error */
  11448. this.msg = ''/*Z_NULL*/;
  11449. /* not visible by applications */
  11450. this.state = null;
  11451. /* best guess about the data type: binary or text */
  11452. this.data_type = 2/*Z_UNKNOWN*/;
  11453. /* adler32 value of the uncompressed data */
  11454. this.adler = 0;
  11455. }
  11456. module.exports = ZStream;
  11457. },{}],45:[function(_dereq_,module,exports){
  11458. /**
  11459. * lodash 3.2.0 (Custom Build) <https://lodash.com/>
  11460. * Build: `lodash modularize exports="npm" -o ./`
  11461. * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
  11462. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11463. * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11464. * Available under MIT license <https://lodash.com/license>
  11465. */
  11466. var root = _dereq_('lodash._root');
  11467. /** Used as references for various `Number` constants. */
  11468. var INFINITY = 1 / 0;
  11469. /** `Object#toString` result references. */
  11470. var symbolTag = '[object Symbol]';
  11471. /** Used to match HTML entities and HTML characters. */
  11472. var reUnescapedHtml = /[&<>"'`]/g,
  11473. reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
  11474. /** Used to map characters to HTML entities. */
  11475. var htmlEscapes = {
  11476. '&': '&amp;',
  11477. '<': '&lt;',
  11478. '>': '&gt;',
  11479. '"': '&quot;',
  11480. "'": '&#39;',
  11481. '`': '&#96;'
  11482. };
  11483. /**
  11484. * Used by `_.escape` to convert characters to HTML entities.
  11485. *
  11486. * @private
  11487. * @param {string} chr The matched character to escape.
  11488. * @returns {string} Returns the escaped character.
  11489. */
  11490. function escapeHtmlChar(chr) {
  11491. return htmlEscapes[chr];
  11492. }
  11493. /** Used for built-in method references. */
  11494. var objectProto = Object.prototype;
  11495. /**
  11496. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  11497. * of values.
  11498. */
  11499. var objectToString = objectProto.toString;
  11500. /** Built-in value references. */
  11501. var Symbol = root.Symbol;
  11502. /** Used to convert symbols to primitives and strings. */
  11503. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11504. symbolToString = Symbol ? symbolProto.toString : undefined;
  11505. /**
  11506. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11507. * and has a `typeof` result of "object".
  11508. *
  11509. * @static
  11510. * @memberOf _
  11511. * @category Lang
  11512. * @param {*} value The value to check.
  11513. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11514. * @example
  11515. *
  11516. * _.isObjectLike({});
  11517. * // => true
  11518. *
  11519. * _.isObjectLike([1, 2, 3]);
  11520. * // => true
  11521. *
  11522. * _.isObjectLike(_.noop);
  11523. * // => false
  11524. *
  11525. * _.isObjectLike(null);
  11526. * // => false
  11527. */
  11528. function isObjectLike(value) {
  11529. return !!value && typeof value == 'object';
  11530. }
  11531. /**
  11532. * Checks if `value` is classified as a `Symbol` primitive or object.
  11533. *
  11534. * @static
  11535. * @memberOf _
  11536. * @category Lang
  11537. * @param {*} value The value to check.
  11538. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  11539. * @example
  11540. *
  11541. * _.isSymbol(Symbol.iterator);
  11542. * // => true
  11543. *
  11544. * _.isSymbol('abc');
  11545. * // => false
  11546. */
  11547. function isSymbol(value) {
  11548. return typeof value == 'symbol' ||
  11549. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11550. }
  11551. /**
  11552. * Converts `value` to a string if it's not one. An empty string is returned
  11553. * for `null` and `undefined` values. The sign of `-0` is preserved.
  11554. *
  11555. * @static
  11556. * @memberOf _
  11557. * @category Lang
  11558. * @param {*} value The value to process.
  11559. * @returns {string} Returns the string.
  11560. * @example
  11561. *
  11562. * _.toString(null);
  11563. * // => ''
  11564. *
  11565. * _.toString(-0);
  11566. * // => '-0'
  11567. *
  11568. * _.toString([1, 2, 3]);
  11569. * // => '1,2,3'
  11570. */
  11571. function toString(value) {
  11572. // Exit early for strings to avoid a performance hit in some environments.
  11573. if (typeof value == 'string') {
  11574. return value;
  11575. }
  11576. if (value == null) {
  11577. return '';
  11578. }
  11579. if (isSymbol(value)) {
  11580. return Symbol ? symbolToString.call(value) : '';
  11581. }
  11582. var result = (value + '');
  11583. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  11584. }
  11585. /**
  11586. * Converts the characters "&", "<", ">", '"', "'", and "\`" in `string` to
  11587. * their corresponding HTML entities.
  11588. *
  11589. * **Note:** No other characters are escaped. To escape additional
  11590. * characters use a third-party library like [_he_](https://mths.be/he).
  11591. *
  11592. * Though the ">" character is escaped for symmetry, characters like
  11593. * ">" and "/" don't need escaping in HTML and have no special meaning
  11594. * unless they're part of a tag or unquoted attribute value.
  11595. * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
  11596. * (under "semi-related fun fact") for more details.
  11597. *
  11598. * Backticks are escaped because in IE < 9, they can break out of
  11599. * attribute values or HTML comments. See [#59](https://html5sec.org/#59),
  11600. * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
  11601. * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
  11602. * for more details.
  11603. *
  11604. * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
  11605. * to reduce XSS vectors.
  11606. *
  11607. * @static
  11608. * @memberOf _
  11609. * @category String
  11610. * @param {string} [string=''] The string to escape.
  11611. * @returns {string} Returns the escaped string.
  11612. * @example
  11613. *
  11614. * _.escape('fred, barney, & pebbles');
  11615. * // => 'fred, barney, &amp; pebbles'
  11616. */
  11617. function escape(string) {
  11618. string = toString(string);
  11619. return (string && reHasUnescapedHtml.test(string))
  11620. ? string.replace(reUnescapedHtml, escapeHtmlChar)
  11621. : string;
  11622. }
  11623. module.exports = escape;
  11624. },{"lodash._root":46}],46:[function(_dereq_,module,exports){
  11625. (function (global){
  11626. /**
  11627. * lodash 3.0.1 (Custom Build) <https://lodash.com/>
  11628. * Build: `lodash modularize exports="npm" -o ./`
  11629. * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
  11630. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11631. * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11632. * Available under MIT license <https://lodash.com/license>
  11633. */
  11634. /** Used to determine if values are of the language type `Object`. */
  11635. var objectTypes = {
  11636. 'function': true,
  11637. 'object': true
  11638. };
  11639. /** Detect free variable `exports`. */
  11640. var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
  11641. ? exports
  11642. : undefined;
  11643. /** Detect free variable `module`. */
  11644. var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
  11645. ? module
  11646. : undefined;
  11647. /** Detect free variable `global` from Node.js. */
  11648. var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
  11649. /** Detect free variable `self`. */
  11650. var freeSelf = checkGlobal(objectTypes[typeof self] && self);
  11651. /** Detect free variable `window`. */
  11652. var freeWindow = checkGlobal(objectTypes[typeof window] && window);
  11653. /** Detect `this` as the global object. */
  11654. var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
  11655. /**
  11656. * Used as a reference to the global object.
  11657. *
  11658. * The `this` value is used if it's the global object to avoid Greasemonkey's
  11659. * restricted `window` object, otherwise the `window` object is used.
  11660. */
  11661. var root = freeGlobal ||
  11662. ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
  11663. freeSelf || thisGlobal || Function('return this')();
  11664. /**
  11665. * Checks if `value` is a global object.
  11666. *
  11667. * @private
  11668. * @param {*} value The value to check.
  11669. * @returns {null|Object} Returns `value` if it's a global object, else `null`.
  11670. */
  11671. function checkGlobal(value) {
  11672. return (value && value.Object === Object) ? value : null;
  11673. }
  11674. module.exports = root;
  11675. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11676. },{}],47:[function(_dereq_,module,exports){
  11677. /**
  11678. * lodash 3.3.2 (Custom Build) <https://lodash.com/>
  11679. * Build: `lodash modern modularize exports="npm" -o ./`
  11680. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11681. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11682. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11683. * Available under MIT license <https://lodash.com/license>
  11684. */
  11685. var arrayCopy = _dereq_('lodash._arraycopy'),
  11686. arrayEach = _dereq_('lodash._arrayeach'),
  11687. createAssigner = _dereq_('lodash._createassigner'),
  11688. isArguments = _dereq_('lodash.isarguments'),
  11689. isArray = _dereq_('lodash.isarray'),
  11690. isPlainObject = _dereq_('lodash.isplainobject'),
  11691. isTypedArray = _dereq_('lodash.istypedarray'),
  11692. keys = _dereq_('lodash.keys'),
  11693. toPlainObject = _dereq_('lodash.toplainobject');
  11694. /**
  11695. * Checks if `value` is object-like.
  11696. *
  11697. * @private
  11698. * @param {*} value The value to check.
  11699. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11700. */
  11701. function isObjectLike(value) {
  11702. return !!value && typeof value == 'object';
  11703. }
  11704. /**
  11705. * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
  11706. * of an array-like value.
  11707. */
  11708. var MAX_SAFE_INTEGER = 9007199254740991;
  11709. /**
  11710. * The base implementation of `_.merge` without support for argument juggling,
  11711. * multiple sources, and `this` binding `customizer` functions.
  11712. *
  11713. * @private
  11714. * @param {Object} object The destination object.
  11715. * @param {Object} source The source object.
  11716. * @param {Function} [customizer] The function to customize merged values.
  11717. * @param {Array} [stackA=[]] Tracks traversed source objects.
  11718. * @param {Array} [stackB=[]] Associates values with source counterparts.
  11719. * @returns {Object} Returns `object`.
  11720. */
  11721. function baseMerge(object, source, customizer, stackA, stackB) {
  11722. if (!isObject(object)) {
  11723. return object;
  11724. }
  11725. var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
  11726. props = isSrcArr ? undefined : keys(source);
  11727. arrayEach(props || source, function(srcValue, key) {
  11728. if (props) {
  11729. key = srcValue;
  11730. srcValue = source[key];
  11731. }
  11732. if (isObjectLike(srcValue)) {
  11733. stackA || (stackA = []);
  11734. stackB || (stackB = []);
  11735. baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
  11736. }
  11737. else {
  11738. var value = object[key],
  11739. result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
  11740. isCommon = result === undefined;
  11741. if (isCommon) {
  11742. result = srcValue;
  11743. }
  11744. if ((result !== undefined || (isSrcArr && !(key in object))) &&
  11745. (isCommon || (result === result ? (result !== value) : (value === value)))) {
  11746. object[key] = result;
  11747. }
  11748. }
  11749. });
  11750. return object;
  11751. }
  11752. /**
  11753. * A specialized version of `baseMerge` for arrays and objects which performs
  11754. * deep merges and tracks traversed objects enabling objects with circular
  11755. * references to be merged.
  11756. *
  11757. * @private
  11758. * @param {Object} object The destination object.
  11759. * @param {Object} source The source object.
  11760. * @param {string} key The key of the value to merge.
  11761. * @param {Function} mergeFunc The function to merge values.
  11762. * @param {Function} [customizer] The function to customize merged values.
  11763. * @param {Array} [stackA=[]] Tracks traversed source objects.
  11764. * @param {Array} [stackB=[]] Associates values with source counterparts.
  11765. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  11766. */
  11767. function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
  11768. var length = stackA.length,
  11769. srcValue = source[key];
  11770. while (length--) {
  11771. if (stackA[length] == srcValue) {
  11772. object[key] = stackB[length];
  11773. return;
  11774. }
  11775. }
  11776. var value = object[key],
  11777. result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
  11778. isCommon = result === undefined;
  11779. if (isCommon) {
  11780. result = srcValue;
  11781. if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
  11782. result = isArray(value)
  11783. ? value
  11784. : (isArrayLike(value) ? arrayCopy(value) : []);
  11785. }
  11786. else if (isPlainObject(srcValue) || isArguments(srcValue)) {
  11787. result = isArguments(value)
  11788. ? toPlainObject(value)
  11789. : (isPlainObject(value) ? value : {});
  11790. }
  11791. else {
  11792. isCommon = false;
  11793. }
  11794. }
  11795. // Add the source value to the stack of traversed objects and associate
  11796. // it with its merged value.
  11797. stackA.push(srcValue);
  11798. stackB.push(result);
  11799. if (isCommon) {
  11800. // Recursively merge objects and arrays (susceptible to call stack limits).
  11801. object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
  11802. } else if (result === result ? (result !== value) : (value === value)) {
  11803. object[key] = result;
  11804. }
  11805. }
  11806. /**
  11807. * The base implementation of `_.property` without support for deep paths.
  11808. *
  11809. * @private
  11810. * @param {string} key The key of the property to get.
  11811. * @returns {Function} Returns the new function.
  11812. */
  11813. function baseProperty(key) {
  11814. return function(object) {
  11815. return object == null ? undefined : object[key];
  11816. };
  11817. }
  11818. /**
  11819. * Gets the "length" property value of `object`.
  11820. *
  11821. * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
  11822. * that affects Safari on at least iOS 8.1-8.3 ARM64.
  11823. *
  11824. * @private
  11825. * @param {Object} object The object to query.
  11826. * @returns {*} Returns the "length" value.
  11827. */
  11828. var getLength = baseProperty('length');
  11829. /**
  11830. * Checks if `value` is array-like.
  11831. *
  11832. * @private
  11833. * @param {*} value The value to check.
  11834. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  11835. */
  11836. function isArrayLike(value) {
  11837. return value != null && isLength(getLength(value));
  11838. }
  11839. /**
  11840. * Checks if `value` is a valid array-like length.
  11841. *
  11842. * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  11843. *
  11844. * @private
  11845. * @param {*} value The value to check.
  11846. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  11847. */
  11848. function isLength(value) {
  11849. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  11850. }
  11851. /**
  11852. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  11853. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  11854. *
  11855. * @static
  11856. * @memberOf _
  11857. * @category Lang
  11858. * @param {*} value The value to check.
  11859. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  11860. * @example
  11861. *
  11862. * _.isObject({});
  11863. * // => true
  11864. *
  11865. * _.isObject([1, 2, 3]);
  11866. * // => true
  11867. *
  11868. * _.isObject(1);
  11869. * // => false
  11870. */
  11871. function isObject(value) {
  11872. // Avoid a V8 JIT bug in Chrome 19-20.
  11873. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  11874. var type = typeof value;
  11875. return !!value && (type == 'object' || type == 'function');
  11876. }
  11877. /**
  11878. * Recursively merges own enumerable properties of the source object(s), that
  11879. * don't resolve to `undefined` into the destination object. Subsequent sources
  11880. * overwrite property assignments of previous sources. If `customizer` is
  11881. * provided it is invoked to produce the merged values of the destination and
  11882. * source properties. If `customizer` returns `undefined` merging is handled
  11883. * by the method instead. The `customizer` is bound to `thisArg` and invoked
  11884. * with five arguments: (objectValue, sourceValue, key, object, source).
  11885. *
  11886. * @static
  11887. * @memberOf _
  11888. * @category Object
  11889. * @param {Object} object The destination object.
  11890. * @param {...Object} [sources] The source objects.
  11891. * @param {Function} [customizer] The function to customize assigned values.
  11892. * @param {*} [thisArg] The `this` binding of `customizer`.
  11893. * @returns {Object} Returns `object`.
  11894. * @example
  11895. *
  11896. * var users = {
  11897. * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
  11898. * };
  11899. *
  11900. * var ages = {
  11901. * 'data': [{ 'age': 36 }, { 'age': 40 }]
  11902. * };
  11903. *
  11904. * _.merge(users, ages);
  11905. * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
  11906. *
  11907. * // using a customizer callback
  11908. * var object = {
  11909. * 'fruits': ['apple'],
  11910. * 'vegetables': ['beet']
  11911. * };
  11912. *
  11913. * var other = {
  11914. * 'fruits': ['banana'],
  11915. * 'vegetables': ['carrot']
  11916. * };
  11917. *
  11918. * _.merge(object, other, function(a, b) {
  11919. * if (_.isArray(a)) {
  11920. * return a.concat(b);
  11921. * }
  11922. * });
  11923. * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
  11924. */
  11925. var merge = createAssigner(baseMerge);
  11926. module.exports = merge;
  11927. },{"lodash._arraycopy":48,"lodash._arrayeach":49,"lodash._createassigner":50,"lodash.isarguments":55,"lodash.isarray":56,"lodash.isplainobject":57,"lodash.istypedarray":59,"lodash.keys":60,"lodash.toplainobject":62}],48:[function(_dereq_,module,exports){
  11928. /**
  11929. * lodash 3.0.0 (Custom Build) <https://lodash.com/>
  11930. * Build: `lodash modern modularize exports="npm" -o ./`
  11931. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11932. * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
  11933. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11934. * Available under MIT license <https://lodash.com/license>
  11935. */
  11936. /**
  11937. * Copies the values of `source` to `array`.
  11938. *
  11939. * @private
  11940. * @param {Array} source The array to copy values from.
  11941. * @param {Array} [array=[]] The array to copy values to.
  11942. * @returns {Array} Returns `array`.
  11943. */
  11944. function arrayCopy(source, array) {
  11945. var index = -1,
  11946. length = source.length;
  11947. array || (array = Array(length));
  11948. while (++index < length) {
  11949. array[index] = source[index];
  11950. }
  11951. return array;
  11952. }
  11953. module.exports = arrayCopy;
  11954. },{}],49:[function(_dereq_,module,exports){
  11955. /**
  11956. * lodash 3.0.0 (Custom Build) <https://lodash.com/>
  11957. * Build: `lodash modern modularize exports="npm" -o ./`
  11958. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11959. * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
  11960. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11961. * Available under MIT license <https://lodash.com/license>
  11962. */
  11963. /**
  11964. * A specialized version of `_.forEach` for arrays without support for callback
  11965. * shorthands or `this` binding.
  11966. *
  11967. * @private
  11968. * @param {Array} array The array to iterate over.
  11969. * @param {Function} iteratee The function invoked per iteration.
  11970. * @returns {Array} Returns `array`.
  11971. */
  11972. function arrayEach(array, iteratee) {
  11973. var index = -1,
  11974. length = array.length;
  11975. while (++index < length) {
  11976. if (iteratee(array[index], index, array) === false) {
  11977. break;
  11978. }
  11979. }
  11980. return array;
  11981. }
  11982. module.exports = arrayEach;
  11983. },{}],50:[function(_dereq_,module,exports){
  11984. /**
  11985. * lodash 3.1.1 (Custom Build) <https://lodash.com/>
  11986. * Build: `lodash modern modularize exports="npm" -o ./`
  11987. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11988. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11989. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11990. * Available under MIT license <https://lodash.com/license>
  11991. */
  11992. var bindCallback = _dereq_('lodash._bindcallback'),
  11993. isIterateeCall = _dereq_('lodash._isiterateecall'),
  11994. restParam = _dereq_('lodash.restparam');
  11995. /**
  11996. * Creates a function that assigns properties of source object(s) to a given
  11997. * destination object.
  11998. *
  11999. * **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`.
  12000. *
  12001. * @private
  12002. * @param {Function} assigner The function to assign values.
  12003. * @returns {Function} Returns the new assigner function.
  12004. */
  12005. function createAssigner(assigner) {
  12006. return restParam(function(object, sources) {
  12007. var index = -1,
  12008. length = object == null ? 0 : sources.length,
  12009. customizer = length > 2 ? sources[length - 2] : undefined,
  12010. guard = length > 2 ? sources[2] : undefined,
  12011. thisArg = length > 1 ? sources[length - 1] : undefined;
  12012. if (typeof customizer == 'function') {
  12013. customizer = bindCallback(customizer, thisArg, 5);
  12014. length -= 2;
  12015. } else {
  12016. customizer = typeof thisArg == 'function' ? thisArg : undefined;
  12017. length -= (customizer ? 1 : 0);
  12018. }
  12019. if (guard && isIterateeCall(sources[0], sources[1], guard)) {
  12020. customizer = length < 3 ? undefined : customizer;
  12021. length = 1;
  12022. }
  12023. while (++index < length) {
  12024. var source = sources[index];
  12025. if (source) {
  12026. assigner(object, source, customizer);
  12027. }
  12028. }
  12029. return object;
  12030. });
  12031. }
  12032. module.exports = createAssigner;
  12033. },{"lodash._bindcallback":51,"lodash._isiterateecall":52,"lodash.restparam":53}],51:[function(_dereq_,module,exports){
  12034. /**
  12035. * lodash 3.0.1 (Custom Build) <https://lodash.com/>
  12036. * Build: `lodash modern modularize exports="npm" -o ./`
  12037. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  12038. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12039. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12040. * Available under MIT license <https://lodash.com/license>
  12041. */
  12042. /**
  12043. * A specialized version of `baseCallback` which only supports `this` binding
  12044. * and specifying the number of arguments to provide to `func`.
  12045. *
  12046. * @private
  12047. * @param {Function} func The function to bind.
  12048. * @param {*} thisArg The `this` binding of `func`.
  12049. * @param {number} [argCount] The number of arguments to provide to `func`.
  12050. * @returns {Function} Returns the callback.
  12051. */
  12052. function bindCallback(func, thisArg, argCount) {
  12053. if (typeof func != 'function') {
  12054. return identity;
  12055. }
  12056. if (thisArg === undefined) {
  12057. return func;
  12058. }
  12059. switch (argCount) {
  12060. case 1: return function(value) {
  12061. return func.call(thisArg, value);
  12062. };
  12063. case 3: return function(value, index, collection) {
  12064. return func.call(thisArg, value, index, collection);
  12065. };
  12066. case 4: return function(accumulator, value, index, collection) {
  12067. return func.call(thisArg, accumulator, value, index, collection);
  12068. };
  12069. case 5: return function(value, other, key, object, source) {
  12070. return func.call(thisArg, value, other, key, object, source);
  12071. };
  12072. }
  12073. return function() {
  12074. return func.apply(thisArg, arguments);
  12075. };
  12076. }
  12077. /**
  12078. * This method returns the first argument provided to it.
  12079. *
  12080. * @static
  12081. * @memberOf _
  12082. * @category Utility
  12083. * @param {*} value Any value.
  12084. * @returns {*} Returns `value`.
  12085. * @example
  12086. *
  12087. * var object = { 'user': 'fred' };
  12088. *
  12089. * _.identity(object) === object;
  12090. * // => true
  12091. */
  12092. function identity(value) {
  12093. return value;
  12094. }
  12095. module.exports = bindCallback;
  12096. },{}],52:[function(_dereq_,module,exports){
  12097. /**
  12098. * lodash 3.0.9 (Custom Build) <https://lodash.com/>
  12099. * Build: `lodash modern modularize exports="npm" -o ./`
  12100. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  12101. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12102. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12103. * Available under MIT license <https://lodash.com/license>
  12104. */
  12105. /** Used to detect unsigned integer values. */
  12106. var reIsUint = /^\d+$/;
  12107. /**
  12108. * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
  12109. * of an array-like value.
  12110. */
  12111. var MAX_SAFE_INTEGER = 9007199254740991;
  12112. /**
  12113. * The base implementation of `_.property` without support for deep paths.
  12114. *
  12115. * @private
  12116. * @param {string} key The key of the property to get.
  12117. * @returns {Function} Returns the new function.
  12118. */
  12119. function baseProperty(key) {
  12120. return function(object) {
  12121. return object == null ? undefined : object[key];
  12122. };
  12123. }
  12124. /**
  12125. * Gets the "length" property value of `object`.
  12126. *
  12127. * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
  12128. * that affects Safari on at least iOS 8.1-8.3 ARM64.
  12129. *
  12130. * @private
  12131. * @param {Object} object The object to query.
  12132. * @returns {*} Returns the "length" value.
  12133. */
  12134. var getLength = baseProperty('length');
  12135. /**
  12136. * Checks if `value` is array-like.
  12137. *
  12138. * @private
  12139. * @param {*} value The value to check.
  12140. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  12141. */
  12142. function isArrayLike(value) {
  12143. return value != null && isLength(getLength(value));
  12144. }
  12145. /**
  12146. * Checks if `value` is a valid array-like index.
  12147. *
  12148. * @private
  12149. * @param {*} value The value to check.
  12150. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  12151. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  12152. */
  12153. function isIndex(value, length) {
  12154. value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
  12155. length = length == null ? MAX_SAFE_INTEGER : length;
  12156. return value > -1 && value % 1 == 0 && value < length;
  12157. }
  12158. /**
  12159. * Checks if the provided arguments are from an iteratee call.
  12160. *
  12161. * @private
  12162. * @param {*} value The potential iteratee value argument.
  12163. * @param {*} index The potential iteratee index or key argument.
  12164. * @param {*} object The potential iteratee object argument.
  12165. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
  12166. */
  12167. function isIterateeCall(value, index, object) {
  12168. if (!isObject(object)) {
  12169. return false;
  12170. }
  12171. var type = typeof index;
  12172. if (type == 'number'
  12173. ? (isArrayLike(object) && isIndex(index, object.length))
  12174. : (type == 'string' && index in object)) {
  12175. var other = object[index];
  12176. return value === value ? (value === other) : (other !== other);
  12177. }
  12178. return false;
  12179. }
  12180. /**
  12181. * Checks if `value` is a valid array-like length.
  12182. *
  12183. * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
  12184. *
  12185. * @private
  12186. * @param {*} value The value to check.
  12187. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  12188. */
  12189. function isLength(value) {
  12190. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  12191. }
  12192. /**
  12193. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  12194. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  12195. *
  12196. * @static
  12197. * @memberOf _
  12198. * @category Lang
  12199. * @param {*} value The value to check.
  12200. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  12201. * @example
  12202. *
  12203. * _.isObject({});
  12204. * // => true
  12205. *
  12206. * _.isObject([1, 2, 3]);
  12207. * // => true
  12208. *
  12209. * _.isObject(1);
  12210. * // => false
  12211. */
  12212. function isObject(value) {
  12213. // Avoid a V8 JIT bug in Chrome 19-20.
  12214. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  12215. var type = typeof value;
  12216. return !!value && (type == 'object' || type == 'function');
  12217. }
  12218. module.exports = isIterateeCall;
  12219. },{}],53:[function(_dereq_,module,exports){
  12220. /**
  12221. * lodash 3.6.1 (Custom Build) <https://lodash.com/>
  12222. * Build: `lodash modern modularize exports="npm" -o ./`
  12223. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  12224. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12225. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12226. * Available under MIT license <https://lodash.com/license>
  12227. */
  12228. /** Used as the `TypeError` message for "Functions" methods. */
  12229. var FUNC_ERROR_TEXT = 'Expected a function';
  12230. /* Native method references for those with the same name as other `lodash` methods. */
  12231. var nativeMax = Math.max;
  12232. /**
  12233. * Creates a function that invokes `func` with the `this` binding of the
  12234. * created function and arguments from `start` and beyond provided as an array.
  12235. *
  12236. * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
  12237. *
  12238. * @static
  12239. * @memberOf _
  12240. * @category Function
  12241. * @param {Function} func The function to apply a rest parameter to.
  12242. * @param {number} [start=func.length-1] The start position of the rest parameter.
  12243. * @returns {Function} Returns the new function.
  12244. * @example
  12245. *
  12246. * var say = _.restParam(function(what, names) {
  12247. * return what + ' ' + _.initial(names).join(', ') +
  12248. * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
  12249. * });
  12250. *
  12251. * say('hello', 'fred', 'barney', 'pebbles');
  12252. * // => 'hello fred, barney, & pebbles'
  12253. */
  12254. function restParam(func, start) {
  12255. if (typeof func != 'function') {
  12256. throw new TypeError(FUNC_ERROR_TEXT);
  12257. }
  12258. start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
  12259. return function() {
  12260. var args = arguments,
  12261. index = -1,
  12262. length = nativeMax(args.length - start, 0),
  12263. rest = Array(length);
  12264. while (++index < length) {
  12265. rest[index] = args[start + index];
  12266. }
  12267. switch (start) {
  12268. case 0: return func.call(this, rest);
  12269. case 1: return func.call(this, args[0], rest);
  12270. case 2: return func.call(this, args[0], args[1], rest);
  12271. }
  12272. var otherArgs = Array(start + 1);
  12273. index = -1;
  12274. while (++index < start) {
  12275. otherArgs[index] = args[index];
  12276. }
  12277. otherArgs[start] = rest;
  12278. return func.apply(this, otherArgs);
  12279. };
  12280. }
  12281. module.exports = restParam;
  12282. },{}],54:[function(_dereq_,module,exports){
  12283. /**
  12284. * lodash 3.9.1 (Custom Build) <https://lodash.com/>
  12285. * Build: `lodash modern modularize exports="npm" -o ./`
  12286. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  12287. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12288. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12289. * Available under MIT license <https://lodash.com/license>
  12290. */
  12291. /** `Object#toString` result references. */
  12292. var funcTag = '[object Function]';
  12293. /** Used to detect host constructors (Safari > 5). */
  12294. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  12295. /**
  12296. * Checks if `value` is object-like.
  12297. *
  12298. * @private
  12299. * @param {*} value The value to check.
  12300. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  12301. */
  12302. function isObjectLike(value) {
  12303. return !!value && typeof value == 'object';
  12304. }
  12305. /** Used for native method references. */
  12306. var objectProto = Object.prototype;
  12307. /** Used to resolve the decompiled source of functions. */
  12308. var fnToString = Function.prototype.toString;
  12309. /** Used to check objects for own properties. */
  12310. var hasOwnProperty = objectProto.hasOwnProperty;
  12311. /**
  12312. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  12313. * of values.
  12314. */
  12315. var objToString = objectProto.toString;
  12316. /** Used to detect if a method is native. */
  12317. var reIsNative = RegExp('^' +
  12318. fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
  12319. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  12320. );
  12321. /**
  12322. * Gets the native function at `key` of `object`.
  12323. *
  12324. * @private
  12325. * @param {Object} object The object to query.
  12326. * @param {string} key The key of the method to get.
  12327. * @returns {*} Returns the function if it's native, else `undefined`.
  12328. */
  12329. function getNative(object, key) {
  12330. var value = object == null ? undefined : object[key];
  12331. return isNative(value) ? value : undefined;
  12332. }
  12333. /**
  12334. * Checks if `value` is classified as a `Function` object.
  12335. *
  12336. * @static
  12337. * @memberOf _
  12338. * @category Lang
  12339. * @param {*} value The value to check.
  12340. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  12341. * @example
  12342. *
  12343. * _.isFunction(_);
  12344. * // => true
  12345. *
  12346. * _.isFunction(/abc/);
  12347. * // => false
  12348. */
  12349. function isFunction(value) {
  12350. // The use of `Object#toString` avoids issues with the `typeof` operator
  12351. // in older versions of Chrome and Safari which return 'function' for regexes
  12352. // and Safari 8 equivalents which return 'object' for typed array constructors.
  12353. return isObject(value) && objToString.call(value) == funcTag;
  12354. }
  12355. /**
  12356. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  12357. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  12358. *
  12359. * @static
  12360. * @memberOf _
  12361. * @category Lang
  12362. * @param {*} value The value to check.
  12363. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  12364. * @example
  12365. *
  12366. * _.isObject({});
  12367. * // => true
  12368. *
  12369. * _.isObject([1, 2, 3]);
  12370. * // => true
  12371. *
  12372. * _.isObject(1);
  12373. * // => false
  12374. */
  12375. function isObject(value) {
  12376. // Avoid a V8 JIT bug in Chrome 19-20.
  12377. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  12378. var type = typeof value;
  12379. return !!value && (type == 'object' || type == 'function');
  12380. }
  12381. /**
  12382. * Checks if `value` is a native function.
  12383. *
  12384. * @static
  12385. * @memberOf _
  12386. * @category Lang
  12387. * @param {*} value The value to check.
  12388. * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
  12389. * @example
  12390. *
  12391. * _.isNative(Array.prototype.push);
  12392. * // => true
  12393. *
  12394. * _.isNative(_);
  12395. * // => false
  12396. */
  12397. function isNative(value) {
  12398. if (value == null) {
  12399. return false;
  12400. }
  12401. if (isFunction(value)) {
  12402. return reIsNative.test(fnToString.call(value));
  12403. }
  12404. return isObjectLike(value) && reIsHostCtor.test(value);
  12405. }
  12406. module.exports = getNative;
  12407. },{}],55:[function(_dereq_,module,exports){
  12408. /**
  12409. * lodash 3.0.8 (Custom Build) <https://lodash.com/>
  12410. * Build: `lodash modularize exports="npm" -o ./`
  12411. * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
  12412. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12413. * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12414. * Available under MIT license <https://lodash.com/license>
  12415. */
  12416. /** Used as references for various `Number` constants. */
  12417. var MAX_SAFE_INTEGER = 9007199254740991;
  12418. /** `Object#toString` result references. */
  12419. var argsTag = '[object Arguments]',
  12420. funcTag = '[object Function]',
  12421. genTag = '[object GeneratorFunction]';
  12422. /** Used for built-in method references. */
  12423. var objectProto = Object.prototype;
  12424. /** Used to check objects for own properties. */
  12425. var hasOwnProperty = objectProto.hasOwnProperty;
  12426. /**
  12427. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  12428. * of values.
  12429. */
  12430. var objectToString = objectProto.toString;
  12431. /** Built-in value references. */
  12432. var propertyIsEnumerable = objectProto.propertyIsEnumerable;
  12433. /**
  12434. * The base implementation of `_.property` without support for deep paths.
  12435. *
  12436. * @private
  12437. * @param {string} key The key of the property to get.
  12438. * @returns {Function} Returns the new function.
  12439. */
  12440. function baseProperty(key) {
  12441. return function(object) {
  12442. return object == null ? undefined : object[key];
  12443. };
  12444. }
  12445. /**
  12446. * Gets the "length" property value of `object`.
  12447. *
  12448. * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
  12449. * that affects Safari on at least iOS 8.1-8.3 ARM64.
  12450. *
  12451. * @private
  12452. * @param {Object} object The object to query.
  12453. * @returns {*} Returns the "length" value.
  12454. */
  12455. var getLength = baseProperty('length');
  12456. /**
  12457. * Checks if `value` is likely an `arguments` object.
  12458. *
  12459. * @static
  12460. * @memberOf _
  12461. * @category Lang
  12462. * @param {*} value The value to check.
  12463. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  12464. * @example
  12465. *
  12466. * _.isArguments(function() { return arguments; }());
  12467. * // => true
  12468. *
  12469. * _.isArguments([1, 2, 3]);
  12470. * // => false
  12471. */
  12472. function isArguments(value) {
  12473. // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
  12474. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
  12475. (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
  12476. }
  12477. /**
  12478. * Checks if `value` is array-like. A value is considered array-like if it's
  12479. * not a function and has a `value.length` that's an integer greater than or
  12480. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  12481. *
  12482. * @static
  12483. * @memberOf _
  12484. * @category Lang
  12485. * @param {*} value The value to check.
  12486. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  12487. * @example
  12488. *
  12489. * _.isArrayLike([1, 2, 3]);
  12490. * // => true
  12491. *
  12492. * _.isArrayLike(document.body.children);
  12493. * // => true
  12494. *
  12495. * _.isArrayLike('abc');
  12496. * // => true
  12497. *
  12498. * _.isArrayLike(_.noop);
  12499. * // => false
  12500. */
  12501. function isArrayLike(value) {
  12502. return value != null && isLength(getLength(value)) && !isFunction(value);
  12503. }
  12504. /**
  12505. * This method is like `_.isArrayLike` except that it also checks if `value`
  12506. * is an object.
  12507. *
  12508. * @static
  12509. * @memberOf _
  12510. * @category Lang
  12511. * @param {*} value The value to check.
  12512. * @returns {boolean} Returns `true` if `value` is an array-like object, else `false`.
  12513. * @example
  12514. *
  12515. * _.isArrayLikeObject([1, 2, 3]);
  12516. * // => true
  12517. *
  12518. * _.isArrayLikeObject(document.body.children);
  12519. * // => true
  12520. *
  12521. * _.isArrayLikeObject('abc');
  12522. * // => false
  12523. *
  12524. * _.isArrayLikeObject(_.noop);
  12525. * // => false
  12526. */
  12527. function isArrayLikeObject(value) {
  12528. return isObjectLike(value) && isArrayLike(value);
  12529. }
  12530. /**
  12531. * Checks if `value` is classified as a `Function` object.
  12532. *
  12533. * @static
  12534. * @memberOf _
  12535. * @category Lang
  12536. * @param {*} value The value to check.
  12537. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  12538. * @example
  12539. *
  12540. * _.isFunction(_);
  12541. * // => true
  12542. *
  12543. * _.isFunction(/abc/);
  12544. * // => false
  12545. */
  12546. function isFunction(value) {
  12547. // The use of `Object#toString` avoids issues with the `typeof` operator
  12548. // in Safari 8 which returns 'object' for typed array and weak map constructors,
  12549. // and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
  12550. var tag = isObject(value) ? objectToString.call(value) : '';
  12551. return tag == funcTag || tag == genTag;
  12552. }
  12553. /**
  12554. * Checks if `value` is a valid array-like length.
  12555. *
  12556. * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  12557. *
  12558. * @static
  12559. * @memberOf _
  12560. * @category Lang
  12561. * @param {*} value The value to check.
  12562. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  12563. * @example
  12564. *
  12565. * _.isLength(3);
  12566. * // => true
  12567. *
  12568. * _.isLength(Number.MIN_VALUE);
  12569. * // => false
  12570. *
  12571. * _.isLength(Infinity);
  12572. * // => false
  12573. *
  12574. * _.isLength('3');
  12575. * // => false
  12576. */
  12577. function isLength(value) {
  12578. return typeof value == 'number' &&
  12579. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  12580. }
  12581. /**
  12582. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  12583. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  12584. *
  12585. * @static
  12586. * @memberOf _
  12587. * @category Lang
  12588. * @param {*} value The value to check.
  12589. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  12590. * @example
  12591. *
  12592. * _.isObject({});
  12593. * // => true
  12594. *
  12595. * _.isObject([1, 2, 3]);
  12596. * // => true
  12597. *
  12598. * _.isObject(_.noop);
  12599. * // => true
  12600. *
  12601. * _.isObject(null);
  12602. * // => false
  12603. */
  12604. function isObject(value) {
  12605. var type = typeof value;
  12606. return !!value && (type == 'object' || type == 'function');
  12607. }
  12608. /**
  12609. * Checks if `value` is object-like. A value is object-like if it's not `null`
  12610. * and has a `typeof` result of "object".
  12611. *
  12612. * @static
  12613. * @memberOf _
  12614. * @category Lang
  12615. * @param {*} value The value to check.
  12616. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  12617. * @example
  12618. *
  12619. * _.isObjectLike({});
  12620. * // => true
  12621. *
  12622. * _.isObjectLike([1, 2, 3]);
  12623. * // => true
  12624. *
  12625. * _.isObjectLike(_.noop);
  12626. * // => false
  12627. *
  12628. * _.isObjectLike(null);
  12629. * // => false
  12630. */
  12631. function isObjectLike(value) {
  12632. return !!value && typeof value == 'object';
  12633. }
  12634. module.exports = isArguments;
  12635. },{}],56:[function(_dereq_,module,exports){
  12636. /**
  12637. * lodash 3.0.4 (Custom Build) <https://lodash.com/>
  12638. * Build: `lodash modern modularize exports="npm" -o ./`
  12639. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  12640. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12641. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12642. * Available under MIT license <https://lodash.com/license>
  12643. */
  12644. /** `Object#toString` result references. */
  12645. var arrayTag = '[object Array]',
  12646. funcTag = '[object Function]';
  12647. /** Used to detect host constructors (Safari > 5). */
  12648. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  12649. /**
  12650. * Checks if `value` is object-like.
  12651. *
  12652. * @private
  12653. * @param {*} value The value to check.
  12654. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  12655. */
  12656. function isObjectLike(value) {
  12657. return !!value && typeof value == 'object';
  12658. }
  12659. /** Used for native method references. */
  12660. var objectProto = Object.prototype;
  12661. /** Used to resolve the decompiled source of functions. */
  12662. var fnToString = Function.prototype.toString;
  12663. /** Used to check objects for own properties. */
  12664. var hasOwnProperty = objectProto.hasOwnProperty;
  12665. /**
  12666. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  12667. * of values.
  12668. */
  12669. var objToString = objectProto.toString;
  12670. /** Used to detect if a method is native. */
  12671. var reIsNative = RegExp('^' +
  12672. fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
  12673. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  12674. );
  12675. /* Native method references for those with the same name as other `lodash` methods. */
  12676. var nativeIsArray = getNative(Array, 'isArray');
  12677. /**
  12678. * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
  12679. * of an array-like value.
  12680. */
  12681. var MAX_SAFE_INTEGER = 9007199254740991;
  12682. /**
  12683. * Gets the native function at `key` of `object`.
  12684. *
  12685. * @private
  12686. * @param {Object} object The object to query.
  12687. * @param {string} key The key of the method to get.
  12688. * @returns {*} Returns the function if it's native, else `undefined`.
  12689. */
  12690. function getNative(object, key) {
  12691. var value = object == null ? undefined : object[key];
  12692. return isNative(value) ? value : undefined;
  12693. }
  12694. /**
  12695. * Checks if `value` is a valid array-like length.
  12696. *
  12697. * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  12698. *
  12699. * @private
  12700. * @param {*} value The value to check.
  12701. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  12702. */
  12703. function isLength(value) {
  12704. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  12705. }
  12706. /**
  12707. * Checks if `value` is classified as an `Array` object.
  12708. *
  12709. * @static
  12710. * @memberOf _
  12711. * @category Lang
  12712. * @param {*} value The value to check.
  12713. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  12714. * @example
  12715. *
  12716. * _.isArray([1, 2, 3]);
  12717. * // => true
  12718. *
  12719. * _.isArray(function() { return arguments; }());
  12720. * // => false
  12721. */
  12722. var isArray = nativeIsArray || function(value) {
  12723. return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
  12724. };
  12725. /**
  12726. * Checks if `value` is classified as a `Function` object.
  12727. *
  12728. * @static
  12729. * @memberOf _
  12730. * @category Lang
  12731. * @param {*} value The value to check.
  12732. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  12733. * @example
  12734. *
  12735. * _.isFunction(_);
  12736. * // => true
  12737. *
  12738. * _.isFunction(/abc/);
  12739. * // => false
  12740. */
  12741. function isFunction(value) {
  12742. // The use of `Object#toString` avoids issues with the `typeof` operator
  12743. // in older versions of Chrome and Safari which return 'function' for regexes
  12744. // and Safari 8 equivalents which return 'object' for typed array constructors.
  12745. return isObject(value) && objToString.call(value) == funcTag;
  12746. }
  12747. /**
  12748. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  12749. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  12750. *
  12751. * @static
  12752. * @memberOf _
  12753. * @category Lang
  12754. * @param {*} value The value to check.
  12755. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  12756. * @example
  12757. *
  12758. * _.isObject({});
  12759. * // => true
  12760. *
  12761. * _.isObject([1, 2, 3]);
  12762. * // => true
  12763. *
  12764. * _.isObject(1);
  12765. * // => false
  12766. */
  12767. function isObject(value) {
  12768. // Avoid a V8 JIT bug in Chrome 19-20.
  12769. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  12770. var type = typeof value;
  12771. return !!value && (type == 'object' || type == 'function');
  12772. }
  12773. /**
  12774. * Checks if `value` is a native function.
  12775. *
  12776. * @static
  12777. * @memberOf _
  12778. * @category Lang
  12779. * @param {*} value The value to check.
  12780. * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
  12781. * @example
  12782. *
  12783. * _.isNative(Array.prototype.push);
  12784. * // => true
  12785. *
  12786. * _.isNative(_);
  12787. * // => false
  12788. */
  12789. function isNative(value) {
  12790. if (value == null) {
  12791. return false;
  12792. }
  12793. if (isFunction(value)) {
  12794. return reIsNative.test(fnToString.call(value));
  12795. }
  12796. return isObjectLike(value) && reIsHostCtor.test(value);
  12797. }
  12798. module.exports = isArray;
  12799. },{}],57:[function(_dereq_,module,exports){
  12800. /**
  12801. * lodash 3.2.0 (Custom Build) <https://lodash.com/>
  12802. * Build: `lodash modern modularize exports="npm" -o ./`
  12803. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  12804. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12805. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12806. * Available under MIT license <https://lodash.com/license>
  12807. */
  12808. var baseFor = _dereq_('lodash._basefor'),
  12809. isArguments = _dereq_('lodash.isarguments'),
  12810. keysIn = _dereq_('lodash.keysin');
  12811. /** `Object#toString` result references. */
  12812. var objectTag = '[object Object]';
  12813. /**
  12814. * Checks if `value` is object-like.
  12815. *
  12816. * @private
  12817. * @param {*} value The value to check.
  12818. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  12819. */
  12820. function isObjectLike(value) {
  12821. return !!value && typeof value == 'object';
  12822. }
  12823. /** Used for native method references. */
  12824. var objectProto = Object.prototype;
  12825. /** Used to check objects for own properties. */
  12826. var hasOwnProperty = objectProto.hasOwnProperty;
  12827. /**
  12828. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  12829. * of values.
  12830. */
  12831. var objToString = objectProto.toString;
  12832. /**
  12833. * The base implementation of `_.forIn` without support for callback
  12834. * shorthands and `this` binding.
  12835. *
  12836. * @private
  12837. * @param {Object} object The object to iterate over.
  12838. * @param {Function} iteratee The function invoked per iteration.
  12839. * @returns {Object} Returns `object`.
  12840. */
  12841. function baseForIn(object, iteratee) {
  12842. return baseFor(object, iteratee, keysIn);
  12843. }
  12844. /**
  12845. * Checks if `value` is a plain object, that is, an object created by the
  12846. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  12847. *
  12848. * **Note:** This method assumes objects created by the `Object` constructor
  12849. * have no inherited enumerable properties.
  12850. *
  12851. * @static
  12852. * @memberOf _
  12853. * @category Lang
  12854. * @param {*} value The value to check.
  12855. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  12856. * @example
  12857. *
  12858. * function Foo() {
  12859. * this.a = 1;
  12860. * }
  12861. *
  12862. * _.isPlainObject(new Foo);
  12863. * // => false
  12864. *
  12865. * _.isPlainObject([1, 2, 3]);
  12866. * // => false
  12867. *
  12868. * _.isPlainObject({ 'x': 0, 'y': 0 });
  12869. * // => true
  12870. *
  12871. * _.isPlainObject(Object.create(null));
  12872. * // => true
  12873. */
  12874. function isPlainObject(value) {
  12875. var Ctor;
  12876. // Exit early for non `Object` objects.
  12877. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
  12878. (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
  12879. return false;
  12880. }
  12881. // IE < 9 iterates inherited properties before own properties. If the first
  12882. // iterated property is an object's own property then there are no inherited
  12883. // enumerable properties.
  12884. var result;
  12885. // In most environments an object's own properties are iterated before
  12886. // its inherited properties. If the last iterated property is an object's
  12887. // own property then there are no inherited enumerable properties.
  12888. baseForIn(value, function(subValue, key) {
  12889. result = key;
  12890. });
  12891. return result === undefined || hasOwnProperty.call(value, result);
  12892. }
  12893. module.exports = isPlainObject;
  12894. },{"lodash._basefor":58,"lodash.isarguments":55,"lodash.keysin":61}],58:[function(_dereq_,module,exports){
  12895. /**
  12896. * lodash 3.0.3 (Custom Build) <https://lodash.com/>
  12897. * Build: `lodash modularize exports="npm" -o ./`
  12898. * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
  12899. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12900. * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12901. * Available under MIT license <https://lodash.com/license>
  12902. */
  12903. /**
  12904. * The base implementation of `baseForIn` and `baseForOwn` which iterates
  12905. * over `object` properties returned by `keysFunc` invoking `iteratee` for
  12906. * each property. Iteratee functions may exit iteration early by explicitly
  12907. * returning `false`.
  12908. *
  12909. * @private
  12910. * @param {Object} object The object to iterate over.
  12911. * @param {Function} iteratee The function invoked per iteration.
  12912. * @param {Function} keysFunc The function to get the keys of `object`.
  12913. * @returns {Object} Returns `object`.
  12914. */
  12915. var baseFor = createBaseFor();
  12916. /**
  12917. * Creates a base function for methods like `_.forIn`.
  12918. *
  12919. * @private
  12920. * @param {boolean} [fromRight] Specify iterating from right to left.
  12921. * @returns {Function} Returns the new base function.
  12922. */
  12923. function createBaseFor(fromRight) {
  12924. return function(object, iteratee, keysFunc) {
  12925. var index = -1,
  12926. iterable = Object(object),
  12927. props = keysFunc(object),
  12928. length = props.length;
  12929. while (length--) {
  12930. var key = props[fromRight ? length : ++index];
  12931. if (iteratee(iterable[key], key, iterable) === false) {
  12932. break;
  12933. }
  12934. }
  12935. return object;
  12936. };
  12937. }
  12938. module.exports = baseFor;
  12939. },{}],59:[function(_dereq_,module,exports){
  12940. /**
  12941. * lodash 3.0.6 (Custom Build) <https://lodash.com/>
  12942. * Build: `lodash modularize exports="npm" -o ./`
  12943. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  12944. * Released under MIT license <https://lodash.com/license>
  12945. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12946. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12947. */
  12948. /** Used as references for various `Number` constants. */
  12949. var MAX_SAFE_INTEGER = 9007199254740991;
  12950. /** `Object#toString` result references. */
  12951. var argsTag = '[object Arguments]',
  12952. arrayTag = '[object Array]',
  12953. boolTag = '[object Boolean]',
  12954. dateTag = '[object Date]',
  12955. errorTag = '[object Error]',
  12956. funcTag = '[object Function]',
  12957. mapTag = '[object Map]',
  12958. numberTag = '[object Number]',
  12959. objectTag = '[object Object]',
  12960. regexpTag = '[object RegExp]',
  12961. setTag = '[object Set]',
  12962. stringTag = '[object String]',
  12963. weakMapTag = '[object WeakMap]';
  12964. var arrayBufferTag = '[object ArrayBuffer]',
  12965. dataViewTag = '[object DataView]',
  12966. float32Tag = '[object Float32Array]',
  12967. float64Tag = '[object Float64Array]',
  12968. int8Tag = '[object Int8Array]',
  12969. int16Tag = '[object Int16Array]',
  12970. int32Tag = '[object Int32Array]',
  12971. uint8Tag = '[object Uint8Array]',
  12972. uint8ClampedTag = '[object Uint8ClampedArray]',
  12973. uint16Tag = '[object Uint16Array]',
  12974. uint32Tag = '[object Uint32Array]';
  12975. /** Used to identify `toStringTag` values of typed arrays. */
  12976. var typedArrayTags = {};
  12977. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  12978. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  12979. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  12980. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  12981. typedArrayTags[uint32Tag] = true;
  12982. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  12983. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  12984. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  12985. typedArrayTags[errorTag] = typedArrayTags[funcTag] =
  12986. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  12987. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  12988. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  12989. typedArrayTags[weakMapTag] = false;
  12990. /** Used for built-in method references. */
  12991. var objectProto = Object.prototype;
  12992. /**
  12993. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  12994. * of values.
  12995. */
  12996. var objectToString = objectProto.toString;
  12997. /**
  12998. * Checks if `value` is a valid array-like length.
  12999. *
  13000. * **Note:** This function is loosely based on
  13001. * [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  13002. *
  13003. * @static
  13004. * @memberOf _
  13005. * @since 4.0.0
  13006. * @category Lang
  13007. * @param {*} value The value to check.
  13008. * @returns {boolean} Returns `true` if `value` is a valid length,
  13009. * else `false`.
  13010. * @example
  13011. *
  13012. * _.isLength(3);
  13013. * // => true
  13014. *
  13015. * _.isLength(Number.MIN_VALUE);
  13016. * // => false
  13017. *
  13018. * _.isLength(Infinity);
  13019. * // => false
  13020. *
  13021. * _.isLength('3');
  13022. * // => false
  13023. */
  13024. function isLength(value) {
  13025. return typeof value == 'number' &&
  13026. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  13027. }
  13028. /**
  13029. * Checks if `value` is object-like. A value is object-like if it's not `null`
  13030. * and has a `typeof` result of "object".
  13031. *
  13032. * @static
  13033. * @memberOf _
  13034. * @since 4.0.0
  13035. * @category Lang
  13036. * @param {*} value The value to check.
  13037. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  13038. * @example
  13039. *
  13040. * _.isObjectLike({});
  13041. * // => true
  13042. *
  13043. * _.isObjectLike([1, 2, 3]);
  13044. * // => true
  13045. *
  13046. * _.isObjectLike(_.noop);
  13047. * // => false
  13048. *
  13049. * _.isObjectLike(null);
  13050. * // => false
  13051. */
  13052. function isObjectLike(value) {
  13053. return !!value && typeof value == 'object';
  13054. }
  13055. /**
  13056. * Checks if `value` is classified as a typed array.
  13057. *
  13058. * @static
  13059. * @memberOf _
  13060. * @since 3.0.0
  13061. * @category Lang
  13062. * @param {*} value The value to check.
  13063. * @returns {boolean} Returns `true` if `value` is correctly classified,
  13064. * else `false`.
  13065. * @example
  13066. *
  13067. * _.isTypedArray(new Uint8Array);
  13068. * // => true
  13069. *
  13070. * _.isTypedArray([]);
  13071. * // => false
  13072. */
  13073. function isTypedArray(value) {
  13074. return isObjectLike(value) &&
  13075. isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
  13076. }
  13077. module.exports = isTypedArray;
  13078. },{}],60:[function(_dereq_,module,exports){
  13079. /**
  13080. * lodash 3.1.2 (Custom Build) <https://lodash.com/>
  13081. * Build: `lodash modern modularize exports="npm" -o ./`
  13082. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  13083. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  13084. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  13085. * Available under MIT license <https://lodash.com/license>
  13086. */
  13087. var getNative = _dereq_('lodash._getnative'),
  13088. isArguments = _dereq_('lodash.isarguments'),
  13089. isArray = _dereq_('lodash.isarray');
  13090. /** Used to detect unsigned integer values. */
  13091. var reIsUint = /^\d+$/;
  13092. /** Used for native method references. */
  13093. var objectProto = Object.prototype;
  13094. /** Used to check objects for own properties. */
  13095. var hasOwnProperty = objectProto.hasOwnProperty;
  13096. /* Native method references for those with the same name as other `lodash` methods. */
  13097. var nativeKeys = getNative(Object, 'keys');
  13098. /**
  13099. * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
  13100. * of an array-like value.
  13101. */
  13102. var MAX_SAFE_INTEGER = 9007199254740991;
  13103. /**
  13104. * The base implementation of `_.property` without support for deep paths.
  13105. *
  13106. * @private
  13107. * @param {string} key The key of the property to get.
  13108. * @returns {Function} Returns the new function.
  13109. */
  13110. function baseProperty(key) {
  13111. return function(object) {
  13112. return object == null ? undefined : object[key];
  13113. };
  13114. }
  13115. /**
  13116. * Gets the "length" property value of `object`.
  13117. *
  13118. * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
  13119. * that affects Safari on at least iOS 8.1-8.3 ARM64.
  13120. *
  13121. * @private
  13122. * @param {Object} object The object to query.
  13123. * @returns {*} Returns the "length" value.
  13124. */
  13125. var getLength = baseProperty('length');
  13126. /**
  13127. * Checks if `value` is array-like.
  13128. *
  13129. * @private
  13130. * @param {*} value The value to check.
  13131. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  13132. */
  13133. function isArrayLike(value) {
  13134. return value != null && isLength(getLength(value));
  13135. }
  13136. /**
  13137. * Checks if `value` is a valid array-like index.
  13138. *
  13139. * @private
  13140. * @param {*} value The value to check.
  13141. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  13142. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  13143. */
  13144. function isIndex(value, length) {
  13145. value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
  13146. length = length == null ? MAX_SAFE_INTEGER : length;
  13147. return value > -1 && value % 1 == 0 && value < length;
  13148. }
  13149. /**
  13150. * Checks if `value` is a valid array-like length.
  13151. *
  13152. * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  13153. *
  13154. * @private
  13155. * @param {*} value The value to check.
  13156. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  13157. */
  13158. function isLength(value) {
  13159. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  13160. }
  13161. /**
  13162. * A fallback implementation of `Object.keys` which creates an array of the
  13163. * own enumerable property names of `object`.
  13164. *
  13165. * @private
  13166. * @param {Object} object The object to query.
  13167. * @returns {Array} Returns the array of property names.
  13168. */
  13169. function shimKeys(object) {
  13170. var props = keysIn(object),
  13171. propsLength = props.length,
  13172. length = propsLength && object.length;
  13173. var allowIndexes = !!length && isLength(length) &&
  13174. (isArray(object) || isArguments(object));
  13175. var index = -1,
  13176. result = [];
  13177. while (++index < propsLength) {
  13178. var key = props[index];
  13179. if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
  13180. result.push(key);
  13181. }
  13182. }
  13183. return result;
  13184. }
  13185. /**
  13186. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  13187. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  13188. *
  13189. * @static
  13190. * @memberOf _
  13191. * @category Lang
  13192. * @param {*} value The value to check.
  13193. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  13194. * @example
  13195. *
  13196. * _.isObject({});
  13197. * // => true
  13198. *
  13199. * _.isObject([1, 2, 3]);
  13200. * // => true
  13201. *
  13202. * _.isObject(1);
  13203. * // => false
  13204. */
  13205. function isObject(value) {
  13206. // Avoid a V8 JIT bug in Chrome 19-20.
  13207. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  13208. var type = typeof value;
  13209. return !!value && (type == 'object' || type == 'function');
  13210. }
  13211. /**
  13212. * Creates an array of the own enumerable property names of `object`.
  13213. *
  13214. * **Note:** Non-object values are coerced to objects. See the
  13215. * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
  13216. * for more details.
  13217. *
  13218. * @static
  13219. * @memberOf _
  13220. * @category Object
  13221. * @param {Object} object The object to query.
  13222. * @returns {Array} Returns the array of property names.
  13223. * @example
  13224. *
  13225. * function Foo() {
  13226. * this.a = 1;
  13227. * this.b = 2;
  13228. * }
  13229. *
  13230. * Foo.prototype.c = 3;
  13231. *
  13232. * _.keys(new Foo);
  13233. * // => ['a', 'b'] (iteration order is not guaranteed)
  13234. *
  13235. * _.keys('hi');
  13236. * // => ['0', '1']
  13237. */
  13238. var keys = !nativeKeys ? shimKeys : function(object) {
  13239. var Ctor = object == null ? undefined : object.constructor;
  13240. if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
  13241. (typeof object != 'function' && isArrayLike(object))) {
  13242. return shimKeys(object);
  13243. }
  13244. return isObject(object) ? nativeKeys(object) : [];
  13245. };
  13246. /**
  13247. * Creates an array of the own and inherited enumerable property names of `object`.
  13248. *
  13249. * **Note:** Non-object values are coerced to objects.
  13250. *
  13251. * @static
  13252. * @memberOf _
  13253. * @category Object
  13254. * @param {Object} object The object to query.
  13255. * @returns {Array} Returns the array of property names.
  13256. * @example
  13257. *
  13258. * function Foo() {
  13259. * this.a = 1;
  13260. * this.b = 2;
  13261. * }
  13262. *
  13263. * Foo.prototype.c = 3;
  13264. *
  13265. * _.keysIn(new Foo);
  13266. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  13267. */
  13268. function keysIn(object) {
  13269. if (object == null) {
  13270. return [];
  13271. }
  13272. if (!isObject(object)) {
  13273. object = Object(object);
  13274. }
  13275. var length = object.length;
  13276. length = (length && isLength(length) &&
  13277. (isArray(object) || isArguments(object)) && length) || 0;
  13278. var Ctor = object.constructor,
  13279. index = -1,
  13280. isProto = typeof Ctor == 'function' && Ctor.prototype === object,
  13281. result = Array(length),
  13282. skipIndexes = length > 0;
  13283. while (++index < length) {
  13284. result[index] = (index + '');
  13285. }
  13286. for (var key in object) {
  13287. if (!(skipIndexes && isIndex(key, length)) &&
  13288. !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
  13289. result.push(key);
  13290. }
  13291. }
  13292. return result;
  13293. }
  13294. module.exports = keys;
  13295. },{"lodash._getnative":54,"lodash.isarguments":55,"lodash.isarray":56}],61:[function(_dereq_,module,exports){
  13296. /**
  13297. * lodash 3.0.8 (Custom Build) <https://lodash.com/>
  13298. * Build: `lodash modern modularize exports="npm" -o ./`
  13299. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  13300. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  13301. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  13302. * Available under MIT license <https://lodash.com/license>
  13303. */
  13304. var isArguments = _dereq_('lodash.isarguments'),
  13305. isArray = _dereq_('lodash.isarray');
  13306. /** Used to detect unsigned integer values. */
  13307. var reIsUint = /^\d+$/;
  13308. /** Used for native method references. */
  13309. var objectProto = Object.prototype;
  13310. /** Used to check objects for own properties. */
  13311. var hasOwnProperty = objectProto.hasOwnProperty;
  13312. /**
  13313. * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
  13314. * of an array-like value.
  13315. */
  13316. var MAX_SAFE_INTEGER = 9007199254740991;
  13317. /**
  13318. * Checks if `value` is a valid array-like index.
  13319. *
  13320. * @private
  13321. * @param {*} value The value to check.
  13322. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  13323. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  13324. */
  13325. function isIndex(value, length) {
  13326. value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
  13327. length = length == null ? MAX_SAFE_INTEGER : length;
  13328. return value > -1 && value % 1 == 0 && value < length;
  13329. }
  13330. /**
  13331. * Checks if `value` is a valid array-like length.
  13332. *
  13333. * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
  13334. *
  13335. * @private
  13336. * @param {*} value The value to check.
  13337. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  13338. */
  13339. function isLength(value) {
  13340. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  13341. }
  13342. /**
  13343. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  13344. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  13345. *
  13346. * @static
  13347. * @memberOf _
  13348. * @category Lang
  13349. * @param {*} value The value to check.
  13350. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  13351. * @example
  13352. *
  13353. * _.isObject({});
  13354. * // => true
  13355. *
  13356. * _.isObject([1, 2, 3]);
  13357. * // => true
  13358. *
  13359. * _.isObject(1);
  13360. * // => false
  13361. */
  13362. function isObject(value) {
  13363. // Avoid a V8 JIT bug in Chrome 19-20.
  13364. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  13365. var type = typeof value;
  13366. return !!value && (type == 'object' || type == 'function');
  13367. }
  13368. /**
  13369. * Creates an array of the own and inherited enumerable property names of `object`.
  13370. *
  13371. * **Note:** Non-object values are coerced to objects.
  13372. *
  13373. * @static
  13374. * @memberOf _
  13375. * @category Object
  13376. * @param {Object} object The object to query.
  13377. * @returns {Array} Returns the array of property names.
  13378. * @example
  13379. *
  13380. * function Foo() {
  13381. * this.a = 1;
  13382. * this.b = 2;
  13383. * }
  13384. *
  13385. * Foo.prototype.c = 3;
  13386. *
  13387. * _.keysIn(new Foo);
  13388. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  13389. */
  13390. function keysIn(object) {
  13391. if (object == null) {
  13392. return [];
  13393. }
  13394. if (!isObject(object)) {
  13395. object = Object(object);
  13396. }
  13397. var length = object.length;
  13398. length = (length && isLength(length) &&
  13399. (isArray(object) || isArguments(object)) && length) || 0;
  13400. var Ctor = object.constructor,
  13401. index = -1,
  13402. isProto = typeof Ctor == 'function' && Ctor.prototype === object,
  13403. result = Array(length),
  13404. skipIndexes = length > 0;
  13405. while (++index < length) {
  13406. result[index] = (index + '');
  13407. }
  13408. for (var key in object) {
  13409. if (!(skipIndexes && isIndex(key, length)) &&
  13410. !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
  13411. result.push(key);
  13412. }
  13413. }
  13414. return result;
  13415. }
  13416. module.exports = keysIn;
  13417. },{"lodash.isarguments":55,"lodash.isarray":56}],62:[function(_dereq_,module,exports){
  13418. /**
  13419. * lodash 3.0.0 (Custom Build) <https://lodash.com/>
  13420. * Build: `lodash modern modularize exports="npm" -o ./`
  13421. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  13422. * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
  13423. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  13424. * Available under MIT license <https://lodash.com/license>
  13425. */
  13426. var baseCopy = _dereq_('lodash._basecopy'),
  13427. keysIn = _dereq_('lodash.keysin');
  13428. /**
  13429. * Converts `value` to a plain object flattening inherited enumerable
  13430. * properties of `value` to own properties of the plain object.
  13431. *
  13432. * @static
  13433. * @memberOf _
  13434. * @category Lang
  13435. * @param {*} value The value to convert.
  13436. * @returns {Object} Returns the converted plain object.
  13437. * @example
  13438. *
  13439. * function Foo() {
  13440. * this.b = 2;
  13441. * }
  13442. *
  13443. * Foo.prototype.c = 3;
  13444. *
  13445. * _.assign({ 'a': 1 }, new Foo);
  13446. * // => { 'a': 1, 'b': 2 }
  13447. *
  13448. * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
  13449. * // => { 'a': 1, 'b': 2, 'c': 3 }
  13450. */
  13451. function toPlainObject(value) {
  13452. return baseCopy(value, keysIn(value));
  13453. }
  13454. module.exports = toPlainObject;
  13455. },{"lodash._basecopy":63,"lodash.keysin":61}],63:[function(_dereq_,module,exports){
  13456. /**
  13457. * lodash 3.0.1 (Custom Build) <https://lodash.com/>
  13458. * Build: `lodash modern modularize exports="npm" -o ./`
  13459. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  13460. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  13461. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  13462. * Available under MIT license <https://lodash.com/license>
  13463. */
  13464. /**
  13465. * Copies properties of `source` to `object`.
  13466. *
  13467. * @private
  13468. * @param {Object} source The object to copy properties from.
  13469. * @param {Array} props The property names to copy.
  13470. * @param {Object} [object={}] The object to copy properties to.
  13471. * @returns {Object} Returns `object`.
  13472. */
  13473. function baseCopy(source, props, object) {
  13474. object || (object = {});
  13475. var index = -1,
  13476. length = props.length;
  13477. while (++index < length) {
  13478. var key = props[index];
  13479. object[key] = source[key];
  13480. }
  13481. return object;
  13482. }
  13483. module.exports = baseCopy;
  13484. },{}],64:[function(_dereq_,module,exports){
  13485. var JSZip, fs, internal;
  13486. JSZip = _dereq_('jszip');
  13487. internal = _dereq_('./internal');
  13488. module.exports = {
  13489. asBlob: function(html, options) {
  13490. var zip;
  13491. zip = new JSZip();
  13492. internal.addFiles(zip, html, options);
  13493. return internal.generateDocument(zip);
  13494. }
  13495. };
  13496. },{"./internal":65,"jszip":14}],65:[function(_dereq_,module,exports){
  13497. (function (global,Buffer){
  13498. var documentTemplate, fs, utils, _;
  13499. documentTemplate = _dereq_('./templates/document');
  13500. utils = _dereq_('./utils');
  13501. _ = {
  13502. merge: _dereq_('lodash.merge')
  13503. };
  13504. module.exports = {
  13505. generateDocument: function(zip) {
  13506. var buffer;
  13507. buffer = zip.generate({
  13508. type: 'arraybuffer'
  13509. });
  13510. if (global.Blob) {
  13511. return new Blob([buffer], {
  13512. type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  13513. });
  13514. } else if (global.Buffer) {
  13515. return new Buffer(new Uint8Array(buffer));
  13516. } else {
  13517. throw new Error("Neither Blob nor Buffer are accessible in this environment. " + "Consider adding Blob.js shim");
  13518. }
  13519. },
  13520. renderDocumentFile: function(documentOptions) {
  13521. var templateData;
  13522. if (documentOptions == null) {
  13523. documentOptions = {};
  13524. }
  13525. templateData = _.merge({
  13526. margins: {
  13527. top: 1440,
  13528. right: 1440,
  13529. bottom: 1440,
  13530. left: 1440,
  13531. header: 720,
  13532. footer: 720,
  13533. gutter: 0
  13534. }
  13535. }, (function() {
  13536. switch (documentOptions.orientation) {
  13537. case 'landscape':
  13538. return {
  13539. height: 12240,
  13540. width: 15840,
  13541. orient: 'landscape'
  13542. };
  13543. default:
  13544. return {
  13545. width: 12240,
  13546. height: 15840,
  13547. orient: 'portrait'
  13548. };
  13549. }
  13550. })(), {
  13551. margins: documentOptions.margins
  13552. });
  13553. return documentTemplate(templateData);
  13554. },
  13555. addFiles: function(zip, htmlSource, documentOptions) {
  13556. zip.file('[Content_Types].xml', Buffer("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/Pgo8VHlwZXMgeG1sbnM9Imh0dHA6Ly9zY2hlbWFzLm9wZW54bWxmb3JtYXRzLm9yZy9wYWNrYWdlLzIwMDYvY29udGVudC10eXBlcyI+CiAgPERlZmF1bHQgRXh0ZW5zaW9uPSJyZWxzIiBDb250ZW50VHlwZT0KICAgICJhcHBsaWNhdGlvbi92bmQub3BlbnhtbGZvcm1hdHMtcGFja2FnZS5yZWxhdGlvbnNoaXBzK3htbCIgLz4KICA8T3ZlcnJpZGUgUGFydE5hbWU9Ii93b3JkL2RvY3VtZW50LnhtbCIgQ29udGVudFR5cGU9CiAgICAiYXBwbGljYXRpb24vdm5kLm9wZW54bWxmb3JtYXRzLW9mZmljZWRvY3VtZW50LndvcmRwcm9jZXNzaW5nbWwuZG9jdW1lbnQubWFpbit4bWwiLz4KICA8T3ZlcnJpZGUgUGFydE5hbWU9Ii93b3JkL2FmY2h1bmsubWh0IiBDb250ZW50VHlwZT0ibWVzc2FnZS9yZmM4MjIiLz4KPC9UeXBlcz4K","base64"));
  13557. zip.folder('_rels').file('.rels', Buffer("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/Pgo8UmVsYXRpb25zaGlwcyB4bWxucz0iaHR0cDovL3NjaGVtYXMub3BlbnhtbGZvcm1hdHMub3JnL3BhY2thZ2UvMjAwNi9yZWxhdGlvbnNoaXBzIj4KICA8UmVsYXRpb25zaGlwCiAgICAgIFR5cGU9Imh0dHA6Ly9zY2hlbWFzLm9wZW54bWxmb3JtYXRzLm9yZy9vZmZpY2VEb2N1bWVudC8yMDA2L3JlbGF0aW9uc2hpcHMvb2ZmaWNlRG9jdW1lbnQiCiAgICAgIFRhcmdldD0iL3dvcmQvZG9jdW1lbnQueG1sIiBJZD0iUjA5YzgzZmFmYzA2NzQ4OGUiIC8+CjwvUmVsYXRpb25zaGlwcz4K","base64"));
  13558. return zip.folder('word').file('document.xml', this.renderDocumentFile(documentOptions)).file('afchunk.mht', utils.getMHTdocument(htmlSource)).folder('_rels').file('document.xml.rels', Buffer("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/Pgo8UmVsYXRpb25zaGlwcyB4bWxucz0iaHR0cDovL3NjaGVtYXMub3BlbnhtbGZvcm1hdHMub3JnL3BhY2thZ2UvMjAwNi9yZWxhdGlvbnNoaXBzIj4KICA8UmVsYXRpb25zaGlwIFR5cGU9Imh0dHA6Ly9zY2hlbWFzLm9wZW54bWxmb3JtYXRzLm9yZy9vZmZpY2VEb2N1bWVudC8yMDA2L3JlbGF0aW9uc2hpcHMvYUZDaHVuayIKICAgIFRhcmdldD0iL3dvcmQvYWZjaHVuay5taHQiIElkPSJodG1sQ2h1bmsiIC8+CjwvUmVsYXRpb25zaGlwcz4K","base64"));
  13559. }
  13560. };
  13561. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer)
  13562. },{"./templates/document":66,"./utils":69,"buffer":1,"lodash.merge":47}],66:[function(_dereq_,module,exports){
  13563. var _ = {escape: _dereq_("lodash.escape")};
  13564. module.exports = function(obj){
  13565. var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
  13566. with(obj||{}){
  13567. __p+='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<w:document\n xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"\n xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"\n xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"\n xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"\n xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"\n xmlns:ns6="http://schemas.openxmlformats.org/schemaLibrary/2006/main"\n xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"\n xmlns:ns8="http://schemas.openxmlformats.org/drawingml/2006/chartDrawing"\n xmlns:dgm="http://schemas.openxmlformats.org/drawingml/2006/diagram"\n xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"\n xmlns:ns11="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"\n xmlns:dsp="http://schemas.microsoft.com/office/drawing/2008/diagram"\n xmlns:ns13="urn:schemas-microsoft-com:office:excel"\n xmlns:o="urn:schemas-microsoft-com:office:office"\n xmlns:v="urn:schemas-microsoft-com:vml"\n xmlns:w10="urn:schemas-microsoft-com:office:word"\n xmlns:ns17="urn:schemas-microsoft-com:office:powerpoint"\n xmlns:odx="http://opendope.org/xpaths"\n xmlns:odc="http://opendope.org/conditions"\n xmlns:odq="http://opendope.org/questions"\n xmlns:odi="http://opendope.org/components"\n xmlns:odgm="http://opendope.org/SmartArt/DataHierarchy"\n xmlns:ns24="http://schemas.openxmlformats.org/officeDocument/2006/bibliography"\n xmlns:ns25="http://schemas.openxmlformats.org/drawingml/2006/compatibility"\n xmlns:ns26="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas">\n <w:body>\n <w:altChunk r:id="htmlChunk" />\n <w:sectPr>\n <w:pgSz w:w="'+
  13568. ((__t=( width ))==null?'':__t)+
  13569. '" w:h="'+
  13570. ((__t=( height ))==null?'':__t)+
  13571. '" w:orient="'+
  13572. ((__t=( orient ))==null?'':__t)+
  13573. '" />\n <w:pgMar w:top="'+
  13574. ((__t=( margins.top ))==null?'':__t)+
  13575. '"\n w:right="'+
  13576. ((__t=( margins.right ))==null?'':__t)+
  13577. '"\n w:bottom="'+
  13578. ((__t=( margins.bottom ))==null?'':__t)+
  13579. '"\n w:left="'+
  13580. ((__t=( margins.left ))==null?'':__t)+
  13581. '"\n w:header="'+
  13582. ((__t=( margins.header ))==null?'':__t)+
  13583. '"\n w:footer="'+
  13584. ((__t=( margins.footer ))==null?'':__t)+
  13585. '"\n w:gutter="'+
  13586. ((__t=( margins.gutter ))==null?'':__t)+
  13587. '"/>\n </w:sectPr>\n </w:body>\n</w:document>\n';
  13588. }
  13589. return __p;
  13590. };
  13591. },{"lodash.escape":45}],67:[function(_dereq_,module,exports){
  13592. var _ = {escape: _dereq_("lodash.escape")};
  13593. module.exports = function(obj){
  13594. var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
  13595. with(obj||{}){
  13596. __p+='MIME-Version: 1.0\nContent-Type: multipart/related;\n type="text/html";\n boundary="----=mhtDocumentPart"\n\n\n------=mhtDocumentPart\nContent-Type: text/html;\n charset="utf-8"\nContent-Transfer-Encoding: quoted-printable\nContent-Location: file:///C:/fake/document.html\n\n'+
  13597. ((__t=( htmlSource ))==null?'':__t)+
  13598. '\n\n'+
  13599. ((__t=( contentParts ))==null?'':__t)+
  13600. '\n\n------=mhtDocumentPart--\n';
  13601. }
  13602. return __p;
  13603. };
  13604. },{"lodash.escape":45}],68:[function(_dereq_,module,exports){
  13605. var _ = {escape: _dereq_("lodash.escape")};
  13606. module.exports = function(obj){
  13607. var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
  13608. with(obj||{}){
  13609. __p+='------=mhtDocumentPart\nContent-Type: '+
  13610. ((__t=( contentType ))==null?'':__t)+
  13611. '\nContent-Transfer-Encoding: '+
  13612. ((__t=( contentEncoding ))==null?'':__t)+
  13613. '\nContent-Location: '+
  13614. ((__t=( contentLocation ))==null?'':__t)+
  13615. '\n\n'+
  13616. ((__t=( encodedContent ))==null?'':__t)+
  13617. '\n';
  13618. }
  13619. return __p;
  13620. };
  13621. },{"lodash.escape":45}],69:[function(_dereq_,module,exports){
  13622. var mhtDocumentTemplate, mhtPartTemplate;
  13623. mhtDocumentTemplate = _dereq_('./templates/mht_document');
  13624. mhtPartTemplate = _dereq_('./templates/mht_part');
  13625. module.exports = {
  13626. getMHTdocument: function(htmlSource) {
  13627. var imageContentParts, _ref;
  13628. _ref = this._prepareImageParts(htmlSource), htmlSource = _ref.htmlSource, imageContentParts = _ref.imageContentParts;
  13629. htmlSource = htmlSource.replace(/\=/g, '=3D');
  13630. return mhtDocumentTemplate({
  13631. htmlSource: htmlSource,
  13632. contentParts: imageContentParts.join('\n')
  13633. });
  13634. },
  13635. _prepareImageParts: function(htmlSource) {
  13636. var imageContentParts, inlinedReplacer, inlinedSrcPattern;
  13637. imageContentParts = [];
  13638. inlinedSrcPattern = /"data:(\w+\/\w+);(\w+),(\S+)"/g;
  13639. inlinedReplacer = function(match, contentType, contentEncoding, encodedContent) {
  13640. var contentLocation, extension, index;
  13641. index = imageContentParts.length;
  13642. extension = contentType.split('/')[1];
  13643. contentLocation = "file:///C:/fake/image" + index + "." + extension;
  13644. imageContentParts.push(mhtPartTemplate({
  13645. contentType: contentType,
  13646. contentEncoding: contentEncoding,
  13647. contentLocation: contentLocation,
  13648. encodedContent: encodedContent
  13649. }));
  13650. return "\"" + contentLocation + "\"";
  13651. };
  13652. if (typeof htmlSource === 'string') {
  13653. if (!/<img/g.test(htmlSource)) {
  13654. return {
  13655. htmlSource: htmlSource,
  13656. imageContentParts: imageContentParts
  13657. };
  13658. }
  13659. htmlSource = htmlSource.replace(inlinedSrcPattern, inlinedReplacer);
  13660. return {
  13661. htmlSource: htmlSource,
  13662. imageContentParts: imageContentParts
  13663. };
  13664. } else {
  13665. throw new Error("Not a valid source provided!");
  13666. }
  13667. }
  13668. };
  13669. },{"./templates/mht_document":67,"./templates/mht_part":68}]},{},[64])
  13670. (64)
  13671. });
  13672. /***/ }),
  13673. /***/ "t4zo":
  13674. /***/ (function(module, exports, __webpack_require__) {
  13675. /* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function(a,b){if(true)!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (b),
  13676. __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
  13677. (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
  13678. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));else if("undefined"!=typeof exports)b();else{b(),a.FileSaver={exports:{}}.exports}})(this,function(){"use strict";function b(a,b){return"undefined"==typeof b?b={autoBom:!1}:"object"!=typeof b&&(console.warn("Deprecated: Expected third argument to be a object"),b={autoBom:!b}),b.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a}function c(a,b,c){var d=new XMLHttpRequest;d.open("GET",a),d.responseType="blob",d.onload=function(){g(d.response,b,c)},d.onerror=function(){console.error("could not download file")},d.send()}function d(a){var b=new XMLHttpRequest;b.open("HEAD",a,!1);try{b.send()}catch(a){}return 200<=b.status&&299>=b.status}function e(a){try{a.dispatchEvent(new MouseEvent("click"))}catch(c){var b=document.createEvent("MouseEvents");b.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),a.dispatchEvent(b)}}var f="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof global&&global.global===global?global:void 0,a=f.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),g=f.saveAs||("object"!=typeof window||window!==f?function(){}:"download"in HTMLAnchorElement.prototype&&!a?function(b,g,h){var i=f.URL||f.webkitURL,j=document.createElement("a");g=g||b.name||"download",j.download=g,j.rel="noopener","string"==typeof b?(j.href=b,j.origin===location.origin?e(j):d(j.href)?c(b,g,h):e(j,j.target="_blank")):(j.href=i.createObjectURL(b),setTimeout(function(){i.revokeObjectURL(j.href)},4E4),setTimeout(function(){e(j)},0))}:"msSaveOrOpenBlob"in navigator?function(f,g,h){if(g=g||f.name||"download","string"!=typeof f)navigator.msSaveOrOpenBlob(b(f,h),g);else if(d(f))c(f,g,h);else{var i=document.createElement("a");i.href=f,i.target="_blank",setTimeout(function(){e(i)})}}:function(b,d,e,g){if(g=g||open("","_blank"),g&&(g.document.title=g.document.body.innerText="downloading..."),"string"==typeof b)return c(b,d,e);var h="application/octet-stream"===b.type,i=/constructor/i.test(f.HTMLElement)||f.safari,j=/CriOS\/[\d]+/.test(navigator.userAgent);if((j||h&&i||a)&&"undefined"!=typeof FileReader){var k=new FileReader;k.onloadend=function(){var a=k.result;a=j?a:a.replace(/^data:[^;]*;/,"data:attachment/file;"),g?g.location.href=a:location=a,g=null},k.readAsDataURL(b)}else{var l=f.URL||f.webkitURL,m=l.createObjectURL(b);g?g.location=m:location.href=m,g=null,setTimeout(function(){l.revokeObjectURL(m)},4E4)}});f.saveAs=g.saveAs=g,"undefined"!=typeof module&&(module.exports=g)});
  13679. //# sourceMappingURL=FileSaver.min.js.map
  13680. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__("DuR2")))
  13681. /***/ })
  13682. });