完成签约之后直接添加人员,录入下发凭证
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.

20168 lines
647 KiB

  1. webpackJsonp([8],{
  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. /***/ "1taR":
  169. /***/ (function(module, exports) {
  170. // removed by extract-text-webpack-plugin
  171. /***/ }),
  172. /***/ "580I":
  173. /***/ (function(module, exports, __webpack_require__) {
  174. var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) {
  175. if (true) {
  176. // AMD. Register as an anonymous module unless amdModuleId is set
  177. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__("4kSj")], __WEBPACK_AMD_DEFINE_RESULT__ = (function (a0) {
  178. return (root['Module'] = factory(a0));
  179. }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
  180. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  181. } else if (typeof exports === 'object') {
  182. // Node. Does not work with strict CommonJS, but
  183. // only CommonJS-like environments that support module.exports,
  184. // like Node.
  185. module.exports = factory(require("jquery"));
  186. } else {
  187. root['SimpleModule'] = factory(jQuery);
  188. }
  189. }(this, function ($) {
  190. var Module,
  191. slice = [].slice;
  192. Module = (function() {
  193. Module.extend = function(obj) {
  194. var key, ref, val;
  195. if (!((obj != null) && typeof obj === 'object')) {
  196. return;
  197. }
  198. for (key in obj) {
  199. val = obj[key];
  200. if (key !== 'included' && key !== 'extended') {
  201. this[key] = val;
  202. }
  203. }
  204. return (ref = obj.extended) != null ? ref.call(this) : void 0;
  205. };
  206. Module.include = function(obj) {
  207. var key, ref, val;
  208. if (!((obj != null) && typeof obj === 'object')) {
  209. return;
  210. }
  211. for (key in obj) {
  212. val = obj[key];
  213. if (key !== 'included' && key !== 'extended') {
  214. this.prototype[key] = val;
  215. }
  216. }
  217. return (ref = obj.included) != null ? ref.call(this) : void 0;
  218. };
  219. Module.connect = function(cls) {
  220. if (typeof cls !== 'function') {
  221. return;
  222. }
  223. if (!cls.pluginName) {
  224. throw new Error('Module.connect: cannot connect plugin without pluginName');
  225. return;
  226. }
  227. cls.prototype._connected = true;
  228. if (!this._connectedClasses) {
  229. this._connectedClasses = [];
  230. }
  231. this._connectedClasses.push(cls);
  232. if (cls.pluginName) {
  233. return this[cls.pluginName] = cls;
  234. }
  235. };
  236. Module.prototype.opts = {};
  237. function Module(opts) {
  238. var base, cls, i, instance, instances, len, name;
  239. this.opts = $.extend({}, this.opts, opts);
  240. (base = this.constructor)._connectedClasses || (base._connectedClasses = []);
  241. instances = (function() {
  242. var i, len, ref, results;
  243. ref = this.constructor._connectedClasses;
  244. results = [];
  245. for (i = 0, len = ref.length; i < len; i++) {
  246. cls = ref[i];
  247. name = cls.pluginName.charAt(0).toLowerCase() + cls.pluginName.slice(1);
  248. if (cls.prototype._connected) {
  249. cls.prototype._module = this;
  250. }
  251. results.push(this[name] = new cls());
  252. }
  253. return results;
  254. }).call(this);
  255. if (this._connected) {
  256. this.opts = $.extend({}, this.opts, this._module.opts);
  257. } else {
  258. this._init();
  259. for (i = 0, len = instances.length; i < len; i++) {
  260. instance = instances[i];
  261. if (typeof instance._init === "function") {
  262. instance._init();
  263. }
  264. }
  265. }
  266. this.trigger('initialized');
  267. }
  268. Module.prototype._init = function() {};
  269. Module.prototype.on = function() {
  270. var args, ref;
  271. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  272. (ref = $(this)).on.apply(ref, args);
  273. return this;
  274. };
  275. Module.prototype.one = function() {
  276. var args, ref;
  277. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  278. (ref = $(this)).one.apply(ref, args);
  279. return this;
  280. };
  281. Module.prototype.off = function() {
  282. var args, ref;
  283. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  284. (ref = $(this)).off.apply(ref, args);
  285. return this;
  286. };
  287. Module.prototype.trigger = function() {
  288. var args, ref;
  289. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  290. (ref = $(this)).trigger.apply(ref, args);
  291. return this;
  292. };
  293. Module.prototype.triggerHandler = function() {
  294. var args, ref;
  295. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  296. return (ref = $(this)).triggerHandler.apply(ref, args);
  297. };
  298. Module.prototype._t = function() {
  299. var args, ref;
  300. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  301. return (ref = this.constructor)._t.apply(ref, args);
  302. };
  303. Module._t = function() {
  304. var args, key, ref, result;
  305. key = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
  306. result = ((ref = this.i18n[this.locale]) != null ? ref[key] : void 0) || '';
  307. if (!(args.length > 0)) {
  308. return result;
  309. }
  310. result = result.replace(/([^%]|^)%(?:(\d+)\$)?s/g, function(p0, p, position) {
  311. if (position) {
  312. return p + args[parseInt(position) - 1];
  313. } else {
  314. return p + args.shift();
  315. }
  316. });
  317. return result.replace(/%%s/g, '%s');
  318. };
  319. Module.i18n = {
  320. 'zh-CN': {}
  321. };
  322. Module.locale = 'zh-CN';
  323. return Module;
  324. })();
  325. return Module;
  326. }));
  327. /***/ }),
  328. /***/ "5IXW":
  329. /***/ (function(module, exports, __webpack_require__) {
  330. var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) {
  331. if (true) {
  332. // AMD. Register as an anonymous module unless amdModuleId is set
  333. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__("4kSj"),__webpack_require__("580I")], __WEBPACK_AMD_DEFINE_RESULT__ = (function ($, SimpleModule) {
  334. return (root['hotkeys'] = factory($, SimpleModule));
  335. }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
  336. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  337. } else if (typeof exports === 'object') {
  338. // Node. Does not work with strict CommonJS, but
  339. // only CommonJS-like environments that support module.exports,
  340. // like Node.
  341. module.exports = factory(require("jquery"),require("simple-module"));
  342. } else {
  343. root.simple = root.simple || {};
  344. root.simple['hotkeys'] = factory(jQuery,SimpleModule);
  345. }
  346. }(this, function ($, SimpleModule) {
  347. var Hotkeys, hotkeys,
  348. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  349. hasProp = {}.hasOwnProperty;
  350. Hotkeys = (function(superClass) {
  351. extend(Hotkeys, superClass);
  352. function Hotkeys() {
  353. return Hotkeys.__super__.constructor.apply(this, arguments);
  354. }
  355. Hotkeys.count = 0;
  356. Hotkeys.keyNameMap = {
  357. 8: "Backspace",
  358. 9: "Tab",
  359. 13: "Enter",
  360. 16: "Shift",
  361. 17: "Control",
  362. 18: "Alt",
  363. 19: "Pause",
  364. 20: "CapsLock",
  365. 27: "Esc",
  366. 32: "Spacebar",
  367. 33: "PageUp",
  368. 34: "PageDown",
  369. 35: "End",
  370. 36: "Home",
  371. 37: "Left",
  372. 38: "Up",
  373. 39: "Right",
  374. 40: "Down",
  375. 45: "Insert",
  376. 46: "Del",
  377. 91: "Meta",
  378. 93: "Meta",
  379. 48: "0",
  380. 49: "1",
  381. 50: "2",
  382. 51: "3",
  383. 52: "4",
  384. 53: "5",
  385. 54: "6",
  386. 55: "7",
  387. 56: "8",
  388. 57: "9",
  389. 65: "A",
  390. 66: "B",
  391. 67: "C",
  392. 68: "D",
  393. 69: "E",
  394. 70: "F",
  395. 71: "G",
  396. 72: "H",
  397. 73: "I",
  398. 74: "J",
  399. 75: "K",
  400. 76: "L",
  401. 77: "M",
  402. 78: "N",
  403. 79: "O",
  404. 80: "P",
  405. 81: "Q",
  406. 82: "R",
  407. 83: "S",
  408. 84: "T",
  409. 85: "U",
  410. 86: "V",
  411. 87: "W",
  412. 88: "X",
  413. 89: "Y",
  414. 90: "Z",
  415. 96: "0",
  416. 97: "1",
  417. 98: "2",
  418. 99: "3",
  419. 100: "4",
  420. 101: "5",
  421. 102: "6",
  422. 103: "7",
  423. 104: "8",
  424. 105: "9",
  425. 106: "Multiply",
  426. 107: "Add",
  427. 109: "Subtract",
  428. 110: "Decimal",
  429. 111: "Divide",
  430. 112: "F1",
  431. 113: "F2",
  432. 114: "F3",
  433. 115: "F4",
  434. 116: "F5",
  435. 117: "F6",
  436. 118: "F7",
  437. 119: "F8",
  438. 120: "F9",
  439. 121: "F10",
  440. 122: "F11",
  441. 123: "F12",
  442. 124: "F13",
  443. 125: "F14",
  444. 126: "F15",
  445. 127: "F16",
  446. 128: "F17",
  447. 129: "F18",
  448. 130: "F19",
  449. 131: "F20",
  450. 132: "F21",
  451. 133: "F22",
  452. 134: "F23",
  453. 135: "F24",
  454. 59: ";",
  455. 61: "=",
  456. 186: ";",
  457. 187: "=",
  458. 188: ",",
  459. 190: ".",
  460. 191: "/",
  461. 192: "`",
  462. 219: "[",
  463. 220: "\\",
  464. 221: "]",
  465. 222: "'"
  466. };
  467. Hotkeys.aliases = {
  468. "escape": "esc",
  469. "delete": "del",
  470. "return": "enter",
  471. "ctrl": "control",
  472. "space": "spacebar",
  473. "ins": "insert",
  474. "cmd": "meta",
  475. "command": "meta",
  476. "wins": "meta",
  477. "windows": "meta"
  478. };
  479. Hotkeys.normalize = function(shortcut) {
  480. var i, j, key, keyname, keys, len;
  481. keys = shortcut.toLowerCase().replace(/\s+/gi, "").split("+");
  482. for (i = j = 0, len = keys.length; j < len; i = ++j) {
  483. key = keys[i];
  484. keys[i] = this.aliases[key] || key;
  485. }
  486. keyname = keys.pop();
  487. keys.sort().push(keyname);
  488. return keys.join("_");
  489. };
  490. Hotkeys.prototype.opts = {
  491. el: document
  492. };
  493. Hotkeys.prototype._init = function() {
  494. this.id = ++this.constructor.count;
  495. this._map = {};
  496. this._delegate = typeof this.opts.el === "string" ? document : this.opts.el;
  497. return $(this._delegate).on("keydown.simple-hotkeys-" + this.id, this.opts.el, (function(_this) {
  498. return function(e) {
  499. var ref;
  500. return (ref = _this._getHander(e)) != null ? ref.call(_this, e) : void 0;
  501. };
  502. })(this));
  503. };
  504. Hotkeys.prototype._getHander = function(e) {
  505. var keyname, shortcut;
  506. if (!(keyname = this.constructor.keyNameMap[e.which])) {
  507. return;
  508. }
  509. shortcut = "";
  510. if (e.altKey) {
  511. shortcut += "alt_";
  512. }
  513. if (e.ctrlKey) {
  514. shortcut += "control_";
  515. }
  516. if (e.metaKey) {
  517. shortcut += "meta_";
  518. }
  519. if (e.shiftKey) {
  520. shortcut += "shift_";
  521. }
  522. shortcut += keyname.toLowerCase();
  523. return this._map[shortcut];
  524. };
  525. Hotkeys.prototype.respondTo = function(subject) {
  526. if (typeof subject === 'string') {
  527. return this._map[this.constructor.normalize(subject)] != null;
  528. } else {
  529. return this._getHander(subject) != null;
  530. }
  531. };
  532. Hotkeys.prototype.add = function(shortcut, handler) {
  533. this._map[this.constructor.normalize(shortcut)] = handler;
  534. return this;
  535. };
  536. Hotkeys.prototype.remove = function(shortcut) {
  537. delete this._map[this.constructor.normalize(shortcut)];
  538. return this;
  539. };
  540. Hotkeys.prototype.destroy = function() {
  541. $(this._delegate).off(".simple-hotkeys-" + this.id);
  542. this._map = {};
  543. return this;
  544. };
  545. return Hotkeys;
  546. })(SimpleModule);
  547. hotkeys = function(opts) {
  548. return new Hotkeys(opts);
  549. };
  550. return hotkeys;
  551. }));
  552. /***/ }),
  553. /***/ "Aba5":
  554. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  555. "use strict";
  556. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  557. // EXTERNAL MODULE: ./node_modules/babel-runtime/regenerator/index.js
  558. var regenerator = __webpack_require__("Xxa5");
  559. var regenerator_default = /*#__PURE__*/__webpack_require__.n(regenerator);
  560. // EXTERNAL MODULE: ./node_modules/babel-runtime/helpers/asyncToGenerator.js
  561. var asyncToGenerator = __webpack_require__("exGp");
  562. var asyncToGenerator_default = /*#__PURE__*/__webpack_require__.n(asyncToGenerator);
  563. // EXTERNAL MODULE: ./node_modules/file-saver/dist/FileSaver.min.js
  564. var FileSaver_min = __webpack_require__("t4zo");
  565. var FileSaver_min_default = /*#__PURE__*/__webpack_require__.n(FileSaver_min);
  566. // EXTERNAL MODULE: ./node_modules/html-docx-js/dist/html-docx.js
  567. var html_docx = __webpack_require__("U3YJ");
  568. var html_docx_default = /*#__PURE__*/__webpack_require__.n(html_docx);
  569. // EXTERNAL MODULE: ./src/components/contractTemplate/contractTemplate.vue + 2 modules
  570. var contractTemplate = __webpack_require__("+php");
  571. // EXTERNAL MODULE: ./node_modules/babel-runtime/core-js/object/assign.js
  572. var object_assign = __webpack_require__("woOf");
  573. var assign_default = /*#__PURE__*/__webpack_require__.n(object_assign);
  574. // EXTERNAL MODULE: ./node_modules/simditor/lib/simditor.js
  575. var simditor = __webpack_require__("faOw");
  576. var simditor_default = /*#__PURE__*/__webpack_require__.n(simditor);
  577. // EXTERNAL MODULE: ./node_modules/jquery/src/jquery.js
  578. var jquery = __webpack_require__("4kSj");
  579. var jquery_default = /*#__PURE__*/__webpack_require__.n(jquery);
  580. // EXTERNAL MODULE: ./node_modules/simditor/styles/simditor.css
  581. var styles_simditor = __webpack_require__("lSXA");
  582. var styles_simditor_default = /*#__PURE__*/__webpack_require__.n(styles_simditor);
  583. // CONCATENATED MODULE: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/editor/editor.vue
  584. //
  585. //
  586. //
  587. //
  588. //
  589. // import config from '@/config/index'
  590. /* harmony default export */ var editor = ({
  591. name: "ueditor",
  592. props: {
  593. options: {
  594. // 配置参数
  595. type: Object,
  596. default: function _default() {
  597. return {};
  598. }
  599. },
  600. policyContent: {
  601. type: String,
  602. default: ""
  603. }
  604. },
  605. watch: {
  606. policyContent: function policyContent(n) {
  607. this.plcontent = n;
  608. this.setContentValue(this.policyContent);
  609. }
  610. },
  611. data: function data() {
  612. return {
  613. id: Math.floor(Math.random() * 10 * 10), // 这是为了在同一个组件里放多个富文本编辑器,而加的标记
  614. editor: "",
  615. plcontent: "",
  616. showStatus: true
  617. };
  618. },
  619. mounted: function mounted() {
  620. var _this = this;
  621. var vm = this;
  622. this.editor = new simditor_default.a(assign_default()({}, {
  623. textarea: jquery_default()("#" + vm.id),
  624. pasteImage: true
  625. }, this.options));
  626. // 不知道干什么的
  627. this.editor.on("valuechanged", function (e, src) {
  628. _this.valueChange(e, src);
  629. });
  630. // 修改上传后图片的路径
  631. // this.editor.uploader.on("uploadsuccess", function (e, file, result) {
  632. // let $img, $mask, msg;
  633. // if (!file.inline) {
  634. // return;
  635. // }
  636. // $img = file.img;
  637. // $img.removeData("file");
  638. // $img.removeClass("uploading");
  639. // $mask = $img.data("mask");
  640. // if ($mask) {
  641. // $mask.remove();
  642. // }
  643. // $img.removeData("mask");
  644. // if (result.success === false) {
  645. // msg = result.msg || "上传被拒绝了";
  646. // this.$message.error(msg);
  647. // $img.attr("src", this.defaultImage);
  648. // } else {
  649. // // 修改图片路径和样式
  650. // $img.attr({
  651. // src: "http://120.79.209.118:8015/" + result.data, // 路径
  652. // // src: config.baseUrl + result.file_path, // 路径
  653. // }); // 这里就是成功后的替换,将这个改成了我们所使用的字段名file
  654. // }
  655. // });
  656. this.setContentValue(this.policyContent);
  657. },
  658. methods: {
  659. // 获取富文本编辑器的值
  660. valueChange: function valueChange(e, val) {
  661. this.$emit("editorContentValue", this.editor.getValue());
  662. },
  663. // 给富文本编辑期赋值
  664. setContentValue: function setContentValue(val) {
  665. this.editor.setValue(val);
  666. }
  667. }
  668. });
  669. // CONCATENATED MODULE: ./node_modules/vue-loader/lib/template-compiler?{"id":"data-v-1069c726","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/editor/editor.vue
  670. var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"simditor"},[_c('textarea',{directives:[{name:"show",rawName:"v-show",value:(_vm.showStatus),expression:"showStatus"}],attrs:{"id":_vm.id},domProps:{"innerHTML":_vm._s(_vm.plcontent)}})])}
  671. var staticRenderFns = []
  672. var esExports = { render: render, staticRenderFns: staticRenderFns }
  673. /* harmony default export */ var editor_editor = (esExports);
  674. // CONCATENATED MODULE: ./src/components/editor/editor.vue
  675. function injectStyle (ssrContext) {
  676. __webpack_require__("1taR")
  677. }
  678. var normalizeComponent = __webpack_require__("VU/8")
  679. /* script */
  680. /* template */
  681. /* template functional */
  682. var __vue_template_functional__ = false
  683. /* styles */
  684. var __vue_styles__ = injectStyle
  685. /* scopeId */
  686. var __vue_scopeId__ = "data-v-1069c726"
  687. /* moduleIdentifier (server only) */
  688. var __vue_module_identifier__ = null
  689. var Component = normalizeComponent(
  690. editor,
  691. editor_editor,
  692. __vue_template_functional__,
  693. __vue_styles__,
  694. __vue_scopeId__,
  695. __vue_module_identifier__
  696. )
  697. /* harmony default export */ var components_editor_editor = (Component.exports);
  698. // EXTERNAL MODULE: ./src/api/index.js + 5 modules
  699. var api = __webpack_require__("gyMJ");
  700. // CONCATENATED MODULE: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/views/template/contractExportTemplate.vue
  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. /* harmony default export */ var contractExportTemplate = ({
  763. name: "contractExportTemplate",
  764. data: function data() {
  765. return {
  766. dialogVisibleOne: false,
  767. fileName: '',
  768. dialogVisible: false,
  769. contractsList: [],
  770. CompanyProfile: '',
  771. editorContent: "",
  772. editorContent1: "",
  773. options: {
  774. placeHolder: "this is placeHolder",
  775. toolbarFloat: false,
  776. toolbar: ["title", "bold", "italic", "underline", "strikethrough", "fontScale", "color", "|", "ol", "ul", "blockquote", "code", "table", "|", "link", "image", "hr", "|", "indent", "outdent", "alignment"]
  777. }
  778. };
  779. },
  780. components: { contractTemplate: contractTemplate["a" /* default */], UEditor: components_editor_editor },
  781. mounted: function mounted() {
  782. // this.getContractsMethods()
  783. this.getAllContracts();
  784. },
  785. methods: {
  786. // 删除模板
  787. deleteContent: function deleteContent(row) {
  788. var _this = this;
  789. this.$confirm('此操作将删除该模板, 是否继续?', '提示', {
  790. confirmButtonText: '确定',
  791. cancelButtonText: '取消',
  792. type: 'warning'
  793. }).then(function () {
  794. var data = [row.label];
  795. Object(api["g" /* httpPost */])(data, _this.$api.deleteContracts).then(function (res) {
  796. if (res.success) {
  797. _this.dialogVisible = false;
  798. _this.$message.success("删除成功");
  799. _this.getAllContracts();
  800. } else {
  801. _this.$message.error("删除失败");
  802. }
  803. });
  804. });
  805. },
  806. // 打开编辑弹窗
  807. handleClick: function handleClick(row) {
  808. this.dialogVisible = true;
  809. this.fileName = row.label;
  810. this.getContractsMethods();
  811. },
  812. // 关闭弹窗
  813. handleClose: function handleClose() {
  814. this.dialogVisible = false;
  815. },
  816. // 获取所有模板
  817. getAllContracts: function getAllContracts() {
  818. var _this2 = this;
  819. Object(api["d" /* httpGet */])('', this.$api.getContracts).then(function (res) {
  820. if (res.success) {
  821. var list = [];
  822. res.data.map(function (li) {
  823. var obj = {
  824. label: li
  825. };
  826. list.push(obj);
  827. });
  828. _this2.contractsList = list;
  829. }
  830. });
  831. },
  832. getContractsMethods: function getContractsMethods() {
  833. var _this3 = this;
  834. var data = {
  835. "fileName": this.fileName
  836. };
  837. Object(api["g" /* httpPost */])(data, this.$api.getOrderContract).then(function (res) {
  838. if (res.success) {
  839. _this3.editorContent = res.data;
  840. console.log(_this3.editorContent);
  841. }
  842. });
  843. },
  844. editorContentValue: function editorContentValue(val) {
  845. this.CompanyProfile = val;
  846. },
  847. // 导出合同模板名称
  848. exportContent: function exportContent(row) {
  849. var _this4 = this;
  850. return asyncToGenerator_default()( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
  851. return regenerator_default.a.wrap(function _callee$(_context) {
  852. while (1) {
  853. switch (_context.prev = _context.next) {
  854. case 0:
  855. _this4.fileName = row.label;
  856. _this4.dialogVisible = true;
  857. _context.next = 4;
  858. return _this4.getContractsMethods();
  859. case 4:
  860. _context.next = 6;
  861. return _this4.exportHtmlWord();
  862. case 6:
  863. case 'end':
  864. return _context.stop();
  865. }
  866. }
  867. }, _callee, _this4);
  868. }))();
  869. },
  870. // 上传模板
  871. uploadTemplate: function uploadTemplate() {
  872. var _this5 = this;
  873. var html = this.CompanyProfile; //获取html的内容
  874. // let arr = document.querySelector('#question_doc')
  875. // let html = arr.innerHTML
  876. 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>';
  877. var data = {
  878. "fileName": this.fileName,
  879. "content": htmlStr
  880. };
  881. Object(api["g" /* httpPost */])(data, this.$api.createUpdateContractHandle).then(function (res) {
  882. if (res.success) {
  883. _this5.$message.success("上传成功");
  884. _this5.dialogVisible = false;
  885. _this5.getAllContracts();
  886. } else {
  887. _this5.$message.error('\u4E0A\u4F20\u5931\u8D25\uFF1A' + res.message);
  888. }
  889. });
  890. },
  891. // 导出模板
  892. exportHtmlWord: function exportHtmlWord() {
  893. // let arr = document.querySelector('#question_doc') //获取dom
  894. var html = this.CompanyProfile; //获取html的内容
  895. 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中 this.CompanyProfile
  896. this.editorContent = htmlStr;
  897. Object(FileSaver_min["saveAs"])(html_docx_default.a.asBlob(htmlStr, { orientation: 'landscape' }), '房屋租赁合同模板.doc'); // 导出为word
  898. }
  899. }
  900. });
  901. // CONCATENATED MODULE: ./node_modules/vue-loader/lib/template-compiler?{"id":"data-v-dc67c7c0","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/template/contractExportTemplate.vue
  902. var contractExportTemplate_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"home"},[_c('el-button',{attrs:{"type":"primary","size":"small"},on:{"click":function($event){_vm.dialogVisibleOne = true}}},[_vm._v("创建模板")]),_vm._v(" "),_c('el-table',{staticClass:"mt-3",staticStyle:{"width":"100%"},attrs:{"data":_vm.contractsList}},[_c('el-table-column',{attrs:{"prop":"label","label":"模板名称"}}),_vm._v(" "),_c('el-table-column',{attrs:{"label":"操作"},scopedSlots:_vm._u([{key:"default",fn:function(scope){return [_c('el-button',{attrs:{"type":"text","size":"small"},on:{"click":function($event){return _vm.handleClick(scope.row)}}},[_vm._v("编辑")]),_vm._v(" "),_c('el-button',{attrs:{"type":"text","size":"small"},on:{"click":function($event){return _vm.exportContent(scope.row)}}},[_vm._v("导出")]),_vm._v(" "),_c('el-button',{attrs:{"type":"text","size":"small"},on:{"click":function($event){return _vm.deleteContent(scope.row)}}},[_vm._v("删除")])]}}])})],1),_vm._v(" "),_c('el-drawer',{attrs:{"title":"创建模板","visible":_vm.dialogVisibleOne,"size":"100%","direction":"rtl","before-close":_vm.handleClose},on:{"update:visible":function($event){_vm.dialogVisibleOne=$event}}},[_c('div',{staticClass:"mx-2"},[_c('el-input',{attrs:{"type":"text","placeholder":"文件名称"},model:{value:(_vm.fileName),callback:function ($$v) {_vm.fileName=$$v},expression:"fileName"}}),_vm._v(" "),_c('UEditor',{key:_vm.editorContent1,staticClass:"mt-2",attrs:{"options":_vm.options,"policyContent":_vm.editorContent,"ShopData":_vm.editorContent1},on:{"editorContentValue":_vm.editorContentValue}}),_vm._v(" "),_c('el-button',{attrs:{"type":"primary","size":"small"},on:{"click":_vm.uploadTemplate}},[_vm._v("保存")]),_vm._v(" "),_c('el-button',{attrs:{"type":"primary","size":"small"},on:{"click":function($event){_vm.dialogVisibleOne = false}}},[_vm._v("返回")])],1)]),_vm._v(" "),_c('el-drawer',{attrs:{"title":"模板内容","visible":_vm.dialogVisible,"size":"100%","direction":"rtl","before-close":_vm.handleClose},on:{"update:visible":function($event){_vm.dialogVisible=$event}}},[_c('div',{staticClass:"mx-2"},[_c('UEditor',{key:_vm.editorContent1,staticClass:"mt-2",attrs:{"options":_vm.options,"policyContent":_vm.editorContent,"ShopData":_vm.editorContent1},on:{"editorContentValue":_vm.editorContentValue}}),_vm._v(" "),_c('el-button',{attrs:{"type":"primary","size":"small"},on:{"click":_vm.uploadTemplate}},[_vm._v("保存")]),_vm._v(" "),_c('el-button',{attrs:{"type":"primary","size":"small"},on:{"click":function($event){_vm.dialogVisible = false}}},[_vm._v("返回")])],1)]),_vm._v(" "),_c('contractTemplate',{directives:[{name:"show",rawName:"v-show",value:(false),expression:"false"}],attrs:{"id":"question_doc","data":{}}})],1)}
  903. var contractExportTemplate_staticRenderFns = []
  904. var contractExportTemplate_esExports = { render: contractExportTemplate_render, staticRenderFns: contractExportTemplate_staticRenderFns }
  905. /* harmony default export */ var template_contractExportTemplate = (contractExportTemplate_esExports);
  906. // CONCATENATED MODULE: ./src/views/template/contractExportTemplate.vue
  907. function contractExportTemplate_injectStyle (ssrContext) {
  908. __webpack_require__("Uxkr")
  909. }
  910. var contractExportTemplate_normalizeComponent = __webpack_require__("VU/8")
  911. /* script */
  912. /* template */
  913. /* template functional */
  914. var contractExportTemplate___vue_template_functional__ = false
  915. /* styles */
  916. var contractExportTemplate___vue_styles__ = contractExportTemplate_injectStyle
  917. /* scopeId */
  918. var contractExportTemplate___vue_scopeId__ = "data-v-dc67c7c0"
  919. /* moduleIdentifier (server only) */
  920. var contractExportTemplate___vue_module_identifier__ = null
  921. var contractExportTemplate_Component = contractExportTemplate_normalizeComponent(
  922. contractExportTemplate,
  923. template_contractExportTemplate,
  924. contractExportTemplate___vue_template_functional__,
  925. contractExportTemplate___vue_styles__,
  926. contractExportTemplate___vue_scopeId__,
  927. contractExportTemplate___vue_module_identifier__
  928. )
  929. /* harmony default export */ var views_template_contractExportTemplate = __webpack_exports__["default"] = (contractExportTemplate_Component.exports);
  930. /***/ }),
  931. /***/ "Cmgq":
  932. /***/ (function(module, exports, __webpack_require__) {
  933. var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) {
  934. if (true) {
  935. // AMD. Register as an anonymous module unless amdModuleId is set
  936. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__("4kSj"),__webpack_require__("580I")], __WEBPACK_AMD_DEFINE_RESULT__ = (function ($, SimpleModule) {
  937. return (root['uploader'] = factory($, SimpleModule));
  938. }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
  939. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  940. } else if (typeof exports === 'object') {
  941. // Node. Does not work with strict CommonJS, but
  942. // only CommonJS-like environments that support module.exports,
  943. // like Node.
  944. module.exports = factory(require("jquery"),require("simple-module"));
  945. } else {
  946. root.simple = root.simple || {};
  947. root.simple['uploader'] = factory(jQuery,SimpleModule);
  948. }
  949. }(this, function ($, SimpleModule) {
  950. var Uploader, uploader,
  951. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  952. hasProp = {}.hasOwnProperty;
  953. Uploader = (function(superClass) {
  954. extend(Uploader, superClass);
  955. function Uploader() {
  956. return Uploader.__super__.constructor.apply(this, arguments);
  957. }
  958. Uploader.count = 0;
  959. Uploader.prototype.opts = {
  960. url: '',
  961. params: null,
  962. fileKey: 'upload_file',
  963. connectionCount: 3
  964. };
  965. Uploader.prototype._init = function() {
  966. this.files = [];
  967. this.queue = [];
  968. this.id = ++Uploader.count;
  969. this.on('uploadcomplete', (function(_this) {
  970. return function(e, file) {
  971. _this.files.splice($.inArray(file, _this.files), 1);
  972. if (_this.queue.length > 0 && _this.files.length < _this.opts.connectionCount) {
  973. return _this.upload(_this.queue.shift());
  974. } else if (_this.files.length === 0) {
  975. return _this.uploading = false;
  976. }
  977. };
  978. })(this));
  979. return $(window).on('beforeunload.uploader-' + this.id, (function(_this) {
  980. return function(e) {
  981. if (!_this.uploading) {
  982. return;
  983. }
  984. e.originalEvent.returnValue = _this._t('leaveConfirm');
  985. return _this._t('leaveConfirm');
  986. };
  987. })(this));
  988. };
  989. Uploader.prototype.generateId = (function() {
  990. var id;
  991. id = 0;
  992. return function() {
  993. return id += 1;
  994. };
  995. })();
  996. Uploader.prototype.upload = function(file, opts) {
  997. var f, i, key, len;
  998. if (opts == null) {
  999. opts = {};
  1000. }
  1001. if (file == null) {
  1002. return;
  1003. }
  1004. if ($.isArray(file) || file instanceof FileList) {
  1005. for (i = 0, len = file.length; i < len; i++) {
  1006. f = file[i];
  1007. this.upload(f, opts);
  1008. }
  1009. } else if ($(file).is('input:file')) {
  1010. key = $(file).attr('name');
  1011. if (key) {
  1012. opts.fileKey = key;
  1013. }
  1014. this.upload($.makeArray($(file)[0].files), opts);
  1015. } else if (!file.id || !file.obj) {
  1016. file = this.getFile(file);
  1017. }
  1018. if (!(file && file.obj)) {
  1019. return;
  1020. }
  1021. $.extend(file, opts);
  1022. if (this.files.length >= this.opts.connectionCount) {
  1023. this.queue.push(file);
  1024. return;
  1025. }
  1026. if (this.triggerHandler('beforeupload', [file]) === false) {
  1027. return;
  1028. }
  1029. this.files.push(file);
  1030. this._xhrUpload(file);
  1031. return this.uploading = true;
  1032. };
  1033. Uploader.prototype.getFile = function(fileObj) {
  1034. var name, ref, ref1;
  1035. if (fileObj instanceof window.File || fileObj instanceof window.Blob) {
  1036. name = (ref = fileObj.fileName) != null ? ref : fileObj.name;
  1037. } else {
  1038. return null;
  1039. }
  1040. return {
  1041. id: this.generateId(),
  1042. url: this.opts.url,
  1043. params: this.opts.params,
  1044. fileKey: this.opts.fileKey,
  1045. name: name,
  1046. size: (ref1 = fileObj.fileSize) != null ? ref1 : fileObj.size,
  1047. ext: name ? name.split('.').pop().toLowerCase() : '',
  1048. obj: fileObj
  1049. };
  1050. };
  1051. Uploader.prototype._xhrUpload = function(file) {
  1052. var formData, k, ref, v;
  1053. formData = new FormData();
  1054. formData.append(file.fileKey, file.obj);
  1055. formData.append("original_filename", file.name);
  1056. if (file.params) {
  1057. ref = file.params;
  1058. for (k in ref) {
  1059. v = ref[k];
  1060. formData.append(k, v);
  1061. }
  1062. }
  1063. return file.xhr = $.ajax({
  1064. url: file.url,
  1065. data: formData,
  1066. processData: false,
  1067. contentType: false,
  1068. type: 'POST',
  1069. headers: {
  1070. 'X-File-Name': encodeURIComponent(file.name)
  1071. },
  1072. xhr: function() {
  1073. var req;
  1074. req = $.ajaxSettings.xhr();
  1075. if (req) {
  1076. req.upload.onprogress = (function(_this) {
  1077. return function(e) {
  1078. return _this.progress(e);
  1079. };
  1080. })(this);
  1081. }
  1082. return req;
  1083. },
  1084. progress: (function(_this) {
  1085. return function(e) {
  1086. if (!e.lengthComputable) {
  1087. return;
  1088. }
  1089. return _this.trigger('uploadprogress', [file, e.loaded, e.total]);
  1090. };
  1091. })(this),
  1092. error: (function(_this) {
  1093. return function(xhr, status, err) {
  1094. return _this.trigger('uploaderror', [file, xhr, status]);
  1095. };
  1096. })(this),
  1097. success: (function(_this) {
  1098. return function(result) {
  1099. _this.trigger('uploadprogress', [file, file.size, file.size]);
  1100. _this.trigger('uploadsuccess', [file, result]);
  1101. return $(document).trigger('uploadsuccess', [file, result, _this]);
  1102. };
  1103. })(this),
  1104. complete: (function(_this) {
  1105. return function(xhr, status) {
  1106. return _this.trigger('uploadcomplete', [file, xhr.responseText]);
  1107. };
  1108. })(this)
  1109. });
  1110. };
  1111. Uploader.prototype.cancel = function(file) {
  1112. var f, i, len, ref;
  1113. if (!file.id) {
  1114. ref = this.files;
  1115. for (i = 0, len = ref.length; i < len; i++) {
  1116. f = ref[i];
  1117. if (f.id === file * 1) {
  1118. file = f;
  1119. break;
  1120. }
  1121. }
  1122. }
  1123. this.trigger('uploadcancel', [file]);
  1124. if (file.xhr) {
  1125. file.xhr.abort();
  1126. }
  1127. return file.xhr = null;
  1128. };
  1129. Uploader.prototype.readImageFile = function(fileObj, callback) {
  1130. var fileReader, img;
  1131. if (!$.isFunction(callback)) {
  1132. return;
  1133. }
  1134. img = new Image();
  1135. img.onload = function() {
  1136. return callback(img);
  1137. };
  1138. img.onerror = function() {
  1139. return callback();
  1140. };
  1141. if (window.FileReader && FileReader.prototype.readAsDataURL && /^image/.test(fileObj.type)) {
  1142. fileReader = new FileReader();
  1143. fileReader.onload = function(e) {
  1144. return img.src = e.target.result;
  1145. };
  1146. return fileReader.readAsDataURL(fileObj);
  1147. } else {
  1148. return callback();
  1149. }
  1150. };
  1151. Uploader.prototype.destroy = function() {
  1152. var file, i, len, ref;
  1153. this.queue.length = 0;
  1154. ref = this.files;
  1155. for (i = 0, len = ref.length; i < len; i++) {
  1156. file = ref[i];
  1157. this.cancel(file);
  1158. }
  1159. $(window).off('.uploader-' + this.id);
  1160. return $(document).off('.uploader-' + this.id);
  1161. };
  1162. Uploader.i18n = {
  1163. 'zh-CN': {
  1164. leaveConfirm: '正在上传文件,如果离开上传会自动取消'
  1165. }
  1166. };
  1167. Uploader.locale = 'zh-CN';
  1168. return Uploader;
  1169. })(SimpleModule);
  1170. uploader = function(opts) {
  1171. return new Uploader(opts);
  1172. };
  1173. return uploader;
  1174. }));
  1175. /***/ }),
  1176. /***/ "SiUS":
  1177. /***/ (function(module, exports) {
  1178. // removed by extract-text-webpack-plugin
  1179. /***/ }),
  1180. /***/ "U3YJ":
  1181. /***/ (function(module, exports, __webpack_require__) {
  1182. 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){
  1183. /*!
  1184. * The buffer module from node.js, for the browser.
  1185. *
  1186. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  1187. * @license MIT
  1188. */
  1189. var base64 = _dereq_('base64-js')
  1190. var ieee754 = _dereq_('ieee754')
  1191. var isArray = _dereq_('is-array')
  1192. exports.Buffer = Buffer
  1193. exports.SlowBuffer = Buffer
  1194. exports.INSPECT_MAX_BYTES = 50
  1195. Buffer.poolSize = 8192 // not used by this implementation
  1196. var kMaxLength = 0x3fffffff
  1197. /**
  1198. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  1199. * === true Use Uint8Array implementation (fastest)
  1200. * === false Use Object implementation (most compatible, even IE6)
  1201. *
  1202. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  1203. * Opera 11.6+, iOS 4.2+.
  1204. *
  1205. * Note:
  1206. *
  1207. * - Implementation must support adding new properties to `Uint8Array` instances.
  1208. * Firefox 4-29 lacked support, fixed in Firefox 30+.
  1209. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  1210. *
  1211. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  1212. *
  1213. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  1214. * incorrect length in some situations.
  1215. *
  1216. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
  1217. * get the Object implementation, which is slower but will work correctly.
  1218. */
  1219. Buffer.TYPED_ARRAY_SUPPORT = (function () {
  1220. try {
  1221. var buf = new ArrayBuffer(0)
  1222. var arr = new Uint8Array(buf)
  1223. arr.foo = function () { return 42 }
  1224. return 42 === arr.foo() && // typed array instances can be augmented
  1225. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  1226. new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  1227. } catch (e) {
  1228. return false
  1229. }
  1230. })()
  1231. /**
  1232. * Class: Buffer
  1233. * =============
  1234. *
  1235. * The Buffer constructor returns instances of `Uint8Array` that are augmented
  1236. * with function properties for all the node `Buffer` API functions. We use
  1237. * `Uint8Array` so that square bracket notation works as expected -- it returns
  1238. * a single octet.
  1239. *
  1240. * By augmenting the instances, we can avoid modifying the `Uint8Array`
  1241. * prototype.
  1242. */
  1243. function Buffer (subject, encoding, noZero) {
  1244. if (!(this instanceof Buffer))
  1245. return new Buffer(subject, encoding, noZero)
  1246. var type = typeof subject
  1247. // Find the length
  1248. var length
  1249. if (type === 'number')
  1250. length = subject > 0 ? subject >>> 0 : 0
  1251. else if (type === 'string') {
  1252. if (encoding === 'base64')
  1253. subject = base64clean(subject)
  1254. length = Buffer.byteLength(subject, encoding)
  1255. } else if (type === 'object' && subject !== null) { // assume object is array-like
  1256. if (subject.type === 'Buffer' && isArray(subject.data))
  1257. subject = subject.data
  1258. length = +subject.length > 0 ? Math.floor(+subject.length) : 0
  1259. } else
  1260. throw new TypeError('must start with number, buffer, array or string')
  1261. if (this.length > kMaxLength)
  1262. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  1263. 'size: 0x' + kMaxLength.toString(16) + ' bytes')
  1264. var buf
  1265. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1266. // Preferred: Return an augmented `Uint8Array` instance for best performance
  1267. buf = Buffer._augment(new Uint8Array(length))
  1268. } else {
  1269. // Fallback: Return THIS instance of Buffer (created by `new`)
  1270. buf = this
  1271. buf.length = length
  1272. buf._isBuffer = true
  1273. }
  1274. var i
  1275. if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
  1276. // Speed optimization -- use set if we're copying from a typed array
  1277. buf._set(subject)
  1278. } else if (isArrayish(subject)) {
  1279. // Treat array-ish objects as a byte array
  1280. if (Buffer.isBuffer(subject)) {
  1281. for (i = 0; i < length; i++)
  1282. buf[i] = subject.readUInt8(i)
  1283. } else {
  1284. for (i = 0; i < length; i++)
  1285. buf[i] = ((subject[i] % 256) + 256) % 256
  1286. }
  1287. } else if (type === 'string') {
  1288. buf.write(subject, 0, encoding)
  1289. } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) {
  1290. for (i = 0; i < length; i++) {
  1291. buf[i] = 0
  1292. }
  1293. }
  1294. return buf
  1295. }
  1296. Buffer.isBuffer = function (b) {
  1297. return !!(b != null && b._isBuffer)
  1298. }
  1299. Buffer.compare = function (a, b) {
  1300. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b))
  1301. throw new TypeError('Arguments must be Buffers')
  1302. var x = a.length
  1303. var y = b.length
  1304. for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
  1305. if (i !== len) {
  1306. x = a[i]
  1307. y = b[i]
  1308. }
  1309. if (x < y) return -1
  1310. if (y < x) return 1
  1311. return 0
  1312. }
  1313. Buffer.isEncoding = function (encoding) {
  1314. switch (String(encoding).toLowerCase()) {
  1315. case 'hex':
  1316. case 'utf8':
  1317. case 'utf-8':
  1318. case 'ascii':
  1319. case 'binary':
  1320. case 'base64':
  1321. case 'raw':
  1322. case 'ucs2':
  1323. case 'ucs-2':
  1324. case 'utf16le':
  1325. case 'utf-16le':
  1326. return true
  1327. default:
  1328. return false
  1329. }
  1330. }
  1331. Buffer.concat = function (list, totalLength) {
  1332. if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])')
  1333. if (list.length === 0) {
  1334. return new Buffer(0)
  1335. } else if (list.length === 1) {
  1336. return list[0]
  1337. }
  1338. var i
  1339. if (totalLength === undefined) {
  1340. totalLength = 0
  1341. for (i = 0; i < list.length; i++) {
  1342. totalLength += list[i].length
  1343. }
  1344. }
  1345. var buf = new Buffer(totalLength)
  1346. var pos = 0
  1347. for (i = 0; i < list.length; i++) {
  1348. var item = list[i]
  1349. item.copy(buf, pos)
  1350. pos += item.length
  1351. }
  1352. return buf
  1353. }
  1354. Buffer.byteLength = function (str, encoding) {
  1355. var ret
  1356. str = str + ''
  1357. switch (encoding || 'utf8') {
  1358. case 'ascii':
  1359. case 'binary':
  1360. case 'raw':
  1361. ret = str.length
  1362. break
  1363. case 'ucs2':
  1364. case 'ucs-2':
  1365. case 'utf16le':
  1366. case 'utf-16le':
  1367. ret = str.length * 2
  1368. break
  1369. case 'hex':
  1370. ret = str.length >>> 1
  1371. break
  1372. case 'utf8':
  1373. case 'utf-8':
  1374. ret = utf8ToBytes(str).length
  1375. break
  1376. case 'base64':
  1377. ret = base64ToBytes(str).length
  1378. break
  1379. default:
  1380. ret = str.length
  1381. }
  1382. return ret
  1383. }
  1384. // pre-set for values that may exist in the future
  1385. Buffer.prototype.length = undefined
  1386. Buffer.prototype.parent = undefined
  1387. // toString(encoding, start=0, end=buffer.length)
  1388. Buffer.prototype.toString = function (encoding, start, end) {
  1389. var loweredCase = false
  1390. start = start >>> 0
  1391. end = end === undefined || end === Infinity ? this.length : end >>> 0
  1392. if (!encoding) encoding = 'utf8'
  1393. if (start < 0) start = 0
  1394. if (end > this.length) end = this.length
  1395. if (end <= start) return ''
  1396. while (true) {
  1397. switch (encoding) {
  1398. case 'hex':
  1399. return hexSlice(this, start, end)
  1400. case 'utf8':
  1401. case 'utf-8':
  1402. return utf8Slice(this, start, end)
  1403. case 'ascii':
  1404. return asciiSlice(this, start, end)
  1405. case 'binary':
  1406. return binarySlice(this, start, end)
  1407. case 'base64':
  1408. return base64Slice(this, start, end)
  1409. case 'ucs2':
  1410. case 'ucs-2':
  1411. case 'utf16le':
  1412. case 'utf-16le':
  1413. return utf16leSlice(this, start, end)
  1414. default:
  1415. if (loweredCase)
  1416. throw new TypeError('Unknown encoding: ' + encoding)
  1417. encoding = (encoding + '').toLowerCase()
  1418. loweredCase = true
  1419. }
  1420. }
  1421. }
  1422. Buffer.prototype.equals = function (b) {
  1423. if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1424. return Buffer.compare(this, b) === 0
  1425. }
  1426. Buffer.prototype.inspect = function () {
  1427. var str = ''
  1428. var max = exports.INSPECT_MAX_BYTES
  1429. if (this.length > 0) {
  1430. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  1431. if (this.length > max)
  1432. str += ' ... '
  1433. }
  1434. return '<Buffer ' + str + '>'
  1435. }
  1436. Buffer.prototype.compare = function (b) {
  1437. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1438. return Buffer.compare(this, b)
  1439. }
  1440. // `get` will be removed in Node 0.13+
  1441. Buffer.prototype.get = function (offset) {
  1442. console.log('.get() is deprecated. Access using array indexes instead.')
  1443. return this.readUInt8(offset)
  1444. }
  1445. // `set` will be removed in Node 0.13+
  1446. Buffer.prototype.set = function (v, offset) {
  1447. console.log('.set() is deprecated. Access using array indexes instead.')
  1448. return this.writeUInt8(v, offset)
  1449. }
  1450. function hexWrite (buf, string, offset, length) {
  1451. offset = Number(offset) || 0
  1452. var remaining = buf.length - offset
  1453. if (!length) {
  1454. length = remaining
  1455. } else {
  1456. length = Number(length)
  1457. if (length > remaining) {
  1458. length = remaining
  1459. }
  1460. }
  1461. // must be an even number of digits
  1462. var strLen = string.length
  1463. if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  1464. if (length > strLen / 2) {
  1465. length = strLen / 2
  1466. }
  1467. for (var i = 0; i < length; i++) {
  1468. var byte = parseInt(string.substr(i * 2, 2), 16)
  1469. if (isNaN(byte)) throw new Error('Invalid hex string')
  1470. buf[offset + i] = byte
  1471. }
  1472. return i
  1473. }
  1474. function utf8Write (buf, string, offset, length) {
  1475. var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
  1476. return charsWritten
  1477. }
  1478. function asciiWrite (buf, string, offset, length) {
  1479. var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
  1480. return charsWritten
  1481. }
  1482. function binaryWrite (buf, string, offset, length) {
  1483. return asciiWrite(buf, string, offset, length)
  1484. }
  1485. function base64Write (buf, string, offset, length) {
  1486. var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
  1487. return charsWritten
  1488. }
  1489. function utf16leWrite (buf, string, offset, length) {
  1490. var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length, 2)
  1491. return charsWritten
  1492. }
  1493. Buffer.prototype.write = function (string, offset, length, encoding) {
  1494. // Support both (string, offset, length, encoding)
  1495. // and the legacy (string, encoding, offset, length)
  1496. if (isFinite(offset)) {
  1497. if (!isFinite(length)) {
  1498. encoding = length
  1499. length = undefined
  1500. }
  1501. } else { // legacy
  1502. var swap = encoding
  1503. encoding = offset
  1504. offset = length
  1505. length = swap
  1506. }
  1507. offset = Number(offset) || 0
  1508. var remaining = this.length - offset
  1509. if (!length) {
  1510. length = remaining
  1511. } else {
  1512. length = Number(length)
  1513. if (length > remaining) {
  1514. length = remaining
  1515. }
  1516. }
  1517. encoding = String(encoding || 'utf8').toLowerCase()
  1518. var ret
  1519. switch (encoding) {
  1520. case 'hex':
  1521. ret = hexWrite(this, string, offset, length)
  1522. break
  1523. case 'utf8':
  1524. case 'utf-8':
  1525. ret = utf8Write(this, string, offset, length)
  1526. break
  1527. case 'ascii':
  1528. ret = asciiWrite(this, string, offset, length)
  1529. break
  1530. case 'binary':
  1531. ret = binaryWrite(this, string, offset, length)
  1532. break
  1533. case 'base64':
  1534. ret = base64Write(this, string, offset, length)
  1535. break
  1536. case 'ucs2':
  1537. case 'ucs-2':
  1538. case 'utf16le':
  1539. case 'utf-16le':
  1540. ret = utf16leWrite(this, string, offset, length)
  1541. break
  1542. default:
  1543. throw new TypeError('Unknown encoding: ' + encoding)
  1544. }
  1545. return ret
  1546. }
  1547. Buffer.prototype.toJSON = function () {
  1548. return {
  1549. type: 'Buffer',
  1550. data: Array.prototype.slice.call(this._arr || this, 0)
  1551. }
  1552. }
  1553. function base64Slice (buf, start, end) {
  1554. if (start === 0 && end === buf.length) {
  1555. return base64.fromByteArray(buf)
  1556. } else {
  1557. return base64.fromByteArray(buf.slice(start, end))
  1558. }
  1559. }
  1560. function utf8Slice (buf, start, end) {
  1561. var res = ''
  1562. var tmp = ''
  1563. end = Math.min(buf.length, end)
  1564. for (var i = start; i < end; i++) {
  1565. if (buf[i] <= 0x7F) {
  1566. res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
  1567. tmp = ''
  1568. } else {
  1569. tmp += '%' + buf[i].toString(16)
  1570. }
  1571. }
  1572. return res + decodeUtf8Char(tmp)
  1573. }
  1574. function asciiSlice (buf, start, end) {
  1575. var ret = ''
  1576. end = Math.min(buf.length, end)
  1577. for (var i = start; i < end; i++) {
  1578. ret += String.fromCharCode(buf[i])
  1579. }
  1580. return ret
  1581. }
  1582. function binarySlice (buf, start, end) {
  1583. return asciiSlice(buf, start, end)
  1584. }
  1585. function hexSlice (buf, start, end) {
  1586. var len = buf.length
  1587. if (!start || start < 0) start = 0
  1588. if (!end || end < 0 || end > len) end = len
  1589. var out = ''
  1590. for (var i = start; i < end; i++) {
  1591. out += toHex(buf[i])
  1592. }
  1593. return out
  1594. }
  1595. function utf16leSlice (buf, start, end) {
  1596. var bytes = buf.slice(start, end)
  1597. var res = ''
  1598. for (var i = 0; i < bytes.length; i += 2) {
  1599. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1600. }
  1601. return res
  1602. }
  1603. Buffer.prototype.slice = function (start, end) {
  1604. var len = this.length
  1605. start = ~~start
  1606. end = end === undefined ? len : ~~end
  1607. if (start < 0) {
  1608. start += len;
  1609. if (start < 0)
  1610. start = 0
  1611. } else if (start > len) {
  1612. start = len
  1613. }
  1614. if (end < 0) {
  1615. end += len
  1616. if (end < 0)
  1617. end = 0
  1618. } else if (end > len) {
  1619. end = len
  1620. }
  1621. if (end < start)
  1622. end = start
  1623. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1624. return Buffer._augment(this.subarray(start, end))
  1625. } else {
  1626. var sliceLen = end - start
  1627. var newBuf = new Buffer(sliceLen, undefined, true)
  1628. for (var i = 0; i < sliceLen; i++) {
  1629. newBuf[i] = this[i + start]
  1630. }
  1631. return newBuf
  1632. }
  1633. }
  1634. /*
  1635. * Need to make sure that buffer isn't trying to write out of bounds.
  1636. */
  1637. function checkOffset (offset, ext, length) {
  1638. if ((offset % 1) !== 0 || offset < 0)
  1639. throw new RangeError('offset is not uint')
  1640. if (offset + ext > length)
  1641. throw new RangeError('Trying to access beyond buffer length')
  1642. }
  1643. Buffer.prototype.readUInt8 = function (offset, noAssert) {
  1644. if (!noAssert)
  1645. checkOffset(offset, 1, this.length)
  1646. return this[offset]
  1647. }
  1648. Buffer.prototype.readUInt16LE = function (offset, noAssert) {
  1649. if (!noAssert)
  1650. checkOffset(offset, 2, this.length)
  1651. return this[offset] | (this[offset + 1] << 8)
  1652. }
  1653. Buffer.prototype.readUInt16BE = function (offset, noAssert) {
  1654. if (!noAssert)
  1655. checkOffset(offset, 2, this.length)
  1656. return (this[offset] << 8) | this[offset + 1]
  1657. }
  1658. Buffer.prototype.readUInt32LE = function (offset, noAssert) {
  1659. if (!noAssert)
  1660. checkOffset(offset, 4, this.length)
  1661. return ((this[offset]) |
  1662. (this[offset + 1] << 8) |
  1663. (this[offset + 2] << 16)) +
  1664. (this[offset + 3] * 0x1000000)
  1665. }
  1666. Buffer.prototype.readUInt32BE = function (offset, noAssert) {
  1667. if (!noAssert)
  1668. checkOffset(offset, 4, this.length)
  1669. return (this[offset] * 0x1000000) +
  1670. ((this[offset + 1] << 16) |
  1671. (this[offset + 2] << 8) |
  1672. this[offset + 3])
  1673. }
  1674. Buffer.prototype.readInt8 = function (offset, noAssert) {
  1675. if (!noAssert)
  1676. checkOffset(offset, 1, this.length)
  1677. if (!(this[offset] & 0x80))
  1678. return (this[offset])
  1679. return ((0xff - this[offset] + 1) * -1)
  1680. }
  1681. Buffer.prototype.readInt16LE = function (offset, noAssert) {
  1682. if (!noAssert)
  1683. checkOffset(offset, 2, this.length)
  1684. var val = this[offset] | (this[offset + 1] << 8)
  1685. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1686. }
  1687. Buffer.prototype.readInt16BE = function (offset, noAssert) {
  1688. if (!noAssert)
  1689. checkOffset(offset, 2, this.length)
  1690. var val = this[offset + 1] | (this[offset] << 8)
  1691. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1692. }
  1693. Buffer.prototype.readInt32LE = function (offset, noAssert) {
  1694. if (!noAssert)
  1695. checkOffset(offset, 4, this.length)
  1696. return (this[offset]) |
  1697. (this[offset + 1] << 8) |
  1698. (this[offset + 2] << 16) |
  1699. (this[offset + 3] << 24)
  1700. }
  1701. Buffer.prototype.readInt32BE = function (offset, noAssert) {
  1702. if (!noAssert)
  1703. checkOffset(offset, 4, this.length)
  1704. return (this[offset] << 24) |
  1705. (this[offset + 1] << 16) |
  1706. (this[offset + 2] << 8) |
  1707. (this[offset + 3])
  1708. }
  1709. Buffer.prototype.readFloatLE = function (offset, noAssert) {
  1710. if (!noAssert)
  1711. checkOffset(offset, 4, this.length)
  1712. return ieee754.read(this, offset, true, 23, 4)
  1713. }
  1714. Buffer.prototype.readFloatBE = function (offset, noAssert) {
  1715. if (!noAssert)
  1716. checkOffset(offset, 4, this.length)
  1717. return ieee754.read(this, offset, false, 23, 4)
  1718. }
  1719. Buffer.prototype.readDoubleLE = function (offset, noAssert) {
  1720. if (!noAssert)
  1721. checkOffset(offset, 8, this.length)
  1722. return ieee754.read(this, offset, true, 52, 8)
  1723. }
  1724. Buffer.prototype.readDoubleBE = function (offset, noAssert) {
  1725. if (!noAssert)
  1726. checkOffset(offset, 8, this.length)
  1727. return ieee754.read(this, offset, false, 52, 8)
  1728. }
  1729. function checkInt (buf, value, offset, ext, max, min) {
  1730. if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
  1731. if (value > max || value < min) throw new TypeError('value is out of bounds')
  1732. if (offset + ext > buf.length) throw new TypeError('index out of range')
  1733. }
  1734. Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
  1735. value = +value
  1736. offset = offset >>> 0
  1737. if (!noAssert)
  1738. checkInt(this, value, offset, 1, 0xff, 0)
  1739. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1740. this[offset] = value
  1741. return offset + 1
  1742. }
  1743. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1744. if (value < 0) value = 0xffff + value + 1
  1745. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
  1746. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1747. (littleEndian ? i : 1 - i) * 8
  1748. }
  1749. }
  1750. Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
  1751. value = +value
  1752. offset = offset >>> 0
  1753. if (!noAssert)
  1754. checkInt(this, value, offset, 2, 0xffff, 0)
  1755. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1756. this[offset] = value
  1757. this[offset + 1] = (value >>> 8)
  1758. } else objectWriteUInt16(this, value, offset, true)
  1759. return offset + 2
  1760. }
  1761. Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
  1762. value = +value
  1763. offset = offset >>> 0
  1764. if (!noAssert)
  1765. checkInt(this, value, offset, 2, 0xffff, 0)
  1766. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1767. this[offset] = (value >>> 8)
  1768. this[offset + 1] = value
  1769. } else objectWriteUInt16(this, value, offset, false)
  1770. return offset + 2
  1771. }
  1772. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1773. if (value < 0) value = 0xffffffff + value + 1
  1774. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
  1775. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1776. }
  1777. }
  1778. Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
  1779. value = +value
  1780. offset = offset >>> 0
  1781. if (!noAssert)
  1782. checkInt(this, value, offset, 4, 0xffffffff, 0)
  1783. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1784. this[offset + 3] = (value >>> 24)
  1785. this[offset + 2] = (value >>> 16)
  1786. this[offset + 1] = (value >>> 8)
  1787. this[offset] = value
  1788. } else objectWriteUInt32(this, value, offset, true)
  1789. return offset + 4
  1790. }
  1791. Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
  1792. value = +value
  1793. offset = offset >>> 0
  1794. if (!noAssert)
  1795. checkInt(this, value, offset, 4, 0xffffffff, 0)
  1796. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1797. this[offset] = (value >>> 24)
  1798. this[offset + 1] = (value >>> 16)
  1799. this[offset + 2] = (value >>> 8)
  1800. this[offset + 3] = value
  1801. } else objectWriteUInt32(this, value, offset, false)
  1802. return offset + 4
  1803. }
  1804. Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
  1805. value = +value
  1806. offset = offset >>> 0
  1807. if (!noAssert)
  1808. checkInt(this, value, offset, 1, 0x7f, -0x80)
  1809. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1810. if (value < 0) value = 0xff + value + 1
  1811. this[offset] = value
  1812. return offset + 1
  1813. }
  1814. Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
  1815. value = +value
  1816. offset = offset >>> 0
  1817. if (!noAssert)
  1818. checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1819. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1820. this[offset] = value
  1821. this[offset + 1] = (value >>> 8)
  1822. } else objectWriteUInt16(this, value, offset, true)
  1823. return offset + 2
  1824. }
  1825. Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
  1826. value = +value
  1827. offset = offset >>> 0
  1828. if (!noAssert)
  1829. checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1830. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1831. this[offset] = (value >>> 8)
  1832. this[offset + 1] = value
  1833. } else objectWriteUInt16(this, value, offset, false)
  1834. return offset + 2
  1835. }
  1836. Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
  1837. value = +value
  1838. offset = offset >>> 0
  1839. if (!noAssert)
  1840. checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1841. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1842. this[offset] = value
  1843. this[offset + 1] = (value >>> 8)
  1844. this[offset + 2] = (value >>> 16)
  1845. this[offset + 3] = (value >>> 24)
  1846. } else objectWriteUInt32(this, value, offset, true)
  1847. return offset + 4
  1848. }
  1849. Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
  1850. value = +value
  1851. offset = offset >>> 0
  1852. if (!noAssert)
  1853. checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1854. if (value < 0) value = 0xffffffff + value + 1
  1855. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1856. this[offset] = (value >>> 24)
  1857. this[offset + 1] = (value >>> 16)
  1858. this[offset + 2] = (value >>> 8)
  1859. this[offset + 3] = value
  1860. } else objectWriteUInt32(this, value, offset, false)
  1861. return offset + 4
  1862. }
  1863. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1864. if (value > max || value < min) throw new TypeError('value is out of bounds')
  1865. if (offset + ext > buf.length) throw new TypeError('index out of range')
  1866. }
  1867. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1868. if (!noAssert)
  1869. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1870. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1871. return offset + 4
  1872. }
  1873. Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
  1874. return writeFloat(this, value, offset, true, noAssert)
  1875. }
  1876. Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
  1877. return writeFloat(this, value, offset, false, noAssert)
  1878. }
  1879. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1880. if (!noAssert)
  1881. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1882. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1883. return offset + 8
  1884. }
  1885. Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
  1886. return writeDouble(this, value, offset, true, noAssert)
  1887. }
  1888. Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
  1889. return writeDouble(this, value, offset, false, noAssert)
  1890. }
  1891. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1892. Buffer.prototype.copy = function (target, target_start, start, end) {
  1893. var source = this
  1894. if (!start) start = 0
  1895. if (!end && end !== 0) end = this.length
  1896. if (!target_start) target_start = 0
  1897. // Copy 0 bytes; we're done
  1898. if (end === start) return
  1899. if (target.length === 0 || source.length === 0) return
  1900. // Fatal error conditions
  1901. if (end < start) throw new TypeError('sourceEnd < sourceStart')
  1902. if (target_start < 0 || target_start >= target.length)
  1903. throw new TypeError('targetStart out of bounds')
  1904. if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds')
  1905. if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds')
  1906. // Are we oob?
  1907. if (end > this.length)
  1908. end = this.length
  1909. if (target.length - target_start < end - start)
  1910. end = target.length - target_start + start
  1911. var len = end - start
  1912. if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1913. for (var i = 0; i < len; i++) {
  1914. target[i + target_start] = this[i + start]
  1915. }
  1916. } else {
  1917. target._set(this.subarray(start, start + len), target_start)
  1918. }
  1919. }
  1920. // fill(value, start=0, end=buffer.length)
  1921. Buffer.prototype.fill = function (value, start, end) {
  1922. if (!value) value = 0
  1923. if (!start) start = 0
  1924. if (!end) end = this.length
  1925. if (end < start) throw new TypeError('end < start')
  1926. // Fill 0 bytes; we're done
  1927. if (end === start) return
  1928. if (this.length === 0) return
  1929. if (start < 0 || start >= this.length) throw new TypeError('start out of bounds')
  1930. if (end < 0 || end > this.length) throw new TypeError('end out of bounds')
  1931. var i
  1932. if (typeof value === 'number') {
  1933. for (i = start; i < end; i++) {
  1934. this[i] = value
  1935. }
  1936. } else {
  1937. var bytes = utf8ToBytes(value.toString())
  1938. var len = bytes.length
  1939. for (i = start; i < end; i++) {
  1940. this[i] = bytes[i % len]
  1941. }
  1942. }
  1943. return this
  1944. }
  1945. /**
  1946. * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
  1947. * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
  1948. */
  1949. Buffer.prototype.toArrayBuffer = function () {
  1950. if (typeof Uint8Array !== 'undefined') {
  1951. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1952. return (new Buffer(this)).buffer
  1953. } else {
  1954. var buf = new Uint8Array(this.length)
  1955. for (var i = 0, len = buf.length; i < len; i += 1) {
  1956. buf[i] = this[i]
  1957. }
  1958. return buf.buffer
  1959. }
  1960. } else {
  1961. throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
  1962. }
  1963. }
  1964. // HELPER FUNCTIONS
  1965. // ================
  1966. var BP = Buffer.prototype
  1967. /**
  1968. * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
  1969. */
  1970. Buffer._augment = function (arr) {
  1971. arr.constructor = Buffer
  1972. arr._isBuffer = true
  1973. // save reference to original Uint8Array get/set methods before overwriting
  1974. arr._get = arr.get
  1975. arr._set = arr.set
  1976. // deprecated, will be removed in node 0.13+
  1977. arr.get = BP.get
  1978. arr.set = BP.set
  1979. arr.write = BP.write
  1980. arr.toString = BP.toString
  1981. arr.toLocaleString = BP.toString
  1982. arr.toJSON = BP.toJSON
  1983. arr.equals = BP.equals
  1984. arr.compare = BP.compare
  1985. arr.copy = BP.copy
  1986. arr.slice = BP.slice
  1987. arr.readUInt8 = BP.readUInt8
  1988. arr.readUInt16LE = BP.readUInt16LE
  1989. arr.readUInt16BE = BP.readUInt16BE
  1990. arr.readUInt32LE = BP.readUInt32LE
  1991. arr.readUInt32BE = BP.readUInt32BE
  1992. arr.readInt8 = BP.readInt8
  1993. arr.readInt16LE = BP.readInt16LE
  1994. arr.readInt16BE = BP.readInt16BE
  1995. arr.readInt32LE = BP.readInt32LE
  1996. arr.readInt32BE = BP.readInt32BE
  1997. arr.readFloatLE = BP.readFloatLE
  1998. arr.readFloatBE = BP.readFloatBE
  1999. arr.readDoubleLE = BP.readDoubleLE
  2000. arr.readDoubleBE = BP.readDoubleBE
  2001. arr.writeUInt8 = BP.writeUInt8
  2002. arr.writeUInt16LE = BP.writeUInt16LE
  2003. arr.writeUInt16BE = BP.writeUInt16BE
  2004. arr.writeUInt32LE = BP.writeUInt32LE
  2005. arr.writeUInt32BE = BP.writeUInt32BE
  2006. arr.writeInt8 = BP.writeInt8
  2007. arr.writeInt16LE = BP.writeInt16LE
  2008. arr.writeInt16BE = BP.writeInt16BE
  2009. arr.writeInt32LE = BP.writeInt32LE
  2010. arr.writeInt32BE = BP.writeInt32BE
  2011. arr.writeFloatLE = BP.writeFloatLE
  2012. arr.writeFloatBE = BP.writeFloatBE
  2013. arr.writeDoubleLE = BP.writeDoubleLE
  2014. arr.writeDoubleBE = BP.writeDoubleBE
  2015. arr.fill = BP.fill
  2016. arr.inspect = BP.inspect
  2017. arr.toArrayBuffer = BP.toArrayBuffer
  2018. return arr
  2019. }
  2020. var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
  2021. function base64clean (str) {
  2022. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2023. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  2024. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2025. while (str.length % 4 !== 0) {
  2026. str = str + '='
  2027. }
  2028. return str
  2029. }
  2030. function stringtrim (str) {
  2031. if (str.trim) return str.trim()
  2032. return str.replace(/^\s+|\s+$/g, '')
  2033. }
  2034. function isArrayish (subject) {
  2035. return isArray(subject) || Buffer.isBuffer(subject) ||
  2036. subject && typeof subject === 'object' &&
  2037. typeof subject.length === 'number'
  2038. }
  2039. function toHex (n) {
  2040. if (n < 16) return '0' + n.toString(16)
  2041. return n.toString(16)
  2042. }
  2043. function utf8ToBytes (str) {
  2044. var byteArray = []
  2045. for (var i = 0; i < str.length; i++) {
  2046. var b = str.charCodeAt(i)
  2047. if (b <= 0x7F) {
  2048. byteArray.push(b)
  2049. } else {
  2050. var start = i
  2051. if (b >= 0xD800 && b <= 0xDFFF) i++
  2052. var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
  2053. for (var j = 0; j < h.length; j++) {
  2054. byteArray.push(parseInt(h[j], 16))
  2055. }
  2056. }
  2057. }
  2058. return byteArray
  2059. }
  2060. function asciiToBytes (str) {
  2061. var byteArray = []
  2062. for (var i = 0; i < str.length; i++) {
  2063. // Node's code seems to be doing this and not & 0x7F..
  2064. byteArray.push(str.charCodeAt(i) & 0xFF)
  2065. }
  2066. return byteArray
  2067. }
  2068. function utf16leToBytes (str) {
  2069. var c, hi, lo
  2070. var byteArray = []
  2071. for (var i = 0; i < str.length; i++) {
  2072. c = str.charCodeAt(i)
  2073. hi = c >> 8
  2074. lo = c % 256
  2075. byteArray.push(lo)
  2076. byteArray.push(hi)
  2077. }
  2078. return byteArray
  2079. }
  2080. function base64ToBytes (str) {
  2081. return base64.toByteArray(str)
  2082. }
  2083. function blitBuffer (src, dst, offset, length, unitSize) {
  2084. if (unitSize) length -= length % unitSize;
  2085. for (var i = 0; i < length; i++) {
  2086. if ((i + offset >= dst.length) || (i >= src.length))
  2087. break
  2088. dst[i + offset] = src[i]
  2089. }
  2090. return i
  2091. }
  2092. function decodeUtf8Char (str) {
  2093. try {
  2094. return decodeURIComponent(str)
  2095. } catch (err) {
  2096. return String.fromCharCode(0xFFFD) // UTF 8 invalid char
  2097. }
  2098. }
  2099. },{"base64-js":2,"ieee754":3,"is-array":4}],2:[function(_dereq_,module,exports){
  2100. var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  2101. ;(function (exports) {
  2102. 'use strict';
  2103. var Arr = (typeof Uint8Array !== 'undefined')
  2104. ? Uint8Array
  2105. : Array
  2106. var PLUS = '+'.charCodeAt(0)
  2107. var SLASH = '/'.charCodeAt(0)
  2108. var NUMBER = '0'.charCodeAt(0)
  2109. var LOWER = 'a'.charCodeAt(0)
  2110. var UPPER = 'A'.charCodeAt(0)
  2111. function decode (elt) {
  2112. var code = elt.charCodeAt(0)
  2113. if (code === PLUS)
  2114. return 62 // '+'
  2115. if (code === SLASH)
  2116. return 63 // '/'
  2117. if (code < NUMBER)
  2118. return -1 //no match
  2119. if (code < NUMBER + 10)
  2120. return code - NUMBER + 26 + 26
  2121. if (code < UPPER + 26)
  2122. return code - UPPER
  2123. if (code < LOWER + 26)
  2124. return code - LOWER + 26
  2125. }
  2126. function b64ToByteArray (b64) {
  2127. var i, j, l, tmp, placeHolders, arr
  2128. if (b64.length % 4 > 0) {
  2129. throw new Error('Invalid string. Length must be a multiple of 4')
  2130. }
  2131. // the number of equal signs (place holders)
  2132. // if there are two placeholders, than the two characters before it
  2133. // represent one byte
  2134. // if there is only one, then the three characters before it represent 2 bytes
  2135. // this is just a cheap hack to not do indexOf twice
  2136. var len = b64.length
  2137. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
  2138. // base64 is 4/3 + up to two characters of the original data
  2139. arr = new Arr(b64.length * 3 / 4 - placeHolders)
  2140. // if there are placeholders, only get up to the last complete 4 chars
  2141. l = placeHolders > 0 ? b64.length - 4 : b64.length
  2142. var L = 0
  2143. function push (v) {
  2144. arr[L++] = v
  2145. }
  2146. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  2147. tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
  2148. push((tmp & 0xFF0000) >> 16)
  2149. push((tmp & 0xFF00) >> 8)
  2150. push(tmp & 0xFF)
  2151. }
  2152. if (placeHolders === 2) {
  2153. tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
  2154. push(tmp & 0xFF)
  2155. } else if (placeHolders === 1) {
  2156. tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
  2157. push((tmp >> 8) & 0xFF)
  2158. push(tmp & 0xFF)
  2159. }
  2160. return arr
  2161. }
  2162. function uint8ToBase64 (uint8) {
  2163. var i,
  2164. extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
  2165. output = "",
  2166. temp, length
  2167. function encode (num) {
  2168. return lookup.charAt(num)
  2169. }
  2170. function tripletToBase64 (num) {
  2171. return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
  2172. }
  2173. // go through the array every three bytes, we'll deal with trailing stuff later
  2174. for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
  2175. temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  2176. output += tripletToBase64(temp)
  2177. }
  2178. // pad the end with zeros, but make sure to not forget the extra bytes
  2179. switch (extraBytes) {
  2180. case 1:
  2181. temp = uint8[uint8.length - 1]
  2182. output += encode(temp >> 2)
  2183. output += encode((temp << 4) & 0x3F)
  2184. output += '=='
  2185. break
  2186. case 2:
  2187. temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
  2188. output += encode(temp >> 10)
  2189. output += encode((temp >> 4) & 0x3F)
  2190. output += encode((temp << 2) & 0x3F)
  2191. output += '='
  2192. break
  2193. }
  2194. return output
  2195. }
  2196. exports.toByteArray = b64ToByteArray
  2197. exports.fromByteArray = uint8ToBase64
  2198. }(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
  2199. },{}],3:[function(_dereq_,module,exports){
  2200. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2201. var e, m
  2202. var eLen = nBytes * 8 - mLen - 1
  2203. var eMax = (1 << eLen) - 1
  2204. var eBias = eMax >> 1
  2205. var nBits = -7
  2206. var i = isLE ? (nBytes - 1) : 0
  2207. var d = isLE ? -1 : 1
  2208. var s = buffer[offset + i]
  2209. i += d
  2210. e = s & ((1 << (-nBits)) - 1)
  2211. s >>= (-nBits)
  2212. nBits += eLen
  2213. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2214. m = e & ((1 << (-nBits)) - 1)
  2215. e >>= (-nBits)
  2216. nBits += mLen
  2217. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2218. if (e === 0) {
  2219. e = 1 - eBias
  2220. } else if (e === eMax) {
  2221. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2222. } else {
  2223. m = m + Math.pow(2, mLen)
  2224. e = e - eBias
  2225. }
  2226. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2227. }
  2228. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2229. var e, m, c
  2230. var eLen = nBytes * 8 - mLen - 1
  2231. var eMax = (1 << eLen) - 1
  2232. var eBias = eMax >> 1
  2233. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2234. var i = isLE ? 0 : (nBytes - 1)
  2235. var d = isLE ? 1 : -1
  2236. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2237. value = Math.abs(value)
  2238. if (isNaN(value) || value === Infinity) {
  2239. m = isNaN(value) ? 1 : 0
  2240. e = eMax
  2241. } else {
  2242. e = Math.floor(Math.log(value) / Math.LN2)
  2243. if (value * (c = Math.pow(2, -e)) < 1) {
  2244. e--
  2245. c *= 2
  2246. }
  2247. if (e + eBias >= 1) {
  2248. value += rt / c
  2249. } else {
  2250. value += rt * Math.pow(2, 1 - eBias)
  2251. }
  2252. if (value * c >= 2) {
  2253. e++
  2254. c /= 2
  2255. }
  2256. if (e + eBias >= eMax) {
  2257. m = 0
  2258. e = eMax
  2259. } else if (e + eBias >= 1) {
  2260. m = (value * c - 1) * Math.pow(2, mLen)
  2261. e = e + eBias
  2262. } else {
  2263. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2264. e = 0
  2265. }
  2266. }
  2267. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2268. e = (e << mLen) | m
  2269. eLen += mLen
  2270. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2271. buffer[offset + i - d] |= s * 128
  2272. }
  2273. },{}],4:[function(_dereq_,module,exports){
  2274. /**
  2275. * isArray
  2276. */
  2277. var isArray = Array.isArray;
  2278. /**
  2279. * toString
  2280. */
  2281. var str = Object.prototype.toString;
  2282. /**
  2283. * Whether or not the given `val`
  2284. * is an array.
  2285. *
  2286. * example:
  2287. *
  2288. * isArray([]);
  2289. * // > true
  2290. * isArray(arguments);
  2291. * // > false
  2292. * isArray('');
  2293. * // > false
  2294. *
  2295. * @param {mixed} val
  2296. * @return {bool}
  2297. */
  2298. module.exports = isArray || function (val) {
  2299. return !! val && '[object Array]' == str.call(val);
  2300. };
  2301. },{}],5:[function(_dereq_,module,exports){
  2302. 'use strict';
  2303. var DataReader = _dereq_('./dataReader');
  2304. function ArrayReader(data) {
  2305. if (data) {
  2306. this.data = data;
  2307. this.length = this.data.length;
  2308. this.index = 0;
  2309. this.zero = 0;
  2310. for(var i = 0; i < this.data.length; i++) {
  2311. data[i] = data[i] & 0xFF;
  2312. }
  2313. }
  2314. }
  2315. ArrayReader.prototype = new DataReader();
  2316. /**
  2317. * @see DataReader.byteAt
  2318. */
  2319. ArrayReader.prototype.byteAt = function(i) {
  2320. return this.data[this.zero + i];
  2321. };
  2322. /**
  2323. * @see DataReader.lastIndexOfSignature
  2324. */
  2325. ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  2326. var sig0 = sig.charCodeAt(0),
  2327. sig1 = sig.charCodeAt(1),
  2328. sig2 = sig.charCodeAt(2),
  2329. sig3 = sig.charCodeAt(3);
  2330. for (var i = this.length - 4; i >= 0; --i) {
  2331. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  2332. return i - this.zero;
  2333. }
  2334. }
  2335. return -1;
  2336. };
  2337. /**
  2338. * @see DataReader.readData
  2339. */
  2340. ArrayReader.prototype.readData = function(size) {
  2341. this.checkOffset(size);
  2342. if(size === 0) {
  2343. return [];
  2344. }
  2345. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  2346. this.index += size;
  2347. return result;
  2348. };
  2349. module.exports = ArrayReader;
  2350. },{"./dataReader":10}],6:[function(_dereq_,module,exports){
  2351. 'use strict';
  2352. // private property
  2353. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  2354. // public method for encoding
  2355. exports.encode = function(input, utf8) {
  2356. var output = "";
  2357. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  2358. var i = 0;
  2359. while (i < input.length) {
  2360. chr1 = input.charCodeAt(i++);
  2361. chr2 = input.charCodeAt(i++);
  2362. chr3 = input.charCodeAt(i++);
  2363. enc1 = chr1 >> 2;
  2364. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  2365. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  2366. enc4 = chr3 & 63;
  2367. if (isNaN(chr2)) {
  2368. enc3 = enc4 = 64;
  2369. }
  2370. else if (isNaN(chr3)) {
  2371. enc4 = 64;
  2372. }
  2373. output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  2374. }
  2375. return output;
  2376. };
  2377. // public method for decoding
  2378. exports.decode = function(input, utf8) {
  2379. var output = "";
  2380. var chr1, chr2, chr3;
  2381. var enc1, enc2, enc3, enc4;
  2382. var i = 0;
  2383. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  2384. while (i < input.length) {
  2385. enc1 = _keyStr.indexOf(input.charAt(i++));
  2386. enc2 = _keyStr.indexOf(input.charAt(i++));
  2387. enc3 = _keyStr.indexOf(input.charAt(i++));
  2388. enc4 = _keyStr.indexOf(input.charAt(i++));
  2389. chr1 = (enc1 << 2) | (enc2 >> 4);
  2390. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  2391. chr3 = ((enc3 & 3) << 6) | enc4;
  2392. output = output + String.fromCharCode(chr1);
  2393. if (enc3 != 64) {
  2394. output = output + String.fromCharCode(chr2);
  2395. }
  2396. if (enc4 != 64) {
  2397. output = output + String.fromCharCode(chr3);
  2398. }
  2399. }
  2400. return output;
  2401. };
  2402. },{}],7:[function(_dereq_,module,exports){
  2403. 'use strict';
  2404. function CompressedObject() {
  2405. this.compressedSize = 0;
  2406. this.uncompressedSize = 0;
  2407. this.crc32 = 0;
  2408. this.compressionMethod = null;
  2409. this.compressedContent = null;
  2410. }
  2411. CompressedObject.prototype = {
  2412. /**
  2413. * Return the decompressed content in an unspecified format.
  2414. * The format will depend on the decompressor.
  2415. * @return {Object} the decompressed content.
  2416. */
  2417. getContent: function() {
  2418. return null; // see implementation
  2419. },
  2420. /**
  2421. * Return the compressed content in an unspecified format.
  2422. * The format will depend on the compressed conten source.
  2423. * @return {Object} the compressed content.
  2424. */
  2425. getCompressedContent: function() {
  2426. return null; // see implementation
  2427. }
  2428. };
  2429. module.exports = CompressedObject;
  2430. },{}],8:[function(_dereq_,module,exports){
  2431. 'use strict';
  2432. exports.STORE = {
  2433. magic: "\x00\x00",
  2434. compress: function(content, compressionOptions) {
  2435. return content; // no compression
  2436. },
  2437. uncompress: function(content) {
  2438. return content; // no compression
  2439. },
  2440. compressInputType: null,
  2441. uncompressInputType: null
  2442. };
  2443. exports.DEFLATE = _dereq_('./flate');
  2444. },{"./flate":13}],9:[function(_dereq_,module,exports){
  2445. 'use strict';
  2446. var utils = _dereq_('./utils');
  2447. var table = [
  2448. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
  2449. 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  2450. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
  2451. 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  2452. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
  2453. 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  2454. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
  2455. 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  2456. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
  2457. 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  2458. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
  2459. 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  2460. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
  2461. 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  2462. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
  2463. 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  2464. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
  2465. 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  2466. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
  2467. 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  2468. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
  2469. 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  2470. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
  2471. 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  2472. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
  2473. 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  2474. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
  2475. 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  2476. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
  2477. 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  2478. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
  2479. 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  2480. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
  2481. 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  2482. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
  2483. 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  2484. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
  2485. 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  2486. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
  2487. 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  2488. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
  2489. 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  2490. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
  2491. 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  2492. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
  2493. 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  2494. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
  2495. 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  2496. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
  2497. 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  2498. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
  2499. 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  2500. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
  2501. 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  2502. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
  2503. 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  2504. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
  2505. 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  2506. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
  2507. 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  2508. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
  2509. 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  2510. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
  2511. 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  2512. ];
  2513. /**
  2514. *
  2515. * Javascript crc32
  2516. * http://www.webtoolkit.info/
  2517. *
  2518. */
  2519. module.exports = function crc32(input, crc) {
  2520. if (typeof input === "undefined" || !input.length) {
  2521. return 0;
  2522. }
  2523. var isArray = utils.getTypeOf(input) !== "string";
  2524. if (typeof(crc) == "undefined") {
  2525. crc = 0;
  2526. }
  2527. var x = 0;
  2528. var y = 0;
  2529. var b = 0;
  2530. crc = crc ^ (-1);
  2531. for (var i = 0, iTop = input.length; i < iTop; i++) {
  2532. b = isArray ? input[i] : input.charCodeAt(i);
  2533. y = (crc ^ b) & 0xFF;
  2534. x = table[y];
  2535. crc = (crc >>> 8) ^ x;
  2536. }
  2537. return crc ^ (-1);
  2538. };
  2539. // vim: set shiftwidth=4 softtabstop=4:
  2540. },{"./utils":26}],10:[function(_dereq_,module,exports){
  2541. 'use strict';
  2542. var utils = _dereq_('./utils');
  2543. function DataReader(data) {
  2544. this.data = null; // type : see implementation
  2545. this.length = 0;
  2546. this.index = 0;
  2547. this.zero = 0;
  2548. }
  2549. DataReader.prototype = {
  2550. /**
  2551. * Check that the offset will not go too far.
  2552. * @param {string} offset the additional offset to check.
  2553. * @throws {Error} an Error if the offset is out of bounds.
  2554. */
  2555. checkOffset: function(offset) {
  2556. this.checkIndex(this.index + offset);
  2557. },
  2558. /**
  2559. * Check that the specifed index will not be too far.
  2560. * @param {string} newIndex the index to check.
  2561. * @throws {Error} an Error if the index is out of bounds.
  2562. */
  2563. checkIndex: function(newIndex) {
  2564. if (this.length < this.zero + newIndex || newIndex < 0) {
  2565. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  2566. }
  2567. },
  2568. /**
  2569. * Change the index.
  2570. * @param {number} newIndex The new index.
  2571. * @throws {Error} if the new index is out of the data.
  2572. */
  2573. setIndex: function(newIndex) {
  2574. this.checkIndex(newIndex);
  2575. this.index = newIndex;
  2576. },
  2577. /**
  2578. * Skip the next n bytes.
  2579. * @param {number} n the number of bytes to skip.
  2580. * @throws {Error} if the new index is out of the data.
  2581. */
  2582. skip: function(n) {
  2583. this.setIndex(this.index + n);
  2584. },
  2585. /**
  2586. * Get the byte at the specified index.
  2587. * @param {number} i the index to use.
  2588. * @return {number} a byte.
  2589. */
  2590. byteAt: function(i) {
  2591. // see implementations
  2592. },
  2593. /**
  2594. * Get the next number with a given byte size.
  2595. * @param {number} size the number of bytes to read.
  2596. * @return {number} the corresponding number.
  2597. */
  2598. readInt: function(size) {
  2599. var result = 0,
  2600. i;
  2601. this.checkOffset(size);
  2602. for (i = this.index + size - 1; i >= this.index; i--) {
  2603. result = (result << 8) + this.byteAt(i);
  2604. }
  2605. this.index += size;
  2606. return result;
  2607. },
  2608. /**
  2609. * Get the next string with a given byte size.
  2610. * @param {number} size the number of bytes to read.
  2611. * @return {string} the corresponding string.
  2612. */
  2613. readString: function(size) {
  2614. return utils.transformTo("string", this.readData(size));
  2615. },
  2616. /**
  2617. * Get raw data without conversion, <size> bytes.
  2618. * @param {number} size the number of bytes to read.
  2619. * @return {Object} the raw data, implementation specific.
  2620. */
  2621. readData: function(size) {
  2622. // see implementations
  2623. },
  2624. /**
  2625. * Find the last occurence of a zip signature (4 bytes).
  2626. * @param {string} sig the signature to find.
  2627. * @return {number} the index of the last occurence, -1 if not found.
  2628. */
  2629. lastIndexOfSignature: function(sig) {
  2630. // see implementations
  2631. },
  2632. /**
  2633. * Get the next date.
  2634. * @return {Date} the date.
  2635. */
  2636. readDate: function() {
  2637. var dostime = this.readInt(4);
  2638. return new Date(
  2639. ((dostime >> 25) & 0x7f) + 1980, // year
  2640. ((dostime >> 21) & 0x0f) - 1, // month
  2641. (dostime >> 16) & 0x1f, // day
  2642. (dostime >> 11) & 0x1f, // hour
  2643. (dostime >> 5) & 0x3f, // minute
  2644. (dostime & 0x1f) << 1); // second
  2645. }
  2646. };
  2647. module.exports = DataReader;
  2648. },{"./utils":26}],11:[function(_dereq_,module,exports){
  2649. 'use strict';
  2650. exports.base64 = false;
  2651. exports.binary = false;
  2652. exports.dir = false;
  2653. exports.createFolders = false;
  2654. exports.date = null;
  2655. exports.compression = null;
  2656. exports.compressionOptions = null;
  2657. exports.comment = null;
  2658. exports.unixPermissions = null;
  2659. exports.dosPermissions = null;
  2660. },{}],12:[function(_dereq_,module,exports){
  2661. 'use strict';
  2662. var utils = _dereq_('./utils');
  2663. /**
  2664. * @deprecated
  2665. * This function will be removed in a future version without replacement.
  2666. */
  2667. exports.string2binary = function(str) {
  2668. return utils.string2binary(str);
  2669. };
  2670. /**
  2671. * @deprecated
  2672. * This function will be removed in a future version without replacement.
  2673. */
  2674. exports.string2Uint8Array = function(str) {
  2675. return utils.transformTo("uint8array", str);
  2676. };
  2677. /**
  2678. * @deprecated
  2679. * This function will be removed in a future version without replacement.
  2680. */
  2681. exports.uint8Array2String = function(array) {
  2682. return utils.transformTo("string", array);
  2683. };
  2684. /**
  2685. * @deprecated
  2686. * This function will be removed in a future version without replacement.
  2687. */
  2688. exports.string2Blob = function(str) {
  2689. var buffer = utils.transformTo("arraybuffer", str);
  2690. return utils.arrayBuffer2Blob(buffer);
  2691. };
  2692. /**
  2693. * @deprecated
  2694. * This function will be removed in a future version without replacement.
  2695. */
  2696. exports.arrayBuffer2Blob = function(buffer) {
  2697. return utils.arrayBuffer2Blob(buffer);
  2698. };
  2699. /**
  2700. * @deprecated
  2701. * This function will be removed in a future version without replacement.
  2702. */
  2703. exports.transformTo = function(outputType, input) {
  2704. return utils.transformTo(outputType, input);
  2705. };
  2706. /**
  2707. * @deprecated
  2708. * This function will be removed in a future version without replacement.
  2709. */
  2710. exports.getTypeOf = function(input) {
  2711. return utils.getTypeOf(input);
  2712. };
  2713. /**
  2714. * @deprecated
  2715. * This function will be removed in a future version without replacement.
  2716. */
  2717. exports.checkSupport = function(type) {
  2718. return utils.checkSupport(type);
  2719. };
  2720. /**
  2721. * @deprecated
  2722. * This value will be removed in a future version without replacement.
  2723. */
  2724. exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
  2725. /**
  2726. * @deprecated
  2727. * This value will be removed in a future version without replacement.
  2728. */
  2729. exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
  2730. /**
  2731. * @deprecated
  2732. * This function will be removed in a future version without replacement.
  2733. */
  2734. exports.pretty = function(str) {
  2735. return utils.pretty(str);
  2736. };
  2737. /**
  2738. * @deprecated
  2739. * This function will be removed in a future version without replacement.
  2740. */
  2741. exports.findCompression = function(compressionMethod) {
  2742. return utils.findCompression(compressionMethod);
  2743. };
  2744. /**
  2745. * @deprecated
  2746. * This function will be removed in a future version without replacement.
  2747. */
  2748. exports.isRegExp = function (object) {
  2749. return utils.isRegExp(object);
  2750. };
  2751. },{"./utils":26}],13:[function(_dereq_,module,exports){
  2752. 'use strict';
  2753. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  2754. var pako = _dereq_("pako");
  2755. exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  2756. exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  2757. exports.magic = "\x08\x00";
  2758. exports.compress = function(input, compressionOptions) {
  2759. return pako.deflateRaw(input, {
  2760. level : compressionOptions.level || -1 // default compression
  2761. });
  2762. };
  2763. exports.uncompress = function(input) {
  2764. return pako.inflateRaw(input);
  2765. };
  2766. },{"pako":29}],14:[function(_dereq_,module,exports){
  2767. 'use strict';
  2768. var base64 = _dereq_('./base64');
  2769. /**
  2770. Usage:
  2771. zip = new JSZip();
  2772. zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
  2773. zip.folder("images").file("smile.gif", base64Data, {base64: true});
  2774. zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
  2775. zip.remove("tempfile");
  2776. base64zip = zip.generate();
  2777. **/
  2778. /**
  2779. * Representation a of zip file in js
  2780. * @constructor
  2781. * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
  2782. * @param {Object=} options the options for creating this objects (optional).
  2783. */
  2784. function JSZip(data, options) {
  2785. // if this constructor is used without `new`, it adds `new` before itself:
  2786. if(!(this instanceof JSZip)) return new JSZip(data, options);
  2787. // object containing the files :
  2788. // {
  2789. // "folder/" : {...},
  2790. // "folder/data.txt" : {...}
  2791. // }
  2792. this.files = {};
  2793. this.comment = null;
  2794. // Where we are in the hierarchy
  2795. this.root = "";
  2796. if (data) {
  2797. this.load(data, options);
  2798. }
  2799. this.clone = function() {
  2800. var newObj = new JSZip();
  2801. for (var i in this) {
  2802. if (typeof this[i] !== "function") {
  2803. newObj[i] = this[i];
  2804. }
  2805. }
  2806. return newObj;
  2807. };
  2808. }
  2809. JSZip.prototype = _dereq_('./object');
  2810. JSZip.prototype.load = _dereq_('./load');
  2811. JSZip.support = _dereq_('./support');
  2812. JSZip.defaults = _dereq_('./defaults');
  2813. /**
  2814. * @deprecated
  2815. * This namespace will be removed in a future version without replacement.
  2816. */
  2817. JSZip.utils = _dereq_('./deprecatedPublicUtils');
  2818. JSZip.base64 = {
  2819. /**
  2820. * @deprecated
  2821. * This method will be removed in a future version without replacement.
  2822. */
  2823. encode : function(input) {
  2824. return base64.encode(input);
  2825. },
  2826. /**
  2827. * @deprecated
  2828. * This method will be removed in a future version without replacement.
  2829. */
  2830. decode : function(input) {
  2831. return base64.decode(input);
  2832. }
  2833. };
  2834. JSZip.compressions = _dereq_('./compressions');
  2835. module.exports = JSZip;
  2836. },{"./base64":6,"./compressions":8,"./defaults":11,"./deprecatedPublicUtils":12,"./load":15,"./object":18,"./support":22}],15:[function(_dereq_,module,exports){
  2837. 'use strict';
  2838. var base64 = _dereq_('./base64');
  2839. var utf8 = _dereq_('./utf8');
  2840. var utils = _dereq_('./utils');
  2841. var ZipEntries = _dereq_('./zipEntries');
  2842. module.exports = function(data, options) {
  2843. var files, zipEntries, i, input;
  2844. options = utils.extend(options || {}, {
  2845. base64: false,
  2846. checkCRC32: false,
  2847. optimizedBinaryString : false,
  2848. createFolders: false,
  2849. decodeFileName: utf8.utf8decode
  2850. });
  2851. if (options.base64) {
  2852. data = base64.decode(data);
  2853. }
  2854. zipEntries = new ZipEntries(data, options);
  2855. files = zipEntries.files;
  2856. for (i = 0; i < files.length; i++) {
  2857. input = files[i];
  2858. this.file(input.fileNameStr, input.decompressed, {
  2859. binary: true,
  2860. optimizedBinaryString: true,
  2861. date: input.date,
  2862. dir: input.dir,
  2863. comment : input.fileCommentStr.length ? input.fileCommentStr : null,
  2864. unixPermissions : input.unixPermissions,
  2865. dosPermissions : input.dosPermissions,
  2866. createFolders: options.createFolders
  2867. });
  2868. }
  2869. if (zipEntries.zipComment.length) {
  2870. this.comment = zipEntries.zipComment;
  2871. }
  2872. return this;
  2873. };
  2874. },{"./base64":6,"./utf8":25,"./utils":26,"./zipEntries":27}],16:[function(_dereq_,module,exports){
  2875. (function (Buffer){
  2876. 'use strict';
  2877. module.exports = function(data, encoding){
  2878. return new Buffer(data, encoding);
  2879. };
  2880. module.exports.test = function(b){
  2881. return Buffer.isBuffer(b);
  2882. };
  2883. }).call(this,_dereq_("buffer").Buffer)
  2884. },{"buffer":1}],17:[function(_dereq_,module,exports){
  2885. 'use strict';
  2886. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  2887. function NodeBufferReader(data) {
  2888. this.data = data;
  2889. this.length = this.data.length;
  2890. this.index = 0;
  2891. this.zero = 0;
  2892. }
  2893. NodeBufferReader.prototype = new Uint8ArrayReader();
  2894. /**
  2895. * @see DataReader.readData
  2896. */
  2897. NodeBufferReader.prototype.readData = function(size) {
  2898. this.checkOffset(size);
  2899. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  2900. this.index += size;
  2901. return result;
  2902. };
  2903. module.exports = NodeBufferReader;
  2904. },{"./uint8ArrayReader":23}],18:[function(_dereq_,module,exports){
  2905. 'use strict';
  2906. var support = _dereq_('./support');
  2907. var utils = _dereq_('./utils');
  2908. var crc32 = _dereq_('./crc32');
  2909. var signature = _dereq_('./signature');
  2910. var defaults = _dereq_('./defaults');
  2911. var base64 = _dereq_('./base64');
  2912. var compressions = _dereq_('./compressions');
  2913. var CompressedObject = _dereq_('./compressedObject');
  2914. var nodeBuffer = _dereq_('./nodeBuffer');
  2915. var utf8 = _dereq_('./utf8');
  2916. var StringWriter = _dereq_('./stringWriter');
  2917. var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter');
  2918. /**
  2919. * Returns the raw data of a ZipObject, decompress the content if necessary.
  2920. * @param {ZipObject} file the file to use.
  2921. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  2922. */
  2923. var getRawData = function(file) {
  2924. if (file._data instanceof CompressedObject) {
  2925. file._data = file._data.getContent();
  2926. file.options.binary = true;
  2927. file.options.base64 = false;
  2928. if (utils.getTypeOf(file._data) === "uint8array") {
  2929. var copy = file._data;
  2930. // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
  2931. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
  2932. file._data = new Uint8Array(copy.length);
  2933. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  2934. if (copy.length !== 0) {
  2935. file._data.set(copy, 0);
  2936. }
  2937. }
  2938. }
  2939. return file._data;
  2940. };
  2941. /**
  2942. * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
  2943. * @param {ZipObject} file the file to use.
  2944. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  2945. */
  2946. var getBinaryData = function(file) {
  2947. var result = getRawData(file),
  2948. type = utils.getTypeOf(result);
  2949. if (type === "string") {
  2950. if (!file.options.binary) {
  2951. // unicode text !
  2952. // unicode string => binary string is a painful process, check if we can avoid it.
  2953. if (support.nodebuffer) {
  2954. return nodeBuffer(result, "utf-8");
  2955. }
  2956. }
  2957. return file.asBinary();
  2958. }
  2959. return result;
  2960. };
  2961. /**
  2962. * Transform this._data into a string.
  2963. * @param {function} filter a function String -> String, applied if not null on the result.
  2964. * @return {String} the string representing this._data.
  2965. */
  2966. var dataToString = function(asUTF8) {
  2967. var result = getRawData(this);
  2968. if (result === null || typeof result === "undefined") {
  2969. return "";
  2970. }
  2971. // if the data is a base64 string, we decode it before checking the encoding !
  2972. if (this.options.base64) {
  2973. result = base64.decode(result);
  2974. }
  2975. if (asUTF8 && this.options.binary) {
  2976. // JSZip.prototype.utf8decode supports arrays as input
  2977. // skip to array => string step, utf8decode will do it.
  2978. result = out.utf8decode(result);
  2979. }
  2980. else {
  2981. // no utf8 transformation, do the array => string step.
  2982. result = utils.transformTo("string", result);
  2983. }
  2984. if (!asUTF8 && !this.options.binary) {
  2985. result = utils.transformTo("string", out.utf8encode(result));
  2986. }
  2987. return result;
  2988. };
  2989. /**
  2990. * A simple object representing a file in the zip file.
  2991. * @constructor
  2992. * @param {string} name the name of the file
  2993. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  2994. * @param {Object} options the options of the file
  2995. */
  2996. var ZipObject = function(name, data, options) {
  2997. this.name = name;
  2998. this.dir = options.dir;
  2999. this.date = options.date;
  3000. this.comment = options.comment;
  3001. this.unixPermissions = options.unixPermissions;
  3002. this.dosPermissions = options.dosPermissions;
  3003. this._data = data;
  3004. this.options = options;
  3005. /*
  3006. * This object contains initial values for dir and date.
  3007. * With them, we can check if the user changed the deprecated metadata in
  3008. * `ZipObject#options` or not.
  3009. */
  3010. this._initialMetadata = {
  3011. dir : options.dir,
  3012. date : options.date
  3013. };
  3014. };
  3015. ZipObject.prototype = {
  3016. /**
  3017. * Return the content as UTF8 string.
  3018. * @return {string} the UTF8 string.
  3019. */
  3020. asText: function() {
  3021. return dataToString.call(this, true);
  3022. },
  3023. /**
  3024. * Returns the binary content.
  3025. * @return {string} the content as binary.
  3026. */
  3027. asBinary: function() {
  3028. return dataToString.call(this, false);
  3029. },
  3030. /**
  3031. * Returns the content as a nodejs Buffer.
  3032. * @return {Buffer} the content as a Buffer.
  3033. */
  3034. asNodeBuffer: function() {
  3035. var result = getBinaryData(this);
  3036. return utils.transformTo("nodebuffer", result);
  3037. },
  3038. /**
  3039. * Returns the content as an Uint8Array.
  3040. * @return {Uint8Array} the content as an Uint8Array.
  3041. */
  3042. asUint8Array: function() {
  3043. var result = getBinaryData(this);
  3044. return utils.transformTo("uint8array", result);
  3045. },
  3046. /**
  3047. * Returns the content as an ArrayBuffer.
  3048. * @return {ArrayBuffer} the content as an ArrayBufer.
  3049. */
  3050. asArrayBuffer: function() {
  3051. return this.asUint8Array().buffer;
  3052. }
  3053. };
  3054. /**
  3055. * Transform an integer into a string in hexadecimal.
  3056. * @private
  3057. * @param {number} dec the number to convert.
  3058. * @param {number} bytes the number of bytes to generate.
  3059. * @returns {string} the result.
  3060. */
  3061. var decToHex = function(dec, bytes) {
  3062. var hex = "",
  3063. i;
  3064. for (i = 0; i < bytes; i++) {
  3065. hex += String.fromCharCode(dec & 0xff);
  3066. dec = dec >>> 8;
  3067. }
  3068. return hex;
  3069. };
  3070. /**
  3071. * Transforms the (incomplete) options from the user into the complete
  3072. * set of options to create a file.
  3073. * @private
  3074. * @param {Object} o the options from the user.
  3075. * @return {Object} the complete set of options.
  3076. */
  3077. var prepareFileAttrs = function(o) {
  3078. o = o || {};
  3079. if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
  3080. o.binary = true;
  3081. }
  3082. o = utils.extend(o, defaults);
  3083. o.date = o.date || new Date();
  3084. if (o.compression !== null) o.compression = o.compression.toUpperCase();
  3085. return o;
  3086. };
  3087. /**
  3088. * Add a file in the current folder.
  3089. * @private
  3090. * @param {string} name the name of the file
  3091. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  3092. * @param {Object} o the options of the file
  3093. * @return {Object} the new file.
  3094. */
  3095. var fileAdd = function(name, data, o) {
  3096. // be sure sub folders exist
  3097. var dataType = utils.getTypeOf(data),
  3098. parent;
  3099. o = prepareFileAttrs(o);
  3100. if (typeof o.unixPermissions === "string") {
  3101. o.unixPermissions = parseInt(o.unixPermissions, 8);
  3102. }
  3103. // UNX_IFDIR 0040000 see zipinfo.c
  3104. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  3105. o.dir = true;
  3106. }
  3107. // Bit 4 Directory
  3108. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  3109. o.dir = true;
  3110. }
  3111. if (o.dir) {
  3112. name = forceTrailingSlash(name);
  3113. }
  3114. if (o.createFolders && (parent = parentFolder(name))) {
  3115. folderAdd.call(this, parent, true);
  3116. }
  3117. if (o.dir || data === null || typeof data === "undefined") {
  3118. o.base64 = false;
  3119. o.binary = false;
  3120. data = null;
  3121. dataType = null;
  3122. }
  3123. else if (dataType === "string") {
  3124. if (o.binary && !o.base64) {
  3125. // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
  3126. if (o.optimizedBinaryString !== true) {
  3127. // this is a string, not in a base64 format.
  3128. // Be sure that this is a correct "binary string"
  3129. data = utils.string2binary(data);
  3130. }
  3131. }
  3132. }
  3133. else { // arraybuffer, uint8array, ...
  3134. o.base64 = false;
  3135. o.binary = true;
  3136. if (!dataType && !(data instanceof CompressedObject)) {
  3137. throw new Error("The data of '" + name + "' is in an unsupported format !");
  3138. }
  3139. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  3140. if (dataType === "arraybuffer") {
  3141. data = utils.transformTo("uint8array", data);
  3142. }
  3143. }
  3144. var object = new ZipObject(name, data, o);
  3145. this.files[name] = object;
  3146. return object;
  3147. };
  3148. /**
  3149. * Find the parent folder of the path.
  3150. * @private
  3151. * @param {string} path the path to use
  3152. * @return {string} the parent folder, or ""
  3153. */
  3154. var parentFolder = function (path) {
  3155. if (path.slice(-1) == '/') {
  3156. path = path.substring(0, path.length - 1);
  3157. }
  3158. var lastSlash = path.lastIndexOf('/');
  3159. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  3160. };
  3161. /**
  3162. * Returns the path with a slash at the end.
  3163. * @private
  3164. * @param {String} path the path to check.
  3165. * @return {String} the path with a trailing slash.
  3166. */
  3167. var forceTrailingSlash = function(path) {
  3168. // Check the name ends with a /
  3169. if (path.slice(-1) != "/") {
  3170. path += "/"; // IE doesn't like substr(-1)
  3171. }
  3172. return path;
  3173. };
  3174. /**
  3175. * Add a (sub) folder in the current folder.
  3176. * @private
  3177. * @param {string} name the folder's name
  3178. * @param {boolean=} [createFolders] If true, automatically create sub
  3179. * folders. Defaults to false.
  3180. * @return {Object} the new folder.
  3181. */
  3182. var folderAdd = function(name, createFolders) {
  3183. createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
  3184. name = forceTrailingSlash(name);
  3185. // Does this folder already exist?
  3186. if (!this.files[name]) {
  3187. fileAdd.call(this, name, null, {
  3188. dir: true,
  3189. createFolders: createFolders
  3190. });
  3191. }
  3192. return this.files[name];
  3193. };
  3194. /**
  3195. * Generate a JSZip.CompressedObject for a given zipOject.
  3196. * @param {ZipObject} file the object to read.
  3197. * @param {JSZip.compression} compression the compression to use.
  3198. * @param {Object} compressionOptions the options to use when compressing.
  3199. * @return {JSZip.CompressedObject} the compressed result.
  3200. */
  3201. var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
  3202. var result = new CompressedObject(),
  3203. content;
  3204. // the data has not been decompressed, we might reuse things !
  3205. if (file._data instanceof CompressedObject) {
  3206. result.uncompressedSize = file._data.uncompressedSize;
  3207. result.crc32 = file._data.crc32;
  3208. if (result.uncompressedSize === 0 || file.dir) {
  3209. compression = compressions['STORE'];
  3210. result.compressedContent = "";
  3211. result.crc32 = 0;
  3212. }
  3213. else if (file._data.compressionMethod === compression.magic) {
  3214. result.compressedContent = file._data.getCompressedContent();
  3215. }
  3216. else {
  3217. content = file._data.getContent();
  3218. // need to decompress / recompress
  3219. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  3220. }
  3221. }
  3222. else {
  3223. // have uncompressed data
  3224. content = getBinaryData(file);
  3225. if (!content || content.length === 0 || file.dir) {
  3226. compression = compressions['STORE'];
  3227. content = "";
  3228. }
  3229. result.uncompressedSize = content.length;
  3230. result.crc32 = crc32(content);
  3231. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  3232. }
  3233. result.compressedSize = result.compressedContent.length;
  3234. result.compressionMethod = compression.magic;
  3235. return result;
  3236. };
  3237. /**
  3238. * Generate the UNIX part of the external file attributes.
  3239. * @param {Object} unixPermissions the unix permissions or null.
  3240. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  3241. * @return {Number} a 32 bit integer.
  3242. *
  3243. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  3244. *
  3245. * TTTTsstrwxrwxrwx0000000000ADVSHR
  3246. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  3247. * ^^^_________________________ setuid, setgid, sticky
  3248. * ^^^^^^^^^________________ permissions
  3249. * ^^^^^^^^^^______ not used ?
  3250. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  3251. */
  3252. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  3253. var result = unixPermissions;
  3254. if (!unixPermissions) {
  3255. // I can't use octal values in strict mode, hence the hexa.
  3256. // 040775 => 0x41fd
  3257. // 0100664 => 0x81b4
  3258. result = isDir ? 0x41fd : 0x81b4;
  3259. }
  3260. return (result & 0xFFFF) << 16;
  3261. };
  3262. /**
  3263. * Generate the DOS part of the external file attributes.
  3264. * @param {Object} dosPermissions the dos permissions or null.
  3265. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  3266. * @return {Number} a 32 bit integer.
  3267. *
  3268. * Bit 0 Read-Only
  3269. * Bit 1 Hidden
  3270. * Bit 2 System
  3271. * Bit 3 Volume Label
  3272. * Bit 4 Directory
  3273. * Bit 5 Archive
  3274. */
  3275. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  3276. // the dir flag is already set for compatibility
  3277. return (dosPermissions || 0) & 0x3F;
  3278. };
  3279. /**
  3280. * Generate the various parts used in the construction of the final zip file.
  3281. * @param {string} name the file name.
  3282. * @param {ZipObject} file the file content.
  3283. * @param {JSZip.CompressedObject} compressedObject the compressed object.
  3284. * @param {number} offset the current offset from the start of the zip file.
  3285. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  3286. * @param {Function} encodeFileName the function to encode the file name / comment.
  3287. * @return {object} the zip parts.
  3288. */
  3289. var generateZipParts = function(name, file, compressedObject, offset, platform, encodeFileName) {
  3290. var data = compressedObject.compressedContent,
  3291. useCustomEncoding = encodeFileName !== utf8.utf8encode,
  3292. encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  3293. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  3294. comment = file.comment || "",
  3295. encodedComment = utils.transformTo("string", encodeFileName(comment)),
  3296. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  3297. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  3298. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  3299. o = file.options,
  3300. dosTime,
  3301. dosDate,
  3302. extraFields = "",
  3303. unicodePathExtraField = "",
  3304. unicodeCommentExtraField = "",
  3305. dir, date;
  3306. // handle the deprecated options.dir
  3307. if (file._initialMetadata.dir !== file.dir) {
  3308. dir = file.dir;
  3309. } else {
  3310. dir = o.dir;
  3311. }
  3312. // handle the deprecated options.date
  3313. if(file._initialMetadata.date !== file.date) {
  3314. date = file.date;
  3315. } else {
  3316. date = o.date;
  3317. }
  3318. var extFileAttr = 0;
  3319. var versionMadeBy = 0;
  3320. if (dir) {
  3321. // dos or unix, we set the dos dir flag
  3322. extFileAttr |= 0x00010;
  3323. }
  3324. if(platform === "UNIX") {
  3325. versionMadeBy = 0x031E; // UNIX, version 3.0
  3326. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  3327. } else { // DOS or other, fallback to DOS
  3328. versionMadeBy = 0x0014; // DOS, version 2.0
  3329. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  3330. }
  3331. // date
  3332. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  3333. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  3334. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  3335. dosTime = date.getHours();
  3336. dosTime = dosTime << 6;
  3337. dosTime = dosTime | date.getMinutes();
  3338. dosTime = dosTime << 5;
  3339. dosTime = dosTime | date.getSeconds() / 2;
  3340. dosDate = date.getFullYear() - 1980;
  3341. dosDate = dosDate << 4;
  3342. dosDate = dosDate | (date.getMonth() + 1);
  3343. dosDate = dosDate << 5;
  3344. dosDate = dosDate | date.getDate();
  3345. if (useUTF8ForFileName) {
  3346. // set the unicode path extra field. unzip needs at least one extra
  3347. // field to correctly handle unicode path, so using the path is as good
  3348. // as any other information. This could improve the situation with
  3349. // other archive managers too.
  3350. // This field is usually used without the utf8 flag, with a non
  3351. // unicode path in the header (winrar, winzip). This helps (a bit)
  3352. // with the messy Windows' default compressed folders feature but
  3353. // breaks on p7zip which doesn't seek the unicode path extra field.
  3354. // So for now, UTF-8 everywhere !
  3355. unicodePathExtraField =
  3356. // Version
  3357. decToHex(1, 1) +
  3358. // NameCRC32
  3359. decToHex(crc32(encodedFileName), 4) +
  3360. // UnicodeName
  3361. utfEncodedFileName;
  3362. extraFields +=
  3363. // Info-ZIP Unicode Path Extra Field
  3364. "\x75\x70" +
  3365. // size
  3366. decToHex(unicodePathExtraField.length, 2) +
  3367. // content
  3368. unicodePathExtraField;
  3369. }
  3370. if(useUTF8ForComment) {
  3371. unicodeCommentExtraField =
  3372. // Version
  3373. decToHex(1, 1) +
  3374. // CommentCRC32
  3375. decToHex(this.crc32(encodedComment), 4) +
  3376. // UnicodeName
  3377. utfEncodedComment;
  3378. extraFields +=
  3379. // Info-ZIP Unicode Path Extra Field
  3380. "\x75\x63" +
  3381. // size
  3382. decToHex(unicodeCommentExtraField.length, 2) +
  3383. // content
  3384. unicodeCommentExtraField;
  3385. }
  3386. var header = "";
  3387. // version needed to extract
  3388. header += "\x0A\x00";
  3389. // general purpose bit flag
  3390. // set bit 11 if utf8
  3391. header += !useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
  3392. // compression method
  3393. header += compressedObject.compressionMethod;
  3394. // last mod file time
  3395. header += decToHex(dosTime, 2);
  3396. // last mod file date
  3397. header += decToHex(dosDate, 2);
  3398. // crc-32
  3399. header += decToHex(compressedObject.crc32, 4);
  3400. // compressed size
  3401. header += decToHex(compressedObject.compressedSize, 4);
  3402. // uncompressed size
  3403. header += decToHex(compressedObject.uncompressedSize, 4);
  3404. // file name length
  3405. header += decToHex(encodedFileName.length, 2);
  3406. // extra field length
  3407. header += decToHex(extraFields.length, 2);
  3408. var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  3409. var dirRecord = signature.CENTRAL_FILE_HEADER +
  3410. // version made by (00: DOS)
  3411. decToHex(versionMadeBy, 2) +
  3412. // file header (common to file and central directory)
  3413. header +
  3414. // file comment length
  3415. decToHex(encodedComment.length, 2) +
  3416. // disk number start
  3417. "\x00\x00" +
  3418. // internal file attributes TODO
  3419. "\x00\x00" +
  3420. // external file attributes
  3421. decToHex(extFileAttr, 4) +
  3422. // relative offset of local header
  3423. decToHex(offset, 4) +
  3424. // file name
  3425. encodedFileName +
  3426. // extra field
  3427. extraFields +
  3428. // file comment
  3429. encodedComment;
  3430. return {
  3431. fileRecord: fileRecord,
  3432. dirRecord: dirRecord,
  3433. compressedObject: compressedObject
  3434. };
  3435. };
  3436. // return the actual prototype of JSZip
  3437. var out = {
  3438. /**
  3439. * Read an existing zip and merge the data in the current JSZip object.
  3440. * The implementation is in jszip-load.js, don't forget to include it.
  3441. * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
  3442. * @param {Object} options Options for loading the stream.
  3443. * options.base64 : is the stream in base64 ? default : false
  3444. * @return {JSZip} the current JSZip object
  3445. */
  3446. load: function(stream, options) {
  3447. throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
  3448. },
  3449. /**
  3450. * Filter nested files/folders with the specified function.
  3451. * @param {Function} search the predicate to use :
  3452. * function (relativePath, file) {...}
  3453. * It takes 2 arguments : the relative path and the file.
  3454. * @return {Array} An array of matching elements.
  3455. */
  3456. filter: function(search) {
  3457. var result = [],
  3458. filename, relativePath, file, fileClone;
  3459. for (filename in this.files) {
  3460. if (!this.files.hasOwnProperty(filename)) {
  3461. continue;
  3462. }
  3463. file = this.files[filename];
  3464. // return a new object, don't let the user mess with our internal objects :)
  3465. fileClone = new ZipObject(file.name, file._data, utils.extend(file.options));
  3466. relativePath = filename.slice(this.root.length, filename.length);
  3467. if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
  3468. search(relativePath, fileClone)) { // and the file matches the function
  3469. result.push(fileClone);
  3470. }
  3471. }
  3472. return result;
  3473. },
  3474. /**
  3475. * Add a file to the zip file, or search a file.
  3476. * @param {string|RegExp} name The name of the file to add (if data is defined),
  3477. * the name of the file to find (if no data) or a regex to match files.
  3478. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  3479. * @param {Object} o File options
  3480. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  3481. * a file (when searching by string) or an array of files (when searching by regex).
  3482. */
  3483. file: function(name, data, o) {
  3484. if (arguments.length === 1) {
  3485. if (utils.isRegExp(name)) {
  3486. var regexp = name;
  3487. return this.filter(function(relativePath, file) {
  3488. return !file.dir && regexp.test(relativePath);
  3489. });
  3490. }
  3491. else { // text
  3492. return this.filter(function(relativePath, file) {
  3493. return !file.dir && relativePath === name;
  3494. })[0] || null;
  3495. }
  3496. }
  3497. else { // more than one argument : we have data !
  3498. name = this.root + name;
  3499. fileAdd.call(this, name, data, o);
  3500. }
  3501. return this;
  3502. },
  3503. /**
  3504. * Add a directory to the zip file, or search.
  3505. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  3506. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  3507. */
  3508. folder: function(arg) {
  3509. if (!arg) {
  3510. return this;
  3511. }
  3512. if (utils.isRegExp(arg)) {
  3513. return this.filter(function(relativePath, file) {
  3514. return file.dir && arg.test(relativePath);
  3515. });
  3516. }
  3517. // else, name is a new folder
  3518. var name = this.root + arg;
  3519. var newFolder = folderAdd.call(this, name);
  3520. // Allow chaining by returning a new object with this folder as the root
  3521. var ret = this.clone();
  3522. ret.root = newFolder.name;
  3523. return ret;
  3524. },
  3525. /**
  3526. * Delete a file, or a directory and all sub-files, from the zip
  3527. * @param {string} name the name of the file to delete
  3528. * @return {JSZip} this JSZip object
  3529. */
  3530. remove: function(name) {
  3531. name = this.root + name;
  3532. var file = this.files[name];
  3533. if (!file) {
  3534. // Look for any folders
  3535. if (name.slice(-1) != "/") {
  3536. name += "/";
  3537. }
  3538. file = this.files[name];
  3539. }
  3540. if (file && !file.dir) {
  3541. // file
  3542. delete this.files[name];
  3543. } else {
  3544. // maybe a folder, delete recursively
  3545. var kids = this.filter(function(relativePath, file) {
  3546. return file.name.slice(0, name.length) === name;
  3547. });
  3548. for (var i = 0; i < kids.length; i++) {
  3549. delete this.files[kids[i].name];
  3550. }
  3551. }
  3552. return this;
  3553. },
  3554. /**
  3555. * Generate the complete zip file
  3556. * @param {Object} options the options to generate the zip file :
  3557. * - base64, (deprecated, use type instead) true to generate base64.
  3558. * - compression, "STORE" by default.
  3559. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  3560. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  3561. */
  3562. generate: function(options) {
  3563. options = utils.extend(options || {}, {
  3564. base64: true,
  3565. compression: "STORE",
  3566. compressionOptions : null,
  3567. type: "base64",
  3568. platform: "DOS",
  3569. comment: null,
  3570. mimeType: 'application/zip',
  3571. encodeFileName: utf8.utf8encode
  3572. });
  3573. utils.checkSupport(options.type);
  3574. // accept nodejs `process.platform`
  3575. if(
  3576. options.platform === 'darwin' ||
  3577. options.platform === 'freebsd' ||
  3578. options.platform === 'linux' ||
  3579. options.platform === 'sunos'
  3580. ) {
  3581. options.platform = "UNIX";
  3582. }
  3583. if (options.platform === 'win32') {
  3584. options.platform = "DOS";
  3585. }
  3586. var zipData = [],
  3587. localDirLength = 0,
  3588. centralDirLength = 0,
  3589. writer, i,
  3590. encodedComment = utils.transformTo("string", options.encodeFileName(options.comment || this.comment || ""));
  3591. // first, generate all the zip parts.
  3592. for (var name in this.files) {
  3593. if (!this.files.hasOwnProperty(name)) {
  3594. continue;
  3595. }
  3596. var file = this.files[name];
  3597. var compressionName = file.options.compression || options.compression.toUpperCase();
  3598. var compression = compressions[compressionName];
  3599. if (!compression) {
  3600. throw new Error(compressionName + " is not a valid compression method !");
  3601. }
  3602. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  3603. var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
  3604. var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform, options.encodeFileName);
  3605. localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
  3606. centralDirLength += zipPart.dirRecord.length;
  3607. zipData.push(zipPart);
  3608. }
  3609. var dirEnd = "";
  3610. // end of central dir signature
  3611. dirEnd = signature.CENTRAL_DIRECTORY_END +
  3612. // number of this disk
  3613. "\x00\x00" +
  3614. // number of the disk with the start of the central directory
  3615. "\x00\x00" +
  3616. // total number of entries in the central directory on this disk
  3617. decToHex(zipData.length, 2) +
  3618. // total number of entries in the central directory
  3619. decToHex(zipData.length, 2) +
  3620. // size of the central directory 4 bytes
  3621. decToHex(centralDirLength, 4) +
  3622. // offset of start of central directory with respect to the starting disk number
  3623. decToHex(localDirLength, 4) +
  3624. // .ZIP file comment length
  3625. decToHex(encodedComment.length, 2) +
  3626. // .ZIP file comment
  3627. encodedComment;
  3628. // we have all the parts (and the total length)
  3629. // time to create a writer !
  3630. var typeName = options.type.toLowerCase();
  3631. if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
  3632. writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
  3633. }else{
  3634. writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
  3635. }
  3636. for (i = 0; i < zipData.length; i++) {
  3637. writer.append(zipData[i].fileRecord);
  3638. writer.append(zipData[i].compressedObject.compressedContent);
  3639. }
  3640. for (i = 0; i < zipData.length; i++) {
  3641. writer.append(zipData[i].dirRecord);
  3642. }
  3643. writer.append(dirEnd);
  3644. var zip = writer.finalize();
  3645. switch(options.type.toLowerCase()) {
  3646. // case "zip is an Uint8Array"
  3647. case "uint8array" :
  3648. case "arraybuffer" :
  3649. case "nodebuffer" :
  3650. return utils.transformTo(options.type.toLowerCase(), zip);
  3651. case "blob" :
  3652. return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
  3653. // case "zip is a string"
  3654. case "base64" :
  3655. return (options.base64) ? base64.encode(zip) : zip;
  3656. default : // case "string" :
  3657. return zip;
  3658. }
  3659. },
  3660. /**
  3661. * @deprecated
  3662. * This method will be removed in a future version without replacement.
  3663. */
  3664. crc32: function (input, crc) {
  3665. return crc32(input, crc);
  3666. },
  3667. /**
  3668. * @deprecated
  3669. * This method will be removed in a future version without replacement.
  3670. */
  3671. utf8encode: function (string) {
  3672. return utils.transformTo("string", utf8.utf8encode(string));
  3673. },
  3674. /**
  3675. * @deprecated
  3676. * This method will be removed in a future version without replacement.
  3677. */
  3678. utf8decode: function (input) {
  3679. return utf8.utf8decode(input);
  3680. }
  3681. };
  3682. module.exports = out;
  3683. },{"./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){
  3684. 'use strict';
  3685. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  3686. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  3687. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  3688. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  3689. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  3690. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  3691. },{}],20:[function(_dereq_,module,exports){
  3692. 'use strict';
  3693. var DataReader = _dereq_('./dataReader');
  3694. var utils = _dereq_('./utils');
  3695. function StringReader(data, optimizedBinaryString) {
  3696. this.data = data;
  3697. if (!optimizedBinaryString) {
  3698. this.data = utils.string2binary(this.data);
  3699. }
  3700. this.length = this.data.length;
  3701. this.index = 0;
  3702. this.zero = 0;
  3703. }
  3704. StringReader.prototype = new DataReader();
  3705. /**
  3706. * @see DataReader.byteAt
  3707. */
  3708. StringReader.prototype.byteAt = function(i) {
  3709. return this.data.charCodeAt(this.zero + i);
  3710. };
  3711. /**
  3712. * @see DataReader.lastIndexOfSignature
  3713. */
  3714. StringReader.prototype.lastIndexOfSignature = function(sig) {
  3715. return this.data.lastIndexOf(sig) - this.zero;
  3716. };
  3717. /**
  3718. * @see DataReader.readData
  3719. */
  3720. StringReader.prototype.readData = function(size) {
  3721. this.checkOffset(size);
  3722. // this will work because the constructor applied the "& 0xff" mask.
  3723. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  3724. this.index += size;
  3725. return result;
  3726. };
  3727. module.exports = StringReader;
  3728. },{"./dataReader":10,"./utils":26}],21:[function(_dereq_,module,exports){
  3729. 'use strict';
  3730. var utils = _dereq_('./utils');
  3731. /**
  3732. * An object to write any content to a string.
  3733. * @constructor
  3734. */
  3735. var StringWriter = function() {
  3736. this.data = [];
  3737. };
  3738. StringWriter.prototype = {
  3739. /**
  3740. * Append any content to the current string.
  3741. * @param {Object} input the content to add.
  3742. */
  3743. append: function(input) {
  3744. input = utils.transformTo("string", input);
  3745. this.data.push(input);
  3746. },
  3747. /**
  3748. * Finalize the construction an return the result.
  3749. * @return {string} the generated string.
  3750. */
  3751. finalize: function() {
  3752. return this.data.join("");
  3753. }
  3754. };
  3755. module.exports = StringWriter;
  3756. },{"./utils":26}],22:[function(_dereq_,module,exports){
  3757. (function (Buffer){
  3758. 'use strict';
  3759. exports.base64 = true;
  3760. exports.array = true;
  3761. exports.string = true;
  3762. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  3763. // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
  3764. // Browserify will provide a Buffer implementation for browsers, which is
  3765. // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
  3766. exports.nodebuffer = typeof Buffer !== "undefined";
  3767. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  3768. exports.uint8array = typeof Uint8Array !== "undefined";
  3769. if (typeof ArrayBuffer === "undefined") {
  3770. exports.blob = false;
  3771. }
  3772. else {
  3773. var buffer = new ArrayBuffer(0);
  3774. try {
  3775. exports.blob = new Blob([buffer], {
  3776. type: "application/zip"
  3777. }).size === 0;
  3778. }
  3779. catch (e) {
  3780. try {
  3781. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  3782. var builder = new Builder();
  3783. builder.append(buffer);
  3784. exports.blob = builder.getBlob('application/zip').size === 0;
  3785. }
  3786. catch (e) {
  3787. exports.blob = false;
  3788. }
  3789. }
  3790. }
  3791. }).call(this,_dereq_("buffer").Buffer)
  3792. },{"buffer":1}],23:[function(_dereq_,module,exports){
  3793. 'use strict';
  3794. var ArrayReader = _dereq_('./arrayReader');
  3795. function Uint8ArrayReader(data) {
  3796. if (data) {
  3797. this.data = data;
  3798. this.length = this.data.length;
  3799. this.index = 0;
  3800. this.zero = 0;
  3801. }
  3802. }
  3803. Uint8ArrayReader.prototype = new ArrayReader();
  3804. /**
  3805. * @see DataReader.readData
  3806. */
  3807. Uint8ArrayReader.prototype.readData = function(size) {
  3808. this.checkOffset(size);
  3809. if(size === 0) {
  3810. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  3811. return new Uint8Array(0);
  3812. }
  3813. var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  3814. this.index += size;
  3815. return result;
  3816. };
  3817. module.exports = Uint8ArrayReader;
  3818. },{"./arrayReader":5}],24:[function(_dereq_,module,exports){
  3819. 'use strict';
  3820. var utils = _dereq_('./utils');
  3821. /**
  3822. * An object to write any content to an Uint8Array.
  3823. * @constructor
  3824. * @param {number} length The length of the array.
  3825. */
  3826. var Uint8ArrayWriter = function(length) {
  3827. this.data = new Uint8Array(length);
  3828. this.index = 0;
  3829. };
  3830. Uint8ArrayWriter.prototype = {
  3831. /**
  3832. * Append any content to the current array.
  3833. * @param {Object} input the content to add.
  3834. */
  3835. append: function(input) {
  3836. if (input.length !== 0) {
  3837. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  3838. input = utils.transformTo("uint8array", input);
  3839. this.data.set(input, this.index);
  3840. this.index += input.length;
  3841. }
  3842. },
  3843. /**
  3844. * Finalize the construction an return the result.
  3845. * @return {Uint8Array} the generated array.
  3846. */
  3847. finalize: function() {
  3848. return this.data;
  3849. }
  3850. };
  3851. module.exports = Uint8ArrayWriter;
  3852. },{"./utils":26}],25:[function(_dereq_,module,exports){
  3853. 'use strict';
  3854. var utils = _dereq_('./utils');
  3855. var support = _dereq_('./support');
  3856. var nodeBuffer = _dereq_('./nodeBuffer');
  3857. /**
  3858. * The following functions come from pako, from pako/lib/utils/strings
  3859. * released under the MIT license, see pako https://github.com/nodeca/pako/
  3860. */
  3861. // Table with utf8 lengths (calculated by first byte of sequence)
  3862. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  3863. // because max possible codepoint is 0x10ffff
  3864. var _utf8len = new Array(256);
  3865. for (var i=0; i<256; i++) {
  3866. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  3867. }
  3868. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  3869. // convert string to array (typed, when possible)
  3870. var string2buf = function (str) {
  3871. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  3872. // count binary size
  3873. for (m_pos = 0; m_pos < str_len; m_pos++) {
  3874. c = str.charCodeAt(m_pos);
  3875. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3876. c2 = str.charCodeAt(m_pos+1);
  3877. if ((c2 & 0xfc00) === 0xdc00) {
  3878. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3879. m_pos++;
  3880. }
  3881. }
  3882. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  3883. }
  3884. // allocate buffer
  3885. if (support.uint8array) {
  3886. buf = new Uint8Array(buf_len);
  3887. } else {
  3888. buf = new Array(buf_len);
  3889. }
  3890. // convert
  3891. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  3892. c = str.charCodeAt(m_pos);
  3893. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3894. c2 = str.charCodeAt(m_pos+1);
  3895. if ((c2 & 0xfc00) === 0xdc00) {
  3896. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3897. m_pos++;
  3898. }
  3899. }
  3900. if (c < 0x80) {
  3901. /* one byte */
  3902. buf[i++] = c;
  3903. } else if (c < 0x800) {
  3904. /* two bytes */
  3905. buf[i++] = 0xC0 | (c >>> 6);
  3906. buf[i++] = 0x80 | (c & 0x3f);
  3907. } else if (c < 0x10000) {
  3908. /* three bytes */
  3909. buf[i++] = 0xE0 | (c >>> 12);
  3910. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3911. buf[i++] = 0x80 | (c & 0x3f);
  3912. } else {
  3913. /* four bytes */
  3914. buf[i++] = 0xf0 | (c >>> 18);
  3915. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  3916. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3917. buf[i++] = 0x80 | (c & 0x3f);
  3918. }
  3919. }
  3920. return buf;
  3921. };
  3922. // Calculate max possible position in utf8 buffer,
  3923. // that will not break sequence. If that's not possible
  3924. // - (very small limits) return max size as is.
  3925. //
  3926. // buf[] - utf8 bytes array
  3927. // max - length limit (mandatory);
  3928. var utf8border = function(buf, max) {
  3929. var pos;
  3930. max = max || buf.length;
  3931. if (max > buf.length) { max = buf.length; }
  3932. // go back from last position, until start of sequence found
  3933. pos = max-1;
  3934. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  3935. // Fuckup - very small and broken sequence,
  3936. // return max, because we should return something anyway.
  3937. if (pos < 0) { return max; }
  3938. // If we came to start of buffer - that means vuffer is too small,
  3939. // return max too.
  3940. if (pos === 0) { return max; }
  3941. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  3942. };
  3943. // convert array to string
  3944. var buf2string = function (buf) {
  3945. var str, i, out, c, c_len;
  3946. var len = buf.length;
  3947. // Reserve max possible length (2 words per char)
  3948. // NB: by unknown reasons, Array is significantly faster for
  3949. // String.fromCharCode.apply than Uint16Array.
  3950. var utf16buf = new Array(len*2);
  3951. for (out=0, i=0; i<len;) {
  3952. c = buf[i++];
  3953. // quick process ascii
  3954. if (c < 0x80) { utf16buf[out++] = c; continue; }
  3955. c_len = _utf8len[c];
  3956. // skip 5 & 6 byte codes
  3957. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  3958. // apply mask on first byte
  3959. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  3960. // join the rest
  3961. while (c_len > 1 && i < len) {
  3962. c = (c << 6) | (buf[i++] & 0x3f);
  3963. c_len--;
  3964. }
  3965. // terminated by end of string?
  3966. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  3967. if (c < 0x10000) {
  3968. utf16buf[out++] = c;
  3969. } else {
  3970. c -= 0x10000;
  3971. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  3972. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  3973. }
  3974. }
  3975. // shrinkBuf(utf16buf, out)
  3976. if (utf16buf.length !== out) {
  3977. if(utf16buf.subarray) {
  3978. utf16buf = utf16buf.subarray(0, out);
  3979. } else {
  3980. utf16buf.length = out;
  3981. }
  3982. }
  3983. // return String.fromCharCode.apply(null, utf16buf);
  3984. return utils.applyFromCharCode(utf16buf);
  3985. };
  3986. // That's all for the pako functions.
  3987. /**
  3988. * Transform a javascript string into an array (typed if possible) of bytes,
  3989. * UTF-8 encoded.
  3990. * @param {String} str the string to encode
  3991. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  3992. */
  3993. exports.utf8encode = function utf8encode(str) {
  3994. if (support.nodebuffer) {
  3995. return nodeBuffer(str, "utf-8");
  3996. }
  3997. return string2buf(str);
  3998. };
  3999. /**
  4000. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  4001. * string into a javascript string.
  4002. * @param {Array|Uint8Array|Buffer} buf the data de decode
  4003. * @return {String} the decoded string.
  4004. */
  4005. exports.utf8decode = function utf8decode(buf) {
  4006. if (support.nodebuffer) {
  4007. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  4008. }
  4009. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  4010. // return buf2string(buf);
  4011. // Chrome prefers to work with "small" chunks of data
  4012. // for the method buf2string.
  4013. // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
  4014. var result = [], k = 0, len = buf.length, chunk = 65536;
  4015. while (k < len) {
  4016. var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
  4017. if (support.uint8array) {
  4018. result.push(buf2string(buf.subarray(k, nextBoundary)));
  4019. } else {
  4020. result.push(buf2string(buf.slice(k, nextBoundary)));
  4021. }
  4022. k = nextBoundary;
  4023. }
  4024. return result.join("");
  4025. };
  4026. // vim: set shiftwidth=4 softtabstop=4:
  4027. },{"./nodeBuffer":16,"./support":22,"./utils":26}],26:[function(_dereq_,module,exports){
  4028. 'use strict';
  4029. var support = _dereq_('./support');
  4030. var compressions = _dereq_('./compressions');
  4031. var nodeBuffer = _dereq_('./nodeBuffer');
  4032. /**
  4033. * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
  4034. * @param {string} str the string to transform.
  4035. * @return {String} the binary string.
  4036. */
  4037. exports.string2binary = function(str) {
  4038. var result = "";
  4039. for (var i = 0; i < str.length; i++) {
  4040. result += String.fromCharCode(str.charCodeAt(i) & 0xff);
  4041. }
  4042. return result;
  4043. };
  4044. exports.arrayBuffer2Blob = function(buffer, mimeType) {
  4045. exports.checkSupport("blob");
  4046. mimeType = mimeType || 'application/zip';
  4047. try {
  4048. // Blob constructor
  4049. return new Blob([buffer], {
  4050. type: mimeType
  4051. });
  4052. }
  4053. catch (e) {
  4054. try {
  4055. // deprecated, browser only, old way
  4056. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  4057. var builder = new Builder();
  4058. builder.append(buffer);
  4059. return builder.getBlob(mimeType);
  4060. }
  4061. catch (e) {
  4062. // well, fuck ?!
  4063. throw new Error("Bug : can't construct the Blob.");
  4064. }
  4065. }
  4066. };
  4067. /**
  4068. * The identity function.
  4069. * @param {Object} input the input.
  4070. * @return {Object} the same input.
  4071. */
  4072. function identity(input) {
  4073. return input;
  4074. }
  4075. /**
  4076. * Fill in an array with a string.
  4077. * @param {String} str the string to use.
  4078. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  4079. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  4080. */
  4081. function stringToArrayLike(str, array) {
  4082. for (var i = 0; i < str.length; ++i) {
  4083. array[i] = str.charCodeAt(i) & 0xFF;
  4084. }
  4085. return array;
  4086. }
  4087. /**
  4088. * Transform an array-like object to a string.
  4089. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  4090. * @return {String} the result.
  4091. */
  4092. function arrayLikeToString(array) {
  4093. // Performances notes :
  4094. // --------------------
  4095. // String.fromCharCode.apply(null, array) is the fastest, see
  4096. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  4097. // but the stack is limited (and we can get huge arrays !).
  4098. //
  4099. // result += String.fromCharCode(array[i]); generate too many strings !
  4100. //
  4101. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  4102. var chunk = 65536;
  4103. var result = [],
  4104. len = array.length,
  4105. type = exports.getTypeOf(array),
  4106. k = 0,
  4107. canUseApply = true;
  4108. try {
  4109. switch(type) {
  4110. case "uint8array":
  4111. String.fromCharCode.apply(null, new Uint8Array(0));
  4112. break;
  4113. case "nodebuffer":
  4114. String.fromCharCode.apply(null, nodeBuffer(0));
  4115. break;
  4116. }
  4117. } catch(e) {
  4118. canUseApply = false;
  4119. }
  4120. // no apply : slow and painful algorithm
  4121. // default browser on android 4.*
  4122. if (!canUseApply) {
  4123. var resultStr = "";
  4124. for(var i = 0; i < array.length;i++) {
  4125. resultStr += String.fromCharCode(array[i]);
  4126. }
  4127. return resultStr;
  4128. }
  4129. while (k < len && chunk > 1) {
  4130. try {
  4131. if (type === "array" || type === "nodebuffer") {
  4132. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  4133. }
  4134. else {
  4135. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  4136. }
  4137. k += chunk;
  4138. }
  4139. catch (e) {
  4140. chunk = Math.floor(chunk / 2);
  4141. }
  4142. }
  4143. return result.join("");
  4144. }
  4145. exports.applyFromCharCode = arrayLikeToString;
  4146. /**
  4147. * Copy the data from an array-like to an other array-like.
  4148. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  4149. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  4150. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  4151. */
  4152. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  4153. for (var i = 0; i < arrayFrom.length; i++) {
  4154. arrayTo[i] = arrayFrom[i];
  4155. }
  4156. return arrayTo;
  4157. }
  4158. // a matrix containing functions to transform everything into everything.
  4159. var transform = {};
  4160. // string to ?
  4161. transform["string"] = {
  4162. "string": identity,
  4163. "array": function(input) {
  4164. return stringToArrayLike(input, new Array(input.length));
  4165. },
  4166. "arraybuffer": function(input) {
  4167. return transform["string"]["uint8array"](input).buffer;
  4168. },
  4169. "uint8array": function(input) {
  4170. return stringToArrayLike(input, new Uint8Array(input.length));
  4171. },
  4172. "nodebuffer": function(input) {
  4173. return stringToArrayLike(input, nodeBuffer(input.length));
  4174. }
  4175. };
  4176. // array to ?
  4177. transform["array"] = {
  4178. "string": arrayLikeToString,
  4179. "array": identity,
  4180. "arraybuffer": function(input) {
  4181. return (new Uint8Array(input)).buffer;
  4182. },
  4183. "uint8array": function(input) {
  4184. return new Uint8Array(input);
  4185. },
  4186. "nodebuffer": function(input) {
  4187. return nodeBuffer(input);
  4188. }
  4189. };
  4190. // arraybuffer to ?
  4191. transform["arraybuffer"] = {
  4192. "string": function(input) {
  4193. return arrayLikeToString(new Uint8Array(input));
  4194. },
  4195. "array": function(input) {
  4196. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  4197. },
  4198. "arraybuffer": identity,
  4199. "uint8array": function(input) {
  4200. return new Uint8Array(input);
  4201. },
  4202. "nodebuffer": function(input) {
  4203. return nodeBuffer(new Uint8Array(input));
  4204. }
  4205. };
  4206. // uint8array to ?
  4207. transform["uint8array"] = {
  4208. "string": arrayLikeToString,
  4209. "array": function(input) {
  4210. return arrayLikeToArrayLike(input, new Array(input.length));
  4211. },
  4212. "arraybuffer": function(input) {
  4213. return input.buffer;
  4214. },
  4215. "uint8array": identity,
  4216. "nodebuffer": function(input) {
  4217. return nodeBuffer(input);
  4218. }
  4219. };
  4220. // nodebuffer to ?
  4221. transform["nodebuffer"] = {
  4222. "string": arrayLikeToString,
  4223. "array": function(input) {
  4224. return arrayLikeToArrayLike(input, new Array(input.length));
  4225. },
  4226. "arraybuffer": function(input) {
  4227. return transform["nodebuffer"]["uint8array"](input).buffer;
  4228. },
  4229. "uint8array": function(input) {
  4230. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  4231. },
  4232. "nodebuffer": identity
  4233. };
  4234. /**
  4235. * Transform an input into any type.
  4236. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  4237. * If no output type is specified, the unmodified input will be returned.
  4238. * @param {String} outputType the output type.
  4239. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  4240. * @throws {Error} an Error if the browser doesn't support the requested output type.
  4241. */
  4242. exports.transformTo = function(outputType, input) {
  4243. if (!input) {
  4244. // undefined, null, etc
  4245. // an empty string won't harm.
  4246. input = "";
  4247. }
  4248. if (!outputType) {
  4249. return input;
  4250. }
  4251. exports.checkSupport(outputType);
  4252. var inputType = exports.getTypeOf(input);
  4253. var result = transform[inputType][outputType](input);
  4254. return result;
  4255. };
  4256. /**
  4257. * Return the type of the input.
  4258. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  4259. * @param {Object} input the input to identify.
  4260. * @return {String} the (lowercase) type of the input.
  4261. */
  4262. exports.getTypeOf = function(input) {
  4263. if (typeof input === "string") {
  4264. return "string";
  4265. }
  4266. if (Object.prototype.toString.call(input) === "[object Array]") {
  4267. return "array";
  4268. }
  4269. if (support.nodebuffer && nodeBuffer.test(input)) {
  4270. return "nodebuffer";
  4271. }
  4272. if (support.uint8array && input instanceof Uint8Array) {
  4273. return "uint8array";
  4274. }
  4275. if (support.arraybuffer && input instanceof ArrayBuffer) {
  4276. return "arraybuffer";
  4277. }
  4278. };
  4279. /**
  4280. * Throw an exception if the type is not supported.
  4281. * @param {String} type the type to check.
  4282. * @throws {Error} an Error if the browser doesn't support the requested type.
  4283. */
  4284. exports.checkSupport = function(type) {
  4285. var supported = support[type.toLowerCase()];
  4286. if (!supported) {
  4287. throw new Error(type + " is not supported by this browser");
  4288. }
  4289. };
  4290. exports.MAX_VALUE_16BITS = 65535;
  4291. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  4292. /**
  4293. * Prettify a string read as binary.
  4294. * @param {string} str the string to prettify.
  4295. * @return {string} a pretty string.
  4296. */
  4297. exports.pretty = function(str) {
  4298. var res = '',
  4299. code, i;
  4300. for (i = 0; i < (str || "").length; i++) {
  4301. code = str.charCodeAt(i);
  4302. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  4303. }
  4304. return res;
  4305. };
  4306. /**
  4307. * Find a compression registered in JSZip.
  4308. * @param {string} compressionMethod the method magic to find.
  4309. * @return {Object|null} the JSZip compression object, null if none found.
  4310. */
  4311. exports.findCompression = function(compressionMethod) {
  4312. for (var method in compressions) {
  4313. if (!compressions.hasOwnProperty(method)) {
  4314. continue;
  4315. }
  4316. if (compressions[method].magic === compressionMethod) {
  4317. return compressions[method];
  4318. }
  4319. }
  4320. return null;
  4321. };
  4322. /**
  4323. * Cross-window, cross-Node-context regular expression detection
  4324. * @param {Object} object Anything
  4325. * @return {Boolean} true if the object is a regular expression,
  4326. * false otherwise
  4327. */
  4328. exports.isRegExp = function (object) {
  4329. return Object.prototype.toString.call(object) === "[object RegExp]";
  4330. };
  4331. /**
  4332. * Merge the objects passed as parameters into a new one.
  4333. * @private
  4334. * @param {...Object} var_args All objects to merge.
  4335. * @return {Object} a new object with the data of the others.
  4336. */
  4337. exports.extend = function() {
  4338. var result = {}, i, attr;
  4339. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  4340. for (attr in arguments[i]) {
  4341. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  4342. result[attr] = arguments[i][attr];
  4343. }
  4344. }
  4345. }
  4346. return result;
  4347. };
  4348. },{"./compressions":8,"./nodeBuffer":16,"./support":22}],27:[function(_dereq_,module,exports){
  4349. 'use strict';
  4350. var StringReader = _dereq_('./stringReader');
  4351. var NodeBufferReader = _dereq_('./nodeBufferReader');
  4352. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  4353. var ArrayReader = _dereq_('./arrayReader');
  4354. var utils = _dereq_('./utils');
  4355. var sig = _dereq_('./signature');
  4356. var ZipEntry = _dereq_('./zipEntry');
  4357. var support = _dereq_('./support');
  4358. var jszipProto = _dereq_('./object');
  4359. // class ZipEntries {{{
  4360. /**
  4361. * All the entries in the zip file.
  4362. * @constructor
  4363. * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
  4364. * @param {Object} loadOptions Options for loading the stream.
  4365. */
  4366. function ZipEntries(data, loadOptions) {
  4367. this.files = [];
  4368. this.loadOptions = loadOptions;
  4369. if (data) {
  4370. this.load(data);
  4371. }
  4372. }
  4373. ZipEntries.prototype = {
  4374. /**
  4375. * Check that the reader is on the speficied signature.
  4376. * @param {string} expectedSignature the expected signature.
  4377. * @throws {Error} if it is an other signature.
  4378. */
  4379. checkSignature: function(expectedSignature) {
  4380. var signature = this.reader.readString(4);
  4381. if (signature !== expectedSignature) {
  4382. throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  4383. }
  4384. },
  4385. /**
  4386. * Check if the given signature is at the given index.
  4387. * @param {number} askedIndex the index to check.
  4388. * @param {string} expectedSignature the signature to expect.
  4389. * @return {boolean} true if the signature is here, false otherwise.
  4390. */
  4391. isSignature: function(askedIndex, expectedSignature) {
  4392. var currentIndex = this.reader.index;
  4393. this.reader.setIndex(askedIndex);
  4394. var signature = this.reader.readString(4);
  4395. var result = signature === expectedSignature;
  4396. this.reader.setIndex(currentIndex);
  4397. return result;
  4398. },
  4399. /**
  4400. * Read the end of the central directory.
  4401. */
  4402. readBlockEndOfCentral: function() {
  4403. this.diskNumber = this.reader.readInt(2);
  4404. this.diskWithCentralDirStart = this.reader.readInt(2);
  4405. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  4406. this.centralDirRecords = this.reader.readInt(2);
  4407. this.centralDirSize = this.reader.readInt(4);
  4408. this.centralDirOffset = this.reader.readInt(4);
  4409. this.zipCommentLength = this.reader.readInt(2);
  4410. // warning : the encoding depends of the system locale
  4411. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  4412. // On a windows machine, this field is encoded with the localized windows code page.
  4413. var zipComment = this.reader.readData(this.zipCommentLength);
  4414. var decodeParamType = support.uint8array ? "uint8array" : "array";
  4415. // To get consistent behavior with the generation part, we will assume that
  4416. // this is utf8 encoded unless specified otherwise.
  4417. var decodeContent = utils.transformTo(decodeParamType, zipComment);
  4418. this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  4419. },
  4420. /**
  4421. * Read the end of the Zip 64 central directory.
  4422. * Not merged with the method readEndOfCentral :
  4423. * The end of central can coexist with its Zip64 brother,
  4424. * I don't want to read the wrong number of bytes !
  4425. */
  4426. readBlockZip64EndOfCentral: function() {
  4427. this.zip64EndOfCentralSize = this.reader.readInt(8);
  4428. this.versionMadeBy = this.reader.readString(2);
  4429. this.versionNeeded = this.reader.readInt(2);
  4430. this.diskNumber = this.reader.readInt(4);
  4431. this.diskWithCentralDirStart = this.reader.readInt(4);
  4432. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  4433. this.centralDirRecords = this.reader.readInt(8);
  4434. this.centralDirSize = this.reader.readInt(8);
  4435. this.centralDirOffset = this.reader.readInt(8);
  4436. this.zip64ExtensibleData = {};
  4437. var extraDataSize = this.zip64EndOfCentralSize - 44,
  4438. index = 0,
  4439. extraFieldId,
  4440. extraFieldLength,
  4441. extraFieldValue;
  4442. while (index < extraDataSize) {
  4443. extraFieldId = this.reader.readInt(2);
  4444. extraFieldLength = this.reader.readInt(4);
  4445. extraFieldValue = this.reader.readString(extraFieldLength);
  4446. this.zip64ExtensibleData[extraFieldId] = {
  4447. id: extraFieldId,
  4448. length: extraFieldLength,
  4449. value: extraFieldValue
  4450. };
  4451. }
  4452. },
  4453. /**
  4454. * Read the end of the Zip 64 central directory locator.
  4455. */
  4456. readBlockZip64EndOfCentralLocator: function() {
  4457. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  4458. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  4459. this.disksCount = this.reader.readInt(4);
  4460. if (this.disksCount > 1) {
  4461. throw new Error("Multi-volumes zip are not supported");
  4462. }
  4463. },
  4464. /**
  4465. * Read the local files, based on the offset read in the central part.
  4466. */
  4467. readLocalFiles: function() {
  4468. var i, file;
  4469. for (i = 0; i < this.files.length; i++) {
  4470. file = this.files[i];
  4471. this.reader.setIndex(file.localHeaderOffset);
  4472. this.checkSignature(sig.LOCAL_FILE_HEADER);
  4473. file.readLocalPart(this.reader);
  4474. file.handleUTF8();
  4475. file.processAttributes();
  4476. }
  4477. },
  4478. /**
  4479. * Read the central directory.
  4480. */
  4481. readCentralDir: function() {
  4482. var file;
  4483. this.reader.setIndex(this.centralDirOffset);
  4484. while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
  4485. file = new ZipEntry({
  4486. zip64: this.zip64
  4487. }, this.loadOptions);
  4488. file.readCentralPart(this.reader);
  4489. this.files.push(file);
  4490. }
  4491. if (this.centralDirRecords !== this.files.length) {
  4492. if (this.centralDirRecords !== 0 && this.files.length === 0) {
  4493. // We expected some records but couldn't find ANY.
  4494. // This is really suspicious, as if something went wrong.
  4495. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  4496. } else {
  4497. // We found some records but not all.
  4498. // Something is wrong but we got something for the user: no error here.
  4499. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  4500. }
  4501. }
  4502. },
  4503. /**
  4504. * Read the end of central directory.
  4505. */
  4506. readEndOfCentral: function() {
  4507. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  4508. if (offset < 0) {
  4509. // Check if the content is a truncated zip or complete garbage.
  4510. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  4511. // extractible zip for example) but it can give a good hint.
  4512. // If an ajax request was used without responseType, we will also
  4513. // get unreadable data.
  4514. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  4515. if (isGarbage) {
  4516. throw new Error("Can't find end of central directory : is this a zip file ? " +
  4517. "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
  4518. } else {
  4519. throw new Error("Corrupted zip : can't find end of central directory");
  4520. }
  4521. }
  4522. this.reader.setIndex(offset);
  4523. var endOfCentralDirOffset = offset;
  4524. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  4525. this.readBlockEndOfCentral();
  4526. /* extract from the zip spec :
  4527. 4) If one of the fields in the end of central directory
  4528. record is too small to hold required data, the field
  4529. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  4530. ZIP64 format record should be created.
  4531. 5) The end of central directory record and the
  4532. Zip64 end of central directory locator record must
  4533. reside on the same disk when splitting or spanning
  4534. an archive.
  4535. */
  4536. 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) {
  4537. this.zip64 = true;
  4538. /*
  4539. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  4540. the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
  4541. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  4542. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  4543. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  4544. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  4545. */
  4546. // should look for a zip64 EOCD locator
  4547. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  4548. if (offset < 0) {
  4549. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
  4550. }
  4551. this.reader.setIndex(offset);
  4552. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  4553. this.readBlockZip64EndOfCentralLocator();
  4554. // now the zip64 EOCD record
  4555. if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  4556. // console.warn("ZIP64 end of central directory not where expected.");
  4557. this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  4558. if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  4559. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory");
  4560. }
  4561. }
  4562. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  4563. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  4564. this.readBlockZip64EndOfCentral();
  4565. }
  4566. var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  4567. if (this.zip64) {
  4568. expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  4569. expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  4570. }
  4571. var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  4572. if (extraBytes > 0) {
  4573. // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  4574. if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  4575. // The offsets seem wrong, but we have something at the specified offset.
  4576. // So… we keep it.
  4577. } else {
  4578. // the offset is wrong, update the "zero" of the reader
  4579. // this happens if data has been prepended (crx files for example)
  4580. this.reader.zero = extraBytes;
  4581. }
  4582. } else if (extraBytes < 0) {
  4583. throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  4584. }
  4585. },
  4586. prepareReader: function(data) {
  4587. var type = utils.getTypeOf(data);
  4588. utils.checkSupport(type);
  4589. if (type === "string" && !support.uint8array) {
  4590. this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
  4591. }
  4592. else if (type === "nodebuffer") {
  4593. this.reader = new NodeBufferReader(data);
  4594. }
  4595. else if (support.uint8array) {
  4596. this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
  4597. } else if (support.array) {
  4598. this.reader = new ArrayReader(utils.transformTo("array", data));
  4599. } else {
  4600. throw new Error("Unexpected error: unsupported type '" + type + "'");
  4601. }
  4602. },
  4603. /**
  4604. * Read a zip file and create ZipEntries.
  4605. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  4606. */
  4607. load: function(data) {
  4608. this.prepareReader(data);
  4609. this.readEndOfCentral();
  4610. this.readCentralDir();
  4611. this.readLocalFiles();
  4612. }
  4613. };
  4614. // }}} end of ZipEntries
  4615. module.exports = ZipEntries;
  4616. },{"./arrayReader":5,"./nodeBufferReader":17,"./object":18,"./signature":19,"./stringReader":20,"./support":22,"./uint8ArrayReader":23,"./utils":26,"./zipEntry":28}],28:[function(_dereq_,module,exports){
  4617. 'use strict';
  4618. var StringReader = _dereq_('./stringReader');
  4619. var utils = _dereq_('./utils');
  4620. var CompressedObject = _dereq_('./compressedObject');
  4621. var jszipProto = _dereq_('./object');
  4622. var support = _dereq_('./support');
  4623. var MADE_BY_DOS = 0x00;
  4624. var MADE_BY_UNIX = 0x03;
  4625. // class ZipEntry {{{
  4626. /**
  4627. * An entry in the zip file.
  4628. * @constructor
  4629. * @param {Object} options Options of the current file.
  4630. * @param {Object} loadOptions Options for loading the stream.
  4631. */
  4632. function ZipEntry(options, loadOptions) {
  4633. this.options = options;
  4634. this.loadOptions = loadOptions;
  4635. }
  4636. ZipEntry.prototype = {
  4637. /**
  4638. * say if the file is encrypted.
  4639. * @return {boolean} true if the file is encrypted, false otherwise.
  4640. */
  4641. isEncrypted: function() {
  4642. // bit 1 is set
  4643. return (this.bitFlag & 0x0001) === 0x0001;
  4644. },
  4645. /**
  4646. * say if the file has utf-8 filename/comment.
  4647. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  4648. */
  4649. useUTF8: function() {
  4650. // bit 11 is set
  4651. return (this.bitFlag & 0x0800) === 0x0800;
  4652. },
  4653. /**
  4654. * Prepare the function used to generate the compressed content from this ZipFile.
  4655. * @param {DataReader} reader the reader to use.
  4656. * @param {number} from the offset from where we should read the data.
  4657. * @param {number} length the length of the data to read.
  4658. * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
  4659. */
  4660. prepareCompressedContent: function(reader, from, length) {
  4661. return function() {
  4662. var previousIndex = reader.index;
  4663. reader.setIndex(from);
  4664. var compressedFileData = reader.readData(length);
  4665. reader.setIndex(previousIndex);
  4666. return compressedFileData;
  4667. };
  4668. },
  4669. /**
  4670. * Prepare the function used to generate the uncompressed content from this ZipFile.
  4671. * @param {DataReader} reader the reader to use.
  4672. * @param {number} from the offset from where we should read the data.
  4673. * @param {number} length the length of the data to read.
  4674. * @param {JSZip.compression} compression the compression used on this file.
  4675. * @param {number} uncompressedSize the uncompressed size to expect.
  4676. * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
  4677. */
  4678. prepareContent: function(reader, from, length, compression, uncompressedSize) {
  4679. return function() {
  4680. var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
  4681. var uncompressedFileData = compression.uncompress(compressedFileData);
  4682. if (uncompressedFileData.length !== uncompressedSize) {
  4683. throw new Error("Bug : uncompressed data size mismatch");
  4684. }
  4685. return uncompressedFileData;
  4686. };
  4687. },
  4688. /**
  4689. * Read the local part of a zip file and add the info in this object.
  4690. * @param {DataReader} reader the reader to use.
  4691. */
  4692. readLocalPart: function(reader) {
  4693. var compression, localExtraFieldsLength;
  4694. // we already know everything from the central dir !
  4695. // If the central dir data are false, we are doomed.
  4696. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  4697. // The less data we get here, the more reliable this should be.
  4698. // Let's skip the whole header and dash to the data !
  4699. reader.skip(22);
  4700. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  4701. // Strangely, the filename here is OK.
  4702. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  4703. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  4704. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  4705. // the internet.
  4706. //
  4707. // I think I see the logic here : the central directory is used to display
  4708. // content and the local directory is used to extract the files. Mixing / and \
  4709. // may be used to display \ to windows users and use / when extracting the files.
  4710. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  4711. this.fileNameLength = reader.readInt(2);
  4712. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  4713. this.fileName = reader.readData(this.fileNameLength);
  4714. reader.skip(localExtraFieldsLength);
  4715. if (this.compressedSize == -1 || this.uncompressedSize == -1) {
  4716. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
  4717. }
  4718. compression = utils.findCompression(this.compressionMethod);
  4719. if (compression === null) { // no compression found
  4720. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  4721. }
  4722. this.decompressed = new CompressedObject();
  4723. this.decompressed.compressedSize = this.compressedSize;
  4724. this.decompressed.uncompressedSize = this.uncompressedSize;
  4725. this.decompressed.crc32 = this.crc32;
  4726. this.decompressed.compressionMethod = this.compressionMethod;
  4727. this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
  4728. this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
  4729. // we need to compute the crc32...
  4730. if (this.loadOptions.checkCRC32) {
  4731. this.decompressed = utils.transformTo("string", this.decompressed.getContent());
  4732. if (jszipProto.crc32(this.decompressed) !== this.crc32) {
  4733. throw new Error("Corrupted zip : CRC32 mismatch");
  4734. }
  4735. }
  4736. },
  4737. /**
  4738. * Read the central part of a zip file and add the info in this object.
  4739. * @param {DataReader} reader the reader to use.
  4740. */
  4741. readCentralPart: function(reader) {
  4742. this.versionMadeBy = reader.readInt(2);
  4743. this.versionNeeded = reader.readInt(2);
  4744. this.bitFlag = reader.readInt(2);
  4745. this.compressionMethod = reader.readString(2);
  4746. this.date = reader.readDate();
  4747. this.crc32 = reader.readInt(4);
  4748. this.compressedSize = reader.readInt(4);
  4749. this.uncompressedSize = reader.readInt(4);
  4750. this.fileNameLength = reader.readInt(2);
  4751. this.extraFieldsLength = reader.readInt(2);
  4752. this.fileCommentLength = reader.readInt(2);
  4753. this.diskNumberStart = reader.readInt(2);
  4754. this.internalFileAttributes = reader.readInt(2);
  4755. this.externalFileAttributes = reader.readInt(4);
  4756. this.localHeaderOffset = reader.readInt(4);
  4757. if (this.isEncrypted()) {
  4758. throw new Error("Encrypted zip are not supported");
  4759. }
  4760. this.fileName = reader.readData(this.fileNameLength);
  4761. this.readExtraFields(reader);
  4762. this.parseZIP64ExtraField(reader);
  4763. this.fileComment = reader.readData(this.fileCommentLength);
  4764. },
  4765. /**
  4766. * Parse the external file attributes and get the unix/dos permissions.
  4767. */
  4768. processAttributes: function () {
  4769. this.unixPermissions = null;
  4770. this.dosPermissions = null;
  4771. var madeBy = this.versionMadeBy >> 8;
  4772. // Check if we have the DOS directory flag set.
  4773. // We look for it in the DOS and UNIX permissions
  4774. // but some unknown platform could set it as a compatibility flag.
  4775. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  4776. if(madeBy === MADE_BY_DOS) {
  4777. // first 6 bits (0 to 5)
  4778. this.dosPermissions = this.externalFileAttributes & 0x3F;
  4779. }
  4780. if(madeBy === MADE_BY_UNIX) {
  4781. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  4782. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  4783. }
  4784. // fail safe : if the name ends with a / it probably means a folder
  4785. if (!this.dir && this.fileNameStr.slice(-1) === '/') {
  4786. this.dir = true;
  4787. }
  4788. },
  4789. /**
  4790. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  4791. * @param {DataReader} reader the reader to use.
  4792. */
  4793. parseZIP64ExtraField: function(reader) {
  4794. if (!this.extraFields[0x0001]) {
  4795. return;
  4796. }
  4797. // should be something, preparing the extra reader
  4798. var extraReader = new StringReader(this.extraFields[0x0001].value);
  4799. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  4800. // won't let us have more.
  4801. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  4802. this.uncompressedSize = extraReader.readInt(8);
  4803. }
  4804. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  4805. this.compressedSize = extraReader.readInt(8);
  4806. }
  4807. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  4808. this.localHeaderOffset = extraReader.readInt(8);
  4809. }
  4810. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  4811. this.diskNumberStart = extraReader.readInt(4);
  4812. }
  4813. },
  4814. /**
  4815. * Read the central part of a zip file and add the info in this object.
  4816. * @param {DataReader} reader the reader to use.
  4817. */
  4818. readExtraFields: function(reader) {
  4819. var start = reader.index,
  4820. extraFieldId,
  4821. extraFieldLength,
  4822. extraFieldValue;
  4823. this.extraFields = this.extraFields || {};
  4824. while (reader.index < start + this.extraFieldsLength) {
  4825. extraFieldId = reader.readInt(2);
  4826. extraFieldLength = reader.readInt(2);
  4827. extraFieldValue = reader.readString(extraFieldLength);
  4828. this.extraFields[extraFieldId] = {
  4829. id: extraFieldId,
  4830. length: extraFieldLength,
  4831. value: extraFieldValue
  4832. };
  4833. }
  4834. },
  4835. /**
  4836. * Apply an UTF8 transformation if needed.
  4837. */
  4838. handleUTF8: function() {
  4839. var decodeParamType = support.uint8array ? "uint8array" : "array";
  4840. if (this.useUTF8()) {
  4841. this.fileNameStr = jszipProto.utf8decode(this.fileName);
  4842. this.fileCommentStr = jszipProto.utf8decode(this.fileComment);
  4843. } else {
  4844. var upath = this.findExtraFieldUnicodePath();
  4845. if (upath !== null) {
  4846. this.fileNameStr = upath;
  4847. } else {
  4848. var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
  4849. this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  4850. }
  4851. var ucomment = this.findExtraFieldUnicodeComment();
  4852. if (ucomment !== null) {
  4853. this.fileCommentStr = ucomment;
  4854. } else {
  4855. var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
  4856. this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  4857. }
  4858. }
  4859. },
  4860. /**
  4861. * Find the unicode path declared in the extra field, if any.
  4862. * @return {String} the unicode path, null otherwise.
  4863. */
  4864. findExtraFieldUnicodePath: function() {
  4865. var upathField = this.extraFields[0x7075];
  4866. if (upathField) {
  4867. var extraReader = new StringReader(upathField.value);
  4868. // wrong version
  4869. if (extraReader.readInt(1) !== 1) {
  4870. return null;
  4871. }
  4872. // the crc of the filename changed, this field is out of date.
  4873. if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
  4874. return null;
  4875. }
  4876. return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
  4877. }
  4878. return null;
  4879. },
  4880. /**
  4881. * Find the unicode comment declared in the extra field, if any.
  4882. * @return {String} the unicode comment, null otherwise.
  4883. */
  4884. findExtraFieldUnicodeComment: function() {
  4885. var ucommentField = this.extraFields[0x6375];
  4886. if (ucommentField) {
  4887. var extraReader = new StringReader(ucommentField.value);
  4888. // wrong version
  4889. if (extraReader.readInt(1) !== 1) {
  4890. return null;
  4891. }
  4892. // the crc of the comment changed, this field is out of date.
  4893. if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
  4894. return null;
  4895. }
  4896. return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
  4897. }
  4898. return null;
  4899. }
  4900. };
  4901. module.exports = ZipEntry;
  4902. },{"./compressedObject":7,"./object":18,"./stringReader":20,"./support":22,"./utils":26}],29:[function(_dereq_,module,exports){
  4903. // Top level file is just a mixin of submodules & constants
  4904. 'use strict';
  4905. var assign = _dereq_('./lib/utils/common').assign;
  4906. var deflate = _dereq_('./lib/deflate');
  4907. var inflate = _dereq_('./lib/inflate');
  4908. var constants = _dereq_('./lib/zlib/constants');
  4909. var pako = {};
  4910. assign(pako, deflate, inflate, constants);
  4911. module.exports = pako;
  4912. },{"./lib/deflate":30,"./lib/inflate":31,"./lib/utils/common":32,"./lib/zlib/constants":35}],30:[function(_dereq_,module,exports){
  4913. 'use strict';
  4914. var zlib_deflate = _dereq_('./zlib/deflate');
  4915. var utils = _dereq_('./utils/common');
  4916. var strings = _dereq_('./utils/strings');
  4917. var msg = _dereq_('./zlib/messages');
  4918. var ZStream = _dereq_('./zlib/zstream');
  4919. var toString = Object.prototype.toString;
  4920. /* Public constants ==========================================================*/
  4921. /* ===========================================================================*/
  4922. var Z_NO_FLUSH = 0;
  4923. var Z_FINISH = 4;
  4924. var Z_OK = 0;
  4925. var Z_STREAM_END = 1;
  4926. var Z_SYNC_FLUSH = 2;
  4927. var Z_DEFAULT_COMPRESSION = -1;
  4928. var Z_DEFAULT_STRATEGY = 0;
  4929. var Z_DEFLATED = 8;
  4930. /* ===========================================================================*/
  4931. /**
  4932. * class Deflate
  4933. *
  4934. * Generic JS-style wrapper for zlib calls. If you don't need
  4935. * streaming behaviour - use more simple functions: [[deflate]],
  4936. * [[deflateRaw]] and [[gzip]].
  4937. **/
  4938. /* internal
  4939. * Deflate.chunks -> Array
  4940. *
  4941. * Chunks of output data, if [[Deflate#onData]] not overriden.
  4942. **/
  4943. /**
  4944. * Deflate.result -> Uint8Array|Array
  4945. *
  4946. * Compressed result, generated by default [[Deflate#onData]]
  4947. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  4948. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  4949. * push a chunk with explicit flush (call [[Deflate#push]] with
  4950. * `Z_SYNC_FLUSH` param).
  4951. **/
  4952. /**
  4953. * Deflate.err -> Number
  4954. *
  4955. * Error code after deflate finished. 0 (Z_OK) on success.
  4956. * You will not need it in real life, because deflate errors
  4957. * are possible only on wrong options or bad `onData` / `onEnd`
  4958. * custom handlers.
  4959. **/
  4960. /**
  4961. * Deflate.msg -> String
  4962. *
  4963. * Error message, if [[Deflate.err]] != 0
  4964. **/
  4965. /**
  4966. * new Deflate(options)
  4967. * - options (Object): zlib deflate options.
  4968. *
  4969. * Creates new deflator instance with specified params. Throws exception
  4970. * on bad params. Supported options:
  4971. *
  4972. * - `level`
  4973. * - `windowBits`
  4974. * - `memLevel`
  4975. * - `strategy`
  4976. * - `dictionary`
  4977. *
  4978. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4979. * for more information on these.
  4980. *
  4981. * Additional options, for internal needs:
  4982. *
  4983. * - `chunkSize` - size of generated data chunks (16K by default)
  4984. * - `raw` (Boolean) - do raw deflate
  4985. * - `gzip` (Boolean) - create gzip wrapper
  4986. * - `to` (String) - if equal to 'string', then result will be "binary string"
  4987. * (each char code [0..255])
  4988. * - `header` (Object) - custom header for gzip
  4989. * - `text` (Boolean) - true if compressed data believed to be text
  4990. * - `time` (Number) - modification time, unix timestamp
  4991. * - `os` (Number) - operation system code
  4992. * - `extra` (Array) - array of bytes with extra data (max 65536)
  4993. * - `name` (String) - file name (binary string)
  4994. * - `comment` (String) - comment (binary string)
  4995. * - `hcrc` (Boolean) - true if header crc should be added
  4996. *
  4997. * ##### Example:
  4998. *
  4999. * ```javascript
  5000. * var pako = require('pako')
  5001. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5002. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5003. *
  5004. * var deflate = new pako.Deflate({ level: 3});
  5005. *
  5006. * deflate.push(chunk1, false);
  5007. * deflate.push(chunk2, true); // true -> last chunk
  5008. *
  5009. * if (deflate.err) { throw new Error(deflate.err); }
  5010. *
  5011. * console.log(deflate.result);
  5012. * ```
  5013. **/
  5014. function Deflate(options) {
  5015. if (!(this instanceof Deflate)) return new Deflate(options);
  5016. this.options = utils.assign({
  5017. level: Z_DEFAULT_COMPRESSION,
  5018. method: Z_DEFLATED,
  5019. chunkSize: 16384,
  5020. windowBits: 15,
  5021. memLevel: 8,
  5022. strategy: Z_DEFAULT_STRATEGY,
  5023. to: ''
  5024. }, options || {});
  5025. var opt = this.options;
  5026. if (opt.raw && (opt.windowBits > 0)) {
  5027. opt.windowBits = -opt.windowBits;
  5028. }
  5029. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  5030. opt.windowBits += 16;
  5031. }
  5032. this.err = 0; // error code, if happens (0 = Z_OK)
  5033. this.msg = ''; // error message
  5034. this.ended = false; // used to avoid multiple onEnd() calls
  5035. this.chunks = []; // chunks of compressed data
  5036. this.strm = new ZStream();
  5037. this.strm.avail_out = 0;
  5038. var status = zlib_deflate.deflateInit2(
  5039. this.strm,
  5040. opt.level,
  5041. opt.method,
  5042. opt.windowBits,
  5043. opt.memLevel,
  5044. opt.strategy
  5045. );
  5046. if (status !== Z_OK) {
  5047. throw new Error(msg[status]);
  5048. }
  5049. if (opt.header) {
  5050. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  5051. }
  5052. if (opt.dictionary) {
  5053. var dict;
  5054. // Convert data if needed
  5055. if (typeof opt.dictionary === 'string') {
  5056. // If we need to compress text, change encoding to utf8.
  5057. dict = strings.string2buf(opt.dictionary);
  5058. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  5059. dict = new Uint8Array(opt.dictionary);
  5060. } else {
  5061. dict = opt.dictionary;
  5062. }
  5063. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  5064. if (status !== Z_OK) {
  5065. throw new Error(msg[status]);
  5066. }
  5067. this._dict_set = true;
  5068. }
  5069. }
  5070. /**
  5071. * Deflate#push(data[, mode]) -> Boolean
  5072. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  5073. * converted to utf8 byte sequence.
  5074. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5075. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5076. *
  5077. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  5078. * new compressed chunks. Returns `true` on success. The last data block must have
  5079. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5080. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5081. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  5082. *
  5083. * On fail call [[Deflate#onEnd]] with error code and return false.
  5084. *
  5085. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5086. * array format is detected automatically). Also, don't skip last param and always
  5087. * use the same type in your code (boolean or number). That will improve JS speed.
  5088. *
  5089. * For regular `Array`-s make sure all elements are [0..255].
  5090. *
  5091. * ##### Example
  5092. *
  5093. * ```javascript
  5094. * push(chunk, false); // push one of data chunks
  5095. * ...
  5096. * push(chunk, true); // push last chunk
  5097. * ```
  5098. **/
  5099. Deflate.prototype.push = function (data, mode) {
  5100. var strm = this.strm;
  5101. var chunkSize = this.options.chunkSize;
  5102. var status, _mode;
  5103. if (this.ended) { return false; }
  5104. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  5105. // Convert data if needed
  5106. if (typeof data === 'string') {
  5107. // If we need to compress text, change encoding to utf8.
  5108. strm.input = strings.string2buf(data);
  5109. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5110. strm.input = new Uint8Array(data);
  5111. } else {
  5112. strm.input = data;
  5113. }
  5114. strm.next_in = 0;
  5115. strm.avail_in = strm.input.length;
  5116. do {
  5117. if (strm.avail_out === 0) {
  5118. strm.output = new utils.Buf8(chunkSize);
  5119. strm.next_out = 0;
  5120. strm.avail_out = chunkSize;
  5121. }
  5122. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  5123. if (status !== Z_STREAM_END && status !== Z_OK) {
  5124. this.onEnd(status);
  5125. this.ended = true;
  5126. return false;
  5127. }
  5128. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  5129. if (this.options.to === 'string') {
  5130. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  5131. } else {
  5132. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5133. }
  5134. }
  5135. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  5136. // Finalize on the last chunk.
  5137. if (_mode === Z_FINISH) {
  5138. status = zlib_deflate.deflateEnd(this.strm);
  5139. this.onEnd(status);
  5140. this.ended = true;
  5141. return status === Z_OK;
  5142. }
  5143. // callback interim results if Z_SYNC_FLUSH.
  5144. if (_mode === Z_SYNC_FLUSH) {
  5145. this.onEnd(Z_OK);
  5146. strm.avail_out = 0;
  5147. return true;
  5148. }
  5149. return true;
  5150. };
  5151. /**
  5152. * Deflate#onData(chunk) -> Void
  5153. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5154. * on js engine support. When string output requested, each chunk
  5155. * will be string.
  5156. *
  5157. * By default, stores data blocks in `chunks[]` property and glue
  5158. * those in `onEnd`. Override this handler, if you need another behaviour.
  5159. **/
  5160. Deflate.prototype.onData = function (chunk) {
  5161. this.chunks.push(chunk);
  5162. };
  5163. /**
  5164. * Deflate#onEnd(status) -> Void
  5165. * - status (Number): deflate status. 0 (Z_OK) on success,
  5166. * other if not.
  5167. *
  5168. * Called once after you tell deflate that the input stream is
  5169. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5170. * or if an error happened. By default - join collected chunks,
  5171. * free memory and fill `results` / `err` properties.
  5172. **/
  5173. Deflate.prototype.onEnd = function (status) {
  5174. // On success - join
  5175. if (status === Z_OK) {
  5176. if (this.options.to === 'string') {
  5177. this.result = this.chunks.join('');
  5178. } else {
  5179. this.result = utils.flattenChunks(this.chunks);
  5180. }
  5181. }
  5182. this.chunks = [];
  5183. this.err = status;
  5184. this.msg = this.strm.msg;
  5185. };
  5186. /**
  5187. * deflate(data[, options]) -> Uint8Array|Array|String
  5188. * - data (Uint8Array|Array|String): input data to compress.
  5189. * - options (Object): zlib deflate options.
  5190. *
  5191. * Compress `data` with deflate algorithm and `options`.
  5192. *
  5193. * Supported options are:
  5194. *
  5195. * - level
  5196. * - windowBits
  5197. * - memLevel
  5198. * - strategy
  5199. * - dictionary
  5200. *
  5201. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5202. * for more information on these.
  5203. *
  5204. * Sugar (options):
  5205. *
  5206. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5207. * negative windowBits implicitly.
  5208. * - `to` (String) - if equal to 'string', then result will be "binary string"
  5209. * (each char code [0..255])
  5210. *
  5211. * ##### Example:
  5212. *
  5213. * ```javascript
  5214. * var pako = require('pako')
  5215. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  5216. *
  5217. * console.log(pako.deflate(data));
  5218. * ```
  5219. **/
  5220. function deflate(input, options) {
  5221. var deflator = new Deflate(options);
  5222. deflator.push(input, true);
  5223. // That will never happens, if you don't cheat with options :)
  5224. if (deflator.err) { throw deflator.msg; }
  5225. return deflator.result;
  5226. }
  5227. /**
  5228. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  5229. * - data (Uint8Array|Array|String): input data to compress.
  5230. * - options (Object): zlib deflate options.
  5231. *
  5232. * The same as [[deflate]], but creates raw data, without wrapper
  5233. * (header and adler32 crc).
  5234. **/
  5235. function deflateRaw(input, options) {
  5236. options = options || {};
  5237. options.raw = true;
  5238. return deflate(input, options);
  5239. }
  5240. /**
  5241. * gzip(data[, options]) -> Uint8Array|Array|String
  5242. * - data (Uint8Array|Array|String): input data to compress.
  5243. * - options (Object): zlib deflate options.
  5244. *
  5245. * The same as [[deflate]], but create gzip wrapper instead of
  5246. * deflate one.
  5247. **/
  5248. function gzip(input, options) {
  5249. options = options || {};
  5250. options.gzip = true;
  5251. return deflate(input, options);
  5252. }
  5253. exports.Deflate = Deflate;
  5254. exports.deflate = deflate;
  5255. exports.deflateRaw = deflateRaw;
  5256. exports.gzip = gzip;
  5257. },{"./utils/common":32,"./utils/strings":33,"./zlib/deflate":37,"./zlib/messages":42,"./zlib/zstream":44}],31:[function(_dereq_,module,exports){
  5258. 'use strict';
  5259. var zlib_inflate = _dereq_('./zlib/inflate');
  5260. var utils = _dereq_('./utils/common');
  5261. var strings = _dereq_('./utils/strings');
  5262. var c = _dereq_('./zlib/constants');
  5263. var msg = _dereq_('./zlib/messages');
  5264. var ZStream = _dereq_('./zlib/zstream');
  5265. var GZheader = _dereq_('./zlib/gzheader');
  5266. var toString = Object.prototype.toString;
  5267. /**
  5268. * class Inflate
  5269. *
  5270. * Generic JS-style wrapper for zlib calls. If you don't need
  5271. * streaming behaviour - use more simple functions: [[inflate]]
  5272. * and [[inflateRaw]].
  5273. **/
  5274. /* internal
  5275. * inflate.chunks -> Array
  5276. *
  5277. * Chunks of output data, if [[Inflate#onData]] not overriden.
  5278. **/
  5279. /**
  5280. * Inflate.result -> Uint8Array|Array|String
  5281. *
  5282. * Uncompressed result, generated by default [[Inflate#onData]]
  5283. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  5284. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  5285. * push a chunk with explicit flush (call [[Inflate#push]] with
  5286. * `Z_SYNC_FLUSH` param).
  5287. **/
  5288. /**
  5289. * Inflate.err -> Number
  5290. *
  5291. * Error code after inflate finished. 0 (Z_OK) on success.
  5292. * Should be checked if broken data possible.
  5293. **/
  5294. /**
  5295. * Inflate.msg -> String
  5296. *
  5297. * Error message, if [[Inflate.err]] != 0
  5298. **/
  5299. /**
  5300. * new Inflate(options)
  5301. * - options (Object): zlib inflate options.
  5302. *
  5303. * Creates new inflator instance with specified params. Throws exception
  5304. * on bad params. Supported options:
  5305. *
  5306. * - `windowBits`
  5307. * - `dictionary`
  5308. *
  5309. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5310. * for more information on these.
  5311. *
  5312. * Additional options, for internal needs:
  5313. *
  5314. * - `chunkSize` - size of generated data chunks (16K by default)
  5315. * - `raw` (Boolean) - do raw inflate
  5316. * - `to` (String) - if equal to 'string', then result will be converted
  5317. * from utf8 to utf16 (javascript) string. When string output requested,
  5318. * chunk length can differ from `chunkSize`, depending on content.
  5319. *
  5320. * By default, when no options set, autodetect deflate/gzip data format via
  5321. * wrapper header.
  5322. *
  5323. * ##### Example:
  5324. *
  5325. * ```javascript
  5326. * var pako = require('pako')
  5327. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5328. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5329. *
  5330. * var inflate = new pako.Inflate({ level: 3});
  5331. *
  5332. * inflate.push(chunk1, false);
  5333. * inflate.push(chunk2, true); // true -> last chunk
  5334. *
  5335. * if (inflate.err) { throw new Error(inflate.err); }
  5336. *
  5337. * console.log(inflate.result);
  5338. * ```
  5339. **/
  5340. function Inflate(options) {
  5341. if (!(this instanceof Inflate)) return new Inflate(options);
  5342. this.options = utils.assign({
  5343. chunkSize: 16384,
  5344. windowBits: 0,
  5345. to: ''
  5346. }, options || {});
  5347. var opt = this.options;
  5348. // Force window size for `raw` data, if not set directly,
  5349. // because we have no header for autodetect.
  5350. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  5351. opt.windowBits = -opt.windowBits;
  5352. if (opt.windowBits === 0) { opt.windowBits = -15; }
  5353. }
  5354. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  5355. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  5356. !(options && options.windowBits)) {
  5357. opt.windowBits += 32;
  5358. }
  5359. // Gzip header has no info about windows size, we can do autodetect only
  5360. // for deflate. So, if window size not set, force it to max when gzip possible
  5361. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  5362. // bit 3 (16) -> gzipped data
  5363. // bit 4 (32) -> autodetect gzip/deflate
  5364. if ((opt.windowBits & 15) === 0) {
  5365. opt.windowBits |= 15;
  5366. }
  5367. }
  5368. this.err = 0; // error code, if happens (0 = Z_OK)
  5369. this.msg = ''; // error message
  5370. this.ended = false; // used to avoid multiple onEnd() calls
  5371. this.chunks = []; // chunks of compressed data
  5372. this.strm = new ZStream();
  5373. this.strm.avail_out = 0;
  5374. var status = zlib_inflate.inflateInit2(
  5375. this.strm,
  5376. opt.windowBits
  5377. );
  5378. if (status !== c.Z_OK) {
  5379. throw new Error(msg[status]);
  5380. }
  5381. this.header = new GZheader();
  5382. zlib_inflate.inflateGetHeader(this.strm, this.header);
  5383. }
  5384. /**
  5385. * Inflate#push(data[, mode]) -> Boolean
  5386. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  5387. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5388. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5389. *
  5390. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  5391. * new output chunks. Returns `true` on success. The last data block must have
  5392. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5393. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5394. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  5395. *
  5396. * On fail call [[Inflate#onEnd]] with error code and return false.
  5397. *
  5398. * We strongly recommend to use `Uint8Array` on input for best speed (output
  5399. * format is detected automatically). Also, don't skip last param and always
  5400. * use the same type in your code (boolean or number). That will improve JS speed.
  5401. *
  5402. * For regular `Array`-s make sure all elements are [0..255].
  5403. *
  5404. * ##### Example
  5405. *
  5406. * ```javascript
  5407. * push(chunk, false); // push one of data chunks
  5408. * ...
  5409. * push(chunk, true); // push last chunk
  5410. * ```
  5411. **/
  5412. Inflate.prototype.push = function (data, mode) {
  5413. var strm = this.strm;
  5414. var chunkSize = this.options.chunkSize;
  5415. var dictionary = this.options.dictionary;
  5416. var status, _mode;
  5417. var next_out_utf8, tail, utf8str;
  5418. var dict;
  5419. // Flag to properly process Z_BUF_ERROR on testing inflate call
  5420. // when we check that all output data was flushed.
  5421. var allowBufError = false;
  5422. if (this.ended) { return false; }
  5423. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  5424. // Convert data if needed
  5425. if (typeof data === 'string') {
  5426. // Only binary strings can be decompressed on practice
  5427. strm.input = strings.binstring2buf(data);
  5428. } else if (toString.call(data) === '[object ArrayBuffer]') {
  5429. strm.input = new Uint8Array(data);
  5430. } else {
  5431. strm.input = data;
  5432. }
  5433. strm.next_in = 0;
  5434. strm.avail_in = strm.input.length;
  5435. do {
  5436. if (strm.avail_out === 0) {
  5437. strm.output = new utils.Buf8(chunkSize);
  5438. strm.next_out = 0;
  5439. strm.avail_out = chunkSize;
  5440. }
  5441. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  5442. if (status === c.Z_NEED_DICT && dictionary) {
  5443. // Convert data if needed
  5444. if (typeof dictionary === 'string') {
  5445. dict = strings.string2buf(dictionary);
  5446. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  5447. dict = new Uint8Array(dictionary);
  5448. } else {
  5449. dict = dictionary;
  5450. }
  5451. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  5452. }
  5453. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  5454. status = c.Z_OK;
  5455. allowBufError = false;
  5456. }
  5457. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  5458. this.onEnd(status);
  5459. this.ended = true;
  5460. return false;
  5461. }
  5462. if (strm.next_out) {
  5463. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  5464. if (this.options.to === 'string') {
  5465. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  5466. tail = strm.next_out - next_out_utf8;
  5467. utf8str = strings.buf2string(strm.output, next_out_utf8);
  5468. // move tail
  5469. strm.next_out = tail;
  5470. strm.avail_out = chunkSize - tail;
  5471. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  5472. this.onData(utf8str);
  5473. } else {
  5474. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5475. }
  5476. }
  5477. }
  5478. // When no more input data, we should check that internal inflate buffers
  5479. // are flushed. The only way to do it when avail_out = 0 - run one more
  5480. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  5481. // Here we set flag to process this error properly.
  5482. //
  5483. // NOTE. Deflate does not return error in this case and does not needs such
  5484. // logic.
  5485. if (strm.avail_in === 0 && strm.avail_out === 0) {
  5486. allowBufError = true;
  5487. }
  5488. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  5489. if (status === c.Z_STREAM_END) {
  5490. _mode = c.Z_FINISH;
  5491. }
  5492. // Finalize on the last chunk.
  5493. if (_mode === c.Z_FINISH) {
  5494. status = zlib_inflate.inflateEnd(this.strm);
  5495. this.onEnd(status);
  5496. this.ended = true;
  5497. return status === c.Z_OK;
  5498. }
  5499. // callback interim results if Z_SYNC_FLUSH.
  5500. if (_mode === c.Z_SYNC_FLUSH) {
  5501. this.onEnd(c.Z_OK);
  5502. strm.avail_out = 0;
  5503. return true;
  5504. }
  5505. return true;
  5506. };
  5507. /**
  5508. * Inflate#onData(chunk) -> Void
  5509. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5510. * on js engine support. When string output requested, each chunk
  5511. * will be string.
  5512. *
  5513. * By default, stores data blocks in `chunks[]` property and glue
  5514. * those in `onEnd`. Override this handler, if you need another behaviour.
  5515. **/
  5516. Inflate.prototype.onData = function (chunk) {
  5517. this.chunks.push(chunk);
  5518. };
  5519. /**
  5520. * Inflate#onEnd(status) -> Void
  5521. * - status (Number): inflate status. 0 (Z_OK) on success,
  5522. * other if not.
  5523. *
  5524. * Called either after you tell inflate that the input stream is
  5525. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5526. * or if an error happened. By default - join collected chunks,
  5527. * free memory and fill `results` / `err` properties.
  5528. **/
  5529. Inflate.prototype.onEnd = function (status) {
  5530. // On success - join
  5531. if (status === c.Z_OK) {
  5532. if (this.options.to === 'string') {
  5533. // Glue & convert here, until we teach pako to send
  5534. // utf8 alligned strings to onData
  5535. this.result = this.chunks.join('');
  5536. } else {
  5537. this.result = utils.flattenChunks(this.chunks);
  5538. }
  5539. }
  5540. this.chunks = [];
  5541. this.err = status;
  5542. this.msg = this.strm.msg;
  5543. };
  5544. /**
  5545. * inflate(data[, options]) -> Uint8Array|Array|String
  5546. * - data (Uint8Array|Array|String): input data to decompress.
  5547. * - options (Object): zlib inflate options.
  5548. *
  5549. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  5550. * format via wrapper header by default. That's why we don't provide
  5551. * separate `ungzip` method.
  5552. *
  5553. * Supported options are:
  5554. *
  5555. * - windowBits
  5556. *
  5557. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5558. * for more information.
  5559. *
  5560. * Sugar (options):
  5561. *
  5562. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5563. * negative windowBits implicitly.
  5564. * - `to` (String) - if equal to 'string', then result will be converted
  5565. * from utf8 to utf16 (javascript) string. When string output requested,
  5566. * chunk length can differ from `chunkSize`, depending on content.
  5567. *
  5568. *
  5569. * ##### Example:
  5570. *
  5571. * ```javascript
  5572. * var pako = require('pako')
  5573. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  5574. * , output;
  5575. *
  5576. * try {
  5577. * output = pako.inflate(input);
  5578. * } catch (err)
  5579. * console.log(err);
  5580. * }
  5581. * ```
  5582. **/
  5583. function inflate(input, options) {
  5584. var inflator = new Inflate(options);
  5585. inflator.push(input, true);
  5586. // That will never happens, if you don't cheat with options :)
  5587. if (inflator.err) { throw inflator.msg; }
  5588. return inflator.result;
  5589. }
  5590. /**
  5591. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  5592. * - data (Uint8Array|Array|String): input data to decompress.
  5593. * - options (Object): zlib inflate options.
  5594. *
  5595. * The same as [[inflate]], but creates raw data, without wrapper
  5596. * (header and adler32 crc).
  5597. **/
  5598. function inflateRaw(input, options) {
  5599. options = options || {};
  5600. options.raw = true;
  5601. return inflate(input, options);
  5602. }
  5603. /**
  5604. * ungzip(data[, options]) -> Uint8Array|Array|String
  5605. * - data (Uint8Array|Array|String): input data to decompress.
  5606. * - options (Object): zlib inflate options.
  5607. *
  5608. * Just shortcut to [[inflate]], because it autodetects format
  5609. * by header.content. Done for convenience.
  5610. **/
  5611. exports.Inflate = Inflate;
  5612. exports.inflate = inflate;
  5613. exports.inflateRaw = inflateRaw;
  5614. exports.ungzip = inflate;
  5615. },{"./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){
  5616. 'use strict';
  5617. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  5618. (typeof Uint16Array !== 'undefined') &&
  5619. (typeof Int32Array !== 'undefined');
  5620. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  5621. var sources = Array.prototype.slice.call(arguments, 1);
  5622. while (sources.length) {
  5623. var source = sources.shift();
  5624. if (!source) { continue; }
  5625. if (typeof source !== 'object') {
  5626. throw new TypeError(source + 'must be non-object');
  5627. }
  5628. for (var p in source) {
  5629. if (source.hasOwnProperty(p)) {
  5630. obj[p] = source[p];
  5631. }
  5632. }
  5633. }
  5634. return obj;
  5635. };
  5636. // reduce buffer size, avoiding mem copy
  5637. exports.shrinkBuf = function (buf, size) {
  5638. if (buf.length === size) { return buf; }
  5639. if (buf.subarray) { return buf.subarray(0, size); }
  5640. buf.length = size;
  5641. return buf;
  5642. };
  5643. var fnTyped = {
  5644. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5645. if (src.subarray && dest.subarray) {
  5646. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  5647. return;
  5648. }
  5649. // Fallback to ordinary array
  5650. for (var i = 0; i < len; i++) {
  5651. dest[dest_offs + i] = src[src_offs + i];
  5652. }
  5653. },
  5654. // Join array of chunks to single array.
  5655. flattenChunks: function (chunks) {
  5656. var i, l, len, pos, chunk, result;
  5657. // calculate data length
  5658. len = 0;
  5659. for (i = 0, l = chunks.length; i < l; i++) {
  5660. len += chunks[i].length;
  5661. }
  5662. // join chunks
  5663. result = new Uint8Array(len);
  5664. pos = 0;
  5665. for (i = 0, l = chunks.length; i < l; i++) {
  5666. chunk = chunks[i];
  5667. result.set(chunk, pos);
  5668. pos += chunk.length;
  5669. }
  5670. return result;
  5671. }
  5672. };
  5673. var fnUntyped = {
  5674. arraySet: function (dest, src, src_offs, len, dest_offs) {
  5675. for (var i = 0; i < len; i++) {
  5676. dest[dest_offs + i] = src[src_offs + i];
  5677. }
  5678. },
  5679. // Join array of chunks to single array.
  5680. flattenChunks: function (chunks) {
  5681. return [].concat.apply([], chunks);
  5682. }
  5683. };
  5684. // Enable/Disable typed arrays use, for testing
  5685. //
  5686. exports.setTyped = function (on) {
  5687. if (on) {
  5688. exports.Buf8 = Uint8Array;
  5689. exports.Buf16 = Uint16Array;
  5690. exports.Buf32 = Int32Array;
  5691. exports.assign(exports, fnTyped);
  5692. } else {
  5693. exports.Buf8 = Array;
  5694. exports.Buf16 = Array;
  5695. exports.Buf32 = Array;
  5696. exports.assign(exports, fnUntyped);
  5697. }
  5698. };
  5699. exports.setTyped(TYPED_OK);
  5700. },{}],33:[function(_dereq_,module,exports){
  5701. // String encode/decode helpers
  5702. 'use strict';
  5703. var utils = _dereq_('./common');
  5704. // Quick check if we can use fast array to bin string conversion
  5705. //
  5706. // - apply(Array) can fail on Android 2.2
  5707. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  5708. //
  5709. var STR_APPLY_OK = true;
  5710. var STR_APPLY_UIA_OK = true;
  5711. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  5712. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  5713. // Table with utf8 lengths (calculated by first byte of sequence)
  5714. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  5715. // because max possible codepoint is 0x10ffff
  5716. var _utf8len = new utils.Buf8(256);
  5717. for (var q = 0; q < 256; q++) {
  5718. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  5719. }
  5720. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  5721. // convert string to array (typed, when possible)
  5722. exports.string2buf = function (str) {
  5723. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  5724. // count binary size
  5725. for (m_pos = 0; m_pos < str_len; m_pos++) {
  5726. c = str.charCodeAt(m_pos);
  5727. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  5728. c2 = str.charCodeAt(m_pos + 1);
  5729. if ((c2 & 0xfc00) === 0xdc00) {
  5730. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5731. m_pos++;
  5732. }
  5733. }
  5734. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  5735. }
  5736. // allocate buffer
  5737. buf = new utils.Buf8(buf_len);
  5738. // convert
  5739. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  5740. c = str.charCodeAt(m_pos);
  5741. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  5742. c2 = str.charCodeAt(m_pos + 1);
  5743. if ((c2 & 0xfc00) === 0xdc00) {
  5744. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5745. m_pos++;
  5746. }
  5747. }
  5748. if (c < 0x80) {
  5749. /* one byte */
  5750. buf[i++] = c;
  5751. } else if (c < 0x800) {
  5752. /* two bytes */
  5753. buf[i++] = 0xC0 | (c >>> 6);
  5754. buf[i++] = 0x80 | (c & 0x3f);
  5755. } else if (c < 0x10000) {
  5756. /* three bytes */
  5757. buf[i++] = 0xE0 | (c >>> 12);
  5758. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5759. buf[i++] = 0x80 | (c & 0x3f);
  5760. } else {
  5761. /* four bytes */
  5762. buf[i++] = 0xf0 | (c >>> 18);
  5763. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  5764. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5765. buf[i++] = 0x80 | (c & 0x3f);
  5766. }
  5767. }
  5768. return buf;
  5769. };
  5770. // Helper (used in 2 places)
  5771. function buf2binstring(buf, len) {
  5772. // use fallback for big arrays to avoid stack overflow
  5773. if (len < 65537) {
  5774. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  5775. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  5776. }
  5777. }
  5778. var result = '';
  5779. for (var i = 0; i < len; i++) {
  5780. result += String.fromCharCode(buf[i]);
  5781. }
  5782. return result;
  5783. }
  5784. // Convert byte array to binary string
  5785. exports.buf2binstring = function (buf) {
  5786. return buf2binstring(buf, buf.length);
  5787. };
  5788. // Convert binary string (typed, when possible)
  5789. exports.binstring2buf = function (str) {
  5790. var buf = new utils.Buf8(str.length);
  5791. for (var i = 0, len = buf.length; i < len; i++) {
  5792. buf[i] = str.charCodeAt(i);
  5793. }
  5794. return buf;
  5795. };
  5796. // convert array to string
  5797. exports.buf2string = function (buf, max) {
  5798. var i, out, c, c_len;
  5799. var len = max || buf.length;
  5800. // Reserve max possible length (2 words per char)
  5801. // NB: by unknown reasons, Array is significantly faster for
  5802. // String.fromCharCode.apply than Uint16Array.
  5803. var utf16buf = new Array(len * 2);
  5804. for (out = 0, i = 0; i < len;) {
  5805. c = buf[i++];
  5806. // quick process ascii
  5807. if (c < 0x80) { utf16buf[out++] = c; continue; }
  5808. c_len = _utf8len[c];
  5809. // skip 5 & 6 byte codes
  5810. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  5811. // apply mask on first byte
  5812. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  5813. // join the rest
  5814. while (c_len > 1 && i < len) {
  5815. c = (c << 6) | (buf[i++] & 0x3f);
  5816. c_len--;
  5817. }
  5818. // terminated by end of string?
  5819. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  5820. if (c < 0x10000) {
  5821. utf16buf[out++] = c;
  5822. } else {
  5823. c -= 0x10000;
  5824. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  5825. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  5826. }
  5827. }
  5828. return buf2binstring(utf16buf, out);
  5829. };
  5830. // Calculate max possible position in utf8 buffer,
  5831. // that will not break sequence. If that's not possible
  5832. // - (very small limits) return max size as is.
  5833. //
  5834. // buf[] - utf8 bytes array
  5835. // max - length limit (mandatory);
  5836. exports.utf8border = function (buf, max) {
  5837. var pos;
  5838. max = max || buf.length;
  5839. if (max > buf.length) { max = buf.length; }
  5840. // go back from last position, until start of sequence found
  5841. pos = max - 1;
  5842. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  5843. // Fuckup - very small and broken sequence,
  5844. // return max, because we should return something anyway.
  5845. if (pos < 0) { return max; }
  5846. // If we came to start of buffer - that means vuffer is too small,
  5847. // return max too.
  5848. if (pos === 0) { return max; }
  5849. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  5850. };
  5851. },{"./common":32}],34:[function(_dereq_,module,exports){
  5852. 'use strict';
  5853. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  5854. // It doesn't worth to make additional optimizationa as in original.
  5855. // Small size is preferable.
  5856. function adler32(adler, buf, len, pos) {
  5857. var s1 = (adler & 0xffff) |0,
  5858. s2 = ((adler >>> 16) & 0xffff) |0,
  5859. n = 0;
  5860. while (len !== 0) {
  5861. // Set limit ~ twice less than 5552, to keep
  5862. // s2 in 31-bits, because we force signed ints.
  5863. // in other case %= will fail.
  5864. n = len > 2000 ? 2000 : len;
  5865. len -= n;
  5866. do {
  5867. s1 = (s1 + buf[pos++]) |0;
  5868. s2 = (s2 + s1) |0;
  5869. } while (--n);
  5870. s1 %= 65521;
  5871. s2 %= 65521;
  5872. }
  5873. return (s1 | (s2 << 16)) |0;
  5874. }
  5875. module.exports = adler32;
  5876. },{}],35:[function(_dereq_,module,exports){
  5877. 'use strict';
  5878. module.exports = {
  5879. /* Allowed flush values; see deflate() and inflate() below for details */
  5880. Z_NO_FLUSH: 0,
  5881. Z_PARTIAL_FLUSH: 1,
  5882. Z_SYNC_FLUSH: 2,
  5883. Z_FULL_FLUSH: 3,
  5884. Z_FINISH: 4,
  5885. Z_BLOCK: 5,
  5886. Z_TREES: 6,
  5887. /* Return codes for the compression/decompression functions. Negative values
  5888. * are errors, positive values are used for special but normal events.
  5889. */
  5890. Z_OK: 0,
  5891. Z_STREAM_END: 1,
  5892. Z_NEED_DICT: 2,
  5893. Z_ERRNO: -1,
  5894. Z_STREAM_ERROR: -2,
  5895. Z_DATA_ERROR: -3,
  5896. //Z_MEM_ERROR: -4,
  5897. Z_BUF_ERROR: -5,
  5898. //Z_VERSION_ERROR: -6,
  5899. /* compression levels */
  5900. Z_NO_COMPRESSION: 0,
  5901. Z_BEST_SPEED: 1,
  5902. Z_BEST_COMPRESSION: 9,
  5903. Z_DEFAULT_COMPRESSION: -1,
  5904. Z_FILTERED: 1,
  5905. Z_HUFFMAN_ONLY: 2,
  5906. Z_RLE: 3,
  5907. Z_FIXED: 4,
  5908. Z_DEFAULT_STRATEGY: 0,
  5909. /* Possible values of the data_type field (though see inflate()) */
  5910. Z_BINARY: 0,
  5911. Z_TEXT: 1,
  5912. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  5913. Z_UNKNOWN: 2,
  5914. /* The deflate compression method */
  5915. Z_DEFLATED: 8
  5916. //Z_NULL: null // Use -1 or null inline, depending on var type
  5917. };
  5918. },{}],36:[function(_dereq_,module,exports){
  5919. 'use strict';
  5920. // Note: we can't get significant speed boost here.
  5921. // So write code to minimize size - no pregenerated tables
  5922. // and array tools dependencies.
  5923. // Use ordinary array, since untyped makes no boost here
  5924. function makeTable() {
  5925. var c, table = [];
  5926. for (var n = 0; n < 256; n++) {
  5927. c = n;
  5928. for (var k = 0; k < 8; k++) {
  5929. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  5930. }
  5931. table[n] = c;
  5932. }
  5933. return table;
  5934. }
  5935. // Create table on load. Just 255 signed longs. Not a problem.
  5936. var crcTable = makeTable();
  5937. function crc32(crc, buf, len, pos) {
  5938. var t = crcTable,
  5939. end = pos + len;
  5940. crc ^= -1;
  5941. for (var i = pos; i < end; i++) {
  5942. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  5943. }
  5944. return (crc ^ (-1)); // >>> 0;
  5945. }
  5946. module.exports = crc32;
  5947. },{}],37:[function(_dereq_,module,exports){
  5948. 'use strict';
  5949. var utils = _dereq_('../utils/common');
  5950. var trees = _dereq_('./trees');
  5951. var adler32 = _dereq_('./adler32');
  5952. var crc32 = _dereq_('./crc32');
  5953. var msg = _dereq_('./messages');
  5954. /* Public constants ==========================================================*/
  5955. /* ===========================================================================*/
  5956. /* Allowed flush values; see deflate() and inflate() below for details */
  5957. var Z_NO_FLUSH = 0;
  5958. var Z_PARTIAL_FLUSH = 1;
  5959. //var Z_SYNC_FLUSH = 2;
  5960. var Z_FULL_FLUSH = 3;
  5961. var Z_FINISH = 4;
  5962. var Z_BLOCK = 5;
  5963. //var Z_TREES = 6;
  5964. /* Return codes for the compression/decompression functions. Negative values
  5965. * are errors, positive values are used for special but normal events.
  5966. */
  5967. var Z_OK = 0;
  5968. var Z_STREAM_END = 1;
  5969. //var Z_NEED_DICT = 2;
  5970. //var Z_ERRNO = -1;
  5971. var Z_STREAM_ERROR = -2;
  5972. var Z_DATA_ERROR = -3;
  5973. //var Z_MEM_ERROR = -4;
  5974. var Z_BUF_ERROR = -5;
  5975. //var Z_VERSION_ERROR = -6;
  5976. /* compression levels */
  5977. //var Z_NO_COMPRESSION = 0;
  5978. //var Z_BEST_SPEED = 1;
  5979. //var Z_BEST_COMPRESSION = 9;
  5980. var Z_DEFAULT_COMPRESSION = -1;
  5981. var Z_FILTERED = 1;
  5982. var Z_HUFFMAN_ONLY = 2;
  5983. var Z_RLE = 3;
  5984. var Z_FIXED = 4;
  5985. var Z_DEFAULT_STRATEGY = 0;
  5986. /* Possible values of the data_type field (though see inflate()) */
  5987. //var Z_BINARY = 0;
  5988. //var Z_TEXT = 1;
  5989. //var Z_ASCII = 1; // = Z_TEXT
  5990. var Z_UNKNOWN = 2;
  5991. /* The deflate compression method */
  5992. var Z_DEFLATED = 8;
  5993. /*============================================================================*/
  5994. var MAX_MEM_LEVEL = 9;
  5995. /* Maximum value for memLevel in deflateInit2 */
  5996. var MAX_WBITS = 15;
  5997. /* 32K LZ77 window */
  5998. var DEF_MEM_LEVEL = 8;
  5999. var LENGTH_CODES = 29;
  6000. /* number of length codes, not counting the special END_BLOCK code */
  6001. var LITERALS = 256;
  6002. /* number of literal bytes 0..255 */
  6003. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  6004. /* number of Literal or Length codes, including the END_BLOCK code */
  6005. var D_CODES = 30;
  6006. /* number of distance codes */
  6007. var BL_CODES = 19;
  6008. /* number of codes used to transfer the bit lengths */
  6009. var HEAP_SIZE = 2 * L_CODES + 1;
  6010. /* maximum heap size */
  6011. var MAX_BITS = 15;
  6012. /* All codes must not exceed MAX_BITS bits */
  6013. var MIN_MATCH = 3;
  6014. var MAX_MATCH = 258;
  6015. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  6016. var PRESET_DICT = 0x20;
  6017. var INIT_STATE = 42;
  6018. var EXTRA_STATE = 69;
  6019. var NAME_STATE = 73;
  6020. var COMMENT_STATE = 91;
  6021. var HCRC_STATE = 103;
  6022. var BUSY_STATE = 113;
  6023. var FINISH_STATE = 666;
  6024. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  6025. var BS_BLOCK_DONE = 2; /* block flush performed */
  6026. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  6027. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  6028. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  6029. function err(strm, errorCode) {
  6030. strm.msg = msg[errorCode];
  6031. return errorCode;
  6032. }
  6033. function rank(f) {
  6034. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  6035. }
  6036. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6037. /* =========================================================================
  6038. * Flush as much pending output as possible. All deflate() output goes
  6039. * through this function so some applications may wish to modify it
  6040. * to avoid allocating a large strm->output buffer and copying into it.
  6041. * (See also read_buf()).
  6042. */
  6043. function flush_pending(strm) {
  6044. var s = strm.state;
  6045. //_tr_flush_bits(s);
  6046. var len = s.pending;
  6047. if (len > strm.avail_out) {
  6048. len = strm.avail_out;
  6049. }
  6050. if (len === 0) { return; }
  6051. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  6052. strm.next_out += len;
  6053. s.pending_out += len;
  6054. strm.total_out += len;
  6055. strm.avail_out -= len;
  6056. s.pending -= len;
  6057. if (s.pending === 0) {
  6058. s.pending_out = 0;
  6059. }
  6060. }
  6061. function flush_block_only(s, last) {
  6062. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  6063. s.block_start = s.strstart;
  6064. flush_pending(s.strm);
  6065. }
  6066. function put_byte(s, b) {
  6067. s.pending_buf[s.pending++] = b;
  6068. }
  6069. /* =========================================================================
  6070. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  6071. * IN assertion: the stream state is correct and there is enough room in
  6072. * pending_buf.
  6073. */
  6074. function putShortMSB(s, b) {
  6075. // put_byte(s, (Byte)(b >> 8));
  6076. // put_byte(s, (Byte)(b & 0xff));
  6077. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  6078. s.pending_buf[s.pending++] = b & 0xff;
  6079. }
  6080. /* ===========================================================================
  6081. * Read a new buffer from the current input stream, update the adler32
  6082. * and total number of bytes read. All deflate() input goes through
  6083. * this function so some applications may wish to modify it to avoid
  6084. * allocating a large strm->input buffer and copying from it.
  6085. * (See also flush_pending()).
  6086. */
  6087. function read_buf(strm, buf, start, size) {
  6088. var len = strm.avail_in;
  6089. if (len > size) { len = size; }
  6090. if (len === 0) { return 0; }
  6091. strm.avail_in -= len;
  6092. // zmemcpy(buf, strm->next_in, len);
  6093. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6094. if (strm.state.wrap === 1) {
  6095. strm.adler = adler32(strm.adler, buf, len, start);
  6096. }
  6097. else if (strm.state.wrap === 2) {
  6098. strm.adler = crc32(strm.adler, buf, len, start);
  6099. }
  6100. strm.next_in += len;
  6101. strm.total_in += len;
  6102. return len;
  6103. }
  6104. /* ===========================================================================
  6105. * Set match_start to the longest match starting at the given string and
  6106. * return its length. Matches shorter or equal to prev_length are discarded,
  6107. * in which case the result is equal to prev_length and match_start is
  6108. * garbage.
  6109. * IN assertions: cur_match is the head of the hash chain for the current
  6110. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6111. * OUT assertion: the match length is not greater than s->lookahead.
  6112. */
  6113. function longest_match(s, cur_match) {
  6114. var chain_length = s.max_chain_length; /* max hash chain length */
  6115. var scan = s.strstart; /* current string */
  6116. var match; /* matched string */
  6117. var len; /* length of current match */
  6118. var best_len = s.prev_length; /* best match length so far */
  6119. var nice_match = s.nice_match; /* stop if match long enough */
  6120. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6121. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6122. var _win = s.window; // shortcut
  6123. var wmask = s.w_mask;
  6124. var prev = s.prev;
  6125. /* Stop when cur_match becomes <= limit. To simplify the code,
  6126. * we prevent matches with the string of window index 0.
  6127. */
  6128. var strend = s.strstart + MAX_MATCH;
  6129. var scan_end1 = _win[scan + best_len - 1];
  6130. var scan_end = _win[scan + best_len];
  6131. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6132. * It is easy to get rid of this optimization if necessary.
  6133. */
  6134. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6135. /* Do not waste too much time if we already have a good match: */
  6136. if (s.prev_length >= s.good_match) {
  6137. chain_length >>= 2;
  6138. }
  6139. /* Do not look for matches beyond the end of the input. This is necessary
  6140. * to make deflate deterministic.
  6141. */
  6142. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6143. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6144. do {
  6145. // Assert(cur_match < s->strstart, "no future");
  6146. match = cur_match;
  6147. /* Skip to next match if the match length cannot increase
  6148. * or if the match length is less than 2. Note that the checks below
  6149. * for insufficient lookahead only occur occasionally for performance
  6150. * reasons. Therefore uninitialized memory will be accessed, and
  6151. * conditional jumps will be made that depend on those values.
  6152. * However the length of the match is limited to the lookahead, so
  6153. * the output of deflate is not affected by the uninitialized values.
  6154. */
  6155. if (_win[match + best_len] !== scan_end ||
  6156. _win[match + best_len - 1] !== scan_end1 ||
  6157. _win[match] !== _win[scan] ||
  6158. _win[++match] !== _win[scan + 1]) {
  6159. continue;
  6160. }
  6161. /* The check at best_len-1 can be removed because it will be made
  6162. * again later. (This heuristic is not always a win.)
  6163. * It is not necessary to compare scan[2] and match[2] since they
  6164. * are always equal when the other bytes match, given that
  6165. * the hash keys are equal and that HASH_BITS >= 8.
  6166. */
  6167. scan += 2;
  6168. match++;
  6169. // Assert(*scan == *match, "match[2]?");
  6170. /* We check for insufficient lookahead only every 8th comparison;
  6171. * the 256th check will be made at strstart+258.
  6172. */
  6173. do {
  6174. /*jshint noempty:false*/
  6175. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6176. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6177. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6178. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6179. scan < strend);
  6180. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  6181. len = MAX_MATCH - (strend - scan);
  6182. scan = strend - MAX_MATCH;
  6183. if (len > best_len) {
  6184. s.match_start = cur_match;
  6185. best_len = len;
  6186. if (len >= nice_match) {
  6187. break;
  6188. }
  6189. scan_end1 = _win[scan + best_len - 1];
  6190. scan_end = _win[scan + best_len];
  6191. }
  6192. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  6193. if (best_len <= s.lookahead) {
  6194. return best_len;
  6195. }
  6196. return s.lookahead;
  6197. }
  6198. /* ===========================================================================
  6199. * Fill the window when the lookahead becomes insufficient.
  6200. * Updates strstart and lookahead.
  6201. *
  6202. * IN assertion: lookahead < MIN_LOOKAHEAD
  6203. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  6204. * At least one byte has been read, or avail_in == 0; reads are
  6205. * performed for at least two bytes (required for the zip translate_eol
  6206. * option -- not supported here).
  6207. */
  6208. function fill_window(s) {
  6209. var _w_size = s.w_size;
  6210. var p, n, m, more, str;
  6211. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  6212. do {
  6213. more = s.window_size - s.lookahead - s.strstart;
  6214. // JS ints have 32 bit, block below not needed
  6215. /* Deal with !@#$% 64K limit: */
  6216. //if (sizeof(int) <= 2) {
  6217. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  6218. // more = wsize;
  6219. //
  6220. // } else if (more == (unsigned)(-1)) {
  6221. // /* Very unlikely, but possible on 16 bit machine if
  6222. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  6223. // */
  6224. // more--;
  6225. // }
  6226. //}
  6227. /* If the window is almost full and there is insufficient lookahead,
  6228. * move the upper half to the lower one to make room in the upper half.
  6229. */
  6230. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  6231. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  6232. s.match_start -= _w_size;
  6233. s.strstart -= _w_size;
  6234. /* we now have strstart >= MAX_DIST */
  6235. s.block_start -= _w_size;
  6236. /* Slide the hash table (could be avoided with 32 bit values
  6237. at the expense of memory usage). We slide even when level == 0
  6238. to keep the hash table consistent if we switch back to level > 0
  6239. later. (Using level 0 permanently is not an optimal usage of
  6240. zlib, so we don't care about this pathological case.)
  6241. */
  6242. n = s.hash_size;
  6243. p = n;
  6244. do {
  6245. m = s.head[--p];
  6246. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  6247. } while (--n);
  6248. n = _w_size;
  6249. p = n;
  6250. do {
  6251. m = s.prev[--p];
  6252. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  6253. /* If n is not on any hash chain, prev[n] is garbage but
  6254. * its value will never be used.
  6255. */
  6256. } while (--n);
  6257. more += _w_size;
  6258. }
  6259. if (s.strm.avail_in === 0) {
  6260. break;
  6261. }
  6262. /* If there was no sliding:
  6263. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  6264. * more == window_size - lookahead - strstart
  6265. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  6266. * => more >= window_size - 2*WSIZE + 2
  6267. * In the BIG_MEM or MMAP case (not yet supported),
  6268. * window_size == input_size + MIN_LOOKAHEAD &&
  6269. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  6270. * Otherwise, window_size == 2*WSIZE so more >= 2.
  6271. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  6272. */
  6273. //Assert(more >= 2, "more < 2");
  6274. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  6275. s.lookahead += n;
  6276. /* Initialize the hash value now that we have some input: */
  6277. if (s.lookahead + s.insert >= MIN_MATCH) {
  6278. str = s.strstart - s.insert;
  6279. s.ins_h = s.window[str];
  6280. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  6281. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  6282. //#if MIN_MATCH != 3
  6283. // Call update_hash() MIN_MATCH-3 more times
  6284. //#endif
  6285. while (s.insert) {
  6286. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6287. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  6288. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6289. s.head[s.ins_h] = str;
  6290. str++;
  6291. s.insert--;
  6292. if (s.lookahead + s.insert < MIN_MATCH) {
  6293. break;
  6294. }
  6295. }
  6296. }
  6297. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  6298. * but this is not important since only literal bytes will be emitted.
  6299. */
  6300. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  6301. /* If the WIN_INIT bytes after the end of the current data have never been
  6302. * written, then zero those bytes in order to avoid memory check reports of
  6303. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  6304. * the longest match routines. Update the high water mark for the next
  6305. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  6306. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  6307. */
  6308. // if (s.high_water < s.window_size) {
  6309. // var curr = s.strstart + s.lookahead;
  6310. // var init = 0;
  6311. //
  6312. // if (s.high_water < curr) {
  6313. // /* Previous high water mark below current data -- zero WIN_INIT
  6314. // * bytes or up to end of window, whichever is less.
  6315. // */
  6316. // init = s.window_size - curr;
  6317. // if (init > WIN_INIT)
  6318. // init = WIN_INIT;
  6319. // zmemzero(s->window + curr, (unsigned)init);
  6320. // s->high_water = curr + init;
  6321. // }
  6322. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  6323. // /* High water mark at or above current data, but below current data
  6324. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  6325. // * to end of window, whichever is less.
  6326. // */
  6327. // init = (ulg)curr + WIN_INIT - s->high_water;
  6328. // if (init > s->window_size - s->high_water)
  6329. // init = s->window_size - s->high_water;
  6330. // zmemzero(s->window + s->high_water, (unsigned)init);
  6331. // s->high_water += init;
  6332. // }
  6333. // }
  6334. //
  6335. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  6336. // "not enough room for search");
  6337. }
  6338. /* ===========================================================================
  6339. * Copy without compression as much as possible from the input stream, return
  6340. * the current block state.
  6341. * This function does not insert new strings in the dictionary since
  6342. * uncompressible data is probably not useful. This function is used
  6343. * only for the level=0 compression option.
  6344. * NOTE: this function should be optimized to avoid extra copying from
  6345. * window to pending_buf.
  6346. */
  6347. function deflate_stored(s, flush) {
  6348. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  6349. * to pending_buf_size, and each stored block has a 5 byte header:
  6350. */
  6351. var max_block_size = 0xffff;
  6352. if (max_block_size > s.pending_buf_size - 5) {
  6353. max_block_size = s.pending_buf_size - 5;
  6354. }
  6355. /* Copy as much as possible from input to output: */
  6356. for (;;) {
  6357. /* Fill the window as much as possible: */
  6358. if (s.lookahead <= 1) {
  6359. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  6360. // s->block_start >= (long)s->w_size, "slide too late");
  6361. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  6362. // s.block_start >= s.w_size)) {
  6363. // throw new Error("slide too late");
  6364. // }
  6365. fill_window(s);
  6366. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  6367. return BS_NEED_MORE;
  6368. }
  6369. if (s.lookahead === 0) {
  6370. break;
  6371. }
  6372. /* flush the current block */
  6373. }
  6374. //Assert(s->block_start >= 0L, "block gone");
  6375. // if (s.block_start < 0) throw new Error("block gone");
  6376. s.strstart += s.lookahead;
  6377. s.lookahead = 0;
  6378. /* Emit a stored block if pending_buf will be full: */
  6379. var max_start = s.block_start + max_block_size;
  6380. if (s.strstart === 0 || s.strstart >= max_start) {
  6381. /* strstart == 0 is possible when wraparound on 16-bit machine */
  6382. s.lookahead = s.strstart - max_start;
  6383. s.strstart = max_start;
  6384. /*** FLUSH_BLOCK(s, 0); ***/
  6385. flush_block_only(s, false);
  6386. if (s.strm.avail_out === 0) {
  6387. return BS_NEED_MORE;
  6388. }
  6389. /***/
  6390. }
  6391. /* Flush if we may have to slide, otherwise block_start may become
  6392. * negative and the data will be gone:
  6393. */
  6394. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  6395. /*** FLUSH_BLOCK(s, 0); ***/
  6396. flush_block_only(s, false);
  6397. if (s.strm.avail_out === 0) {
  6398. return BS_NEED_MORE;
  6399. }
  6400. /***/
  6401. }
  6402. }
  6403. s.insert = 0;
  6404. if (flush === Z_FINISH) {
  6405. /*** FLUSH_BLOCK(s, 1); ***/
  6406. flush_block_only(s, true);
  6407. if (s.strm.avail_out === 0) {
  6408. return BS_FINISH_STARTED;
  6409. }
  6410. /***/
  6411. return BS_FINISH_DONE;
  6412. }
  6413. if (s.strstart > s.block_start) {
  6414. /*** FLUSH_BLOCK(s, 0); ***/
  6415. flush_block_only(s, false);
  6416. if (s.strm.avail_out === 0) {
  6417. return BS_NEED_MORE;
  6418. }
  6419. /***/
  6420. }
  6421. return BS_NEED_MORE;
  6422. }
  6423. /* ===========================================================================
  6424. * Compress as much as possible from the input stream, return the current
  6425. * block state.
  6426. * This function does not perform lazy evaluation of matches and inserts
  6427. * new strings in the dictionary only for unmatched strings or for short
  6428. * matches. It is used only for the fast compression options.
  6429. */
  6430. function deflate_fast(s, flush) {
  6431. var hash_head; /* head of the hash chain */
  6432. var bflush; /* set if current block must be flushed */
  6433. for (;;) {
  6434. /* Make sure that we always have enough lookahead, except
  6435. * at the end of the input file. We need MAX_MATCH bytes
  6436. * for the next match, plus MIN_MATCH bytes to insert the
  6437. * string following the next match.
  6438. */
  6439. if (s.lookahead < MIN_LOOKAHEAD) {
  6440. fill_window(s);
  6441. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6442. return BS_NEED_MORE;
  6443. }
  6444. if (s.lookahead === 0) {
  6445. break; /* flush the current block */
  6446. }
  6447. }
  6448. /* Insert the string window[strstart .. strstart+2] in the
  6449. * dictionary, and set hash_head to the head of the hash chain:
  6450. */
  6451. hash_head = 0/*NIL*/;
  6452. if (s.lookahead >= MIN_MATCH) {
  6453. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6454. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6455. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6456. s.head[s.ins_h] = s.strstart;
  6457. /***/
  6458. }
  6459. /* Find the longest match, discarding those <= prev_length.
  6460. * At this point we have always match_length < MIN_MATCH
  6461. */
  6462. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  6463. /* To simplify the code, we prevent matches with the string
  6464. * of window index 0 (in particular we have to avoid a match
  6465. * of the string with itself at the start of the input file).
  6466. */
  6467. s.match_length = longest_match(s, hash_head);
  6468. /* longest_match() sets match_start */
  6469. }
  6470. if (s.match_length >= MIN_MATCH) {
  6471. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  6472. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  6473. s.match_length - MIN_MATCH, bflush); ***/
  6474. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  6475. s.lookahead -= s.match_length;
  6476. /* Insert new strings in the hash table only if the match length
  6477. * is not too large. This saves time but degrades compression.
  6478. */
  6479. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  6480. s.match_length--; /* string at strstart already in table */
  6481. do {
  6482. s.strstart++;
  6483. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6484. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6485. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6486. s.head[s.ins_h] = s.strstart;
  6487. /***/
  6488. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  6489. * always MIN_MATCH bytes ahead.
  6490. */
  6491. } while (--s.match_length !== 0);
  6492. s.strstart++;
  6493. } else
  6494. {
  6495. s.strstart += s.match_length;
  6496. s.match_length = 0;
  6497. s.ins_h = s.window[s.strstart];
  6498. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  6499. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  6500. //#if MIN_MATCH != 3
  6501. // Call UPDATE_HASH() MIN_MATCH-3 more times
  6502. //#endif
  6503. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  6504. * matter since it will be recomputed at next deflate call.
  6505. */
  6506. }
  6507. } else {
  6508. /* No match, output a literal byte */
  6509. //Tracevv((stderr,"%c", s.window[s.strstart]));
  6510. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6511. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6512. s.lookahead--;
  6513. s.strstart++;
  6514. }
  6515. if (bflush) {
  6516. /*** FLUSH_BLOCK(s, 0); ***/
  6517. flush_block_only(s, false);
  6518. if (s.strm.avail_out === 0) {
  6519. return BS_NEED_MORE;
  6520. }
  6521. /***/
  6522. }
  6523. }
  6524. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  6525. if (flush === Z_FINISH) {
  6526. /*** FLUSH_BLOCK(s, 1); ***/
  6527. flush_block_only(s, true);
  6528. if (s.strm.avail_out === 0) {
  6529. return BS_FINISH_STARTED;
  6530. }
  6531. /***/
  6532. return BS_FINISH_DONE;
  6533. }
  6534. if (s.last_lit) {
  6535. /*** FLUSH_BLOCK(s, 0); ***/
  6536. flush_block_only(s, false);
  6537. if (s.strm.avail_out === 0) {
  6538. return BS_NEED_MORE;
  6539. }
  6540. /***/
  6541. }
  6542. return BS_BLOCK_DONE;
  6543. }
  6544. /* ===========================================================================
  6545. * Same as above, but achieves better compression. We use a lazy
  6546. * evaluation for matches: a match is finally adopted only if there is
  6547. * no better match at the next window position.
  6548. */
  6549. function deflate_slow(s, flush) {
  6550. var hash_head; /* head of hash chain */
  6551. var bflush; /* set if current block must be flushed */
  6552. var max_insert;
  6553. /* Process the input block. */
  6554. for (;;) {
  6555. /* Make sure that we always have enough lookahead, except
  6556. * at the end of the input file. We need MAX_MATCH bytes
  6557. * for the next match, plus MIN_MATCH bytes to insert the
  6558. * string following the next match.
  6559. */
  6560. if (s.lookahead < MIN_LOOKAHEAD) {
  6561. fill_window(s);
  6562. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6563. return BS_NEED_MORE;
  6564. }
  6565. if (s.lookahead === 0) { break; } /* flush the current block */
  6566. }
  6567. /* Insert the string window[strstart .. strstart+2] in the
  6568. * dictionary, and set hash_head to the head of the hash chain:
  6569. */
  6570. hash_head = 0/*NIL*/;
  6571. if (s.lookahead >= MIN_MATCH) {
  6572. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6573. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6574. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6575. s.head[s.ins_h] = s.strstart;
  6576. /***/
  6577. }
  6578. /* Find the longest match, discarding those <= prev_length.
  6579. */
  6580. s.prev_length = s.match_length;
  6581. s.prev_match = s.match_start;
  6582. s.match_length = MIN_MATCH - 1;
  6583. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  6584. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  6585. /* To simplify the code, we prevent matches with the string
  6586. * of window index 0 (in particular we have to avoid a match
  6587. * of the string with itself at the start of the input file).
  6588. */
  6589. s.match_length = longest_match(s, hash_head);
  6590. /* longest_match() sets match_start */
  6591. if (s.match_length <= 5 &&
  6592. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  6593. /* If prev_match is also MIN_MATCH, match_start is garbage
  6594. * but we will ignore the current match anyway.
  6595. */
  6596. s.match_length = MIN_MATCH - 1;
  6597. }
  6598. }
  6599. /* If there was a match at the previous step and the current
  6600. * match is not better, output the previous match:
  6601. */
  6602. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  6603. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  6604. /* Do not insert strings in hash table beyond this. */
  6605. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  6606. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  6607. s.prev_length - MIN_MATCH, bflush);***/
  6608. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  6609. /* Insert in hash table all strings up to the end of the match.
  6610. * strstart-1 and strstart are already inserted. If there is not
  6611. * enough lookahead, the last two strings are not inserted in
  6612. * the hash table.
  6613. */
  6614. s.lookahead -= s.prev_length - 1;
  6615. s.prev_length -= 2;
  6616. do {
  6617. if (++s.strstart <= max_insert) {
  6618. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6619. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6620. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6621. s.head[s.ins_h] = s.strstart;
  6622. /***/
  6623. }
  6624. } while (--s.prev_length !== 0);
  6625. s.match_available = 0;
  6626. s.match_length = MIN_MATCH - 1;
  6627. s.strstart++;
  6628. if (bflush) {
  6629. /*** FLUSH_BLOCK(s, 0); ***/
  6630. flush_block_only(s, false);
  6631. if (s.strm.avail_out === 0) {
  6632. return BS_NEED_MORE;
  6633. }
  6634. /***/
  6635. }
  6636. } else if (s.match_available) {
  6637. /* If there was no match at the previous position, output a
  6638. * single literal. If there was a match but the current match
  6639. * is longer, truncate the previous match to a single literal.
  6640. */
  6641. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6642. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6643. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6644. if (bflush) {
  6645. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  6646. flush_block_only(s, false);
  6647. /***/
  6648. }
  6649. s.strstart++;
  6650. s.lookahead--;
  6651. if (s.strm.avail_out === 0) {
  6652. return BS_NEED_MORE;
  6653. }
  6654. } else {
  6655. /* There is no previous match to compare with, wait for
  6656. * the next step to decide.
  6657. */
  6658. s.match_available = 1;
  6659. s.strstart++;
  6660. s.lookahead--;
  6661. }
  6662. }
  6663. //Assert (flush != Z_NO_FLUSH, "no flush?");
  6664. if (s.match_available) {
  6665. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6666. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6667. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6668. s.match_available = 0;
  6669. }
  6670. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  6671. if (flush === Z_FINISH) {
  6672. /*** FLUSH_BLOCK(s, 1); ***/
  6673. flush_block_only(s, true);
  6674. if (s.strm.avail_out === 0) {
  6675. return BS_FINISH_STARTED;
  6676. }
  6677. /***/
  6678. return BS_FINISH_DONE;
  6679. }
  6680. if (s.last_lit) {
  6681. /*** FLUSH_BLOCK(s, 0); ***/
  6682. flush_block_only(s, false);
  6683. if (s.strm.avail_out === 0) {
  6684. return BS_NEED_MORE;
  6685. }
  6686. /***/
  6687. }
  6688. return BS_BLOCK_DONE;
  6689. }
  6690. /* ===========================================================================
  6691. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  6692. * one. Do not maintain a hash table. (It will be regenerated if this run of
  6693. * deflate switches away from Z_RLE.)
  6694. */
  6695. function deflate_rle(s, flush) {
  6696. var bflush; /* set if current block must be flushed */
  6697. var prev; /* byte at distance one to match */
  6698. var scan, strend; /* scan goes up to strend for length of run */
  6699. var _win = s.window;
  6700. for (;;) {
  6701. /* Make sure that we always have enough lookahead, except
  6702. * at the end of the input file. We need MAX_MATCH bytes
  6703. * for the longest run, plus one for the unrolled loop.
  6704. */
  6705. if (s.lookahead <= MAX_MATCH) {
  6706. fill_window(s);
  6707. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  6708. return BS_NEED_MORE;
  6709. }
  6710. if (s.lookahead === 0) { break; } /* flush the current block */
  6711. }
  6712. /* See how many times the previous byte repeats */
  6713. s.match_length = 0;
  6714. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  6715. scan = s.strstart - 1;
  6716. prev = _win[scan];
  6717. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  6718. strend = s.strstart + MAX_MATCH;
  6719. do {
  6720. /*jshint noempty:false*/
  6721. } while (prev === _win[++scan] && prev === _win[++scan] &&
  6722. prev === _win[++scan] && prev === _win[++scan] &&
  6723. prev === _win[++scan] && prev === _win[++scan] &&
  6724. prev === _win[++scan] && prev === _win[++scan] &&
  6725. scan < strend);
  6726. s.match_length = MAX_MATCH - (strend - scan);
  6727. if (s.match_length > s.lookahead) {
  6728. s.match_length = s.lookahead;
  6729. }
  6730. }
  6731. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  6732. }
  6733. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  6734. if (s.match_length >= MIN_MATCH) {
  6735. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  6736. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  6737. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  6738. s.lookahead -= s.match_length;
  6739. s.strstart += s.match_length;
  6740. s.match_length = 0;
  6741. } else {
  6742. /* No match, output a literal byte */
  6743. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6744. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6745. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6746. s.lookahead--;
  6747. s.strstart++;
  6748. }
  6749. if (bflush) {
  6750. /*** FLUSH_BLOCK(s, 0); ***/
  6751. flush_block_only(s, false);
  6752. if (s.strm.avail_out === 0) {
  6753. return BS_NEED_MORE;
  6754. }
  6755. /***/
  6756. }
  6757. }
  6758. s.insert = 0;
  6759. if (flush === Z_FINISH) {
  6760. /*** FLUSH_BLOCK(s, 1); ***/
  6761. flush_block_only(s, true);
  6762. if (s.strm.avail_out === 0) {
  6763. return BS_FINISH_STARTED;
  6764. }
  6765. /***/
  6766. return BS_FINISH_DONE;
  6767. }
  6768. if (s.last_lit) {
  6769. /*** FLUSH_BLOCK(s, 0); ***/
  6770. flush_block_only(s, false);
  6771. if (s.strm.avail_out === 0) {
  6772. return BS_NEED_MORE;
  6773. }
  6774. /***/
  6775. }
  6776. return BS_BLOCK_DONE;
  6777. }
  6778. /* ===========================================================================
  6779. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  6780. * (It will be regenerated if this run of deflate switches away from Huffman.)
  6781. */
  6782. function deflate_huff(s, flush) {
  6783. var bflush; /* set if current block must be flushed */
  6784. for (;;) {
  6785. /* Make sure that we have a literal to write. */
  6786. if (s.lookahead === 0) {
  6787. fill_window(s);
  6788. if (s.lookahead === 0) {
  6789. if (flush === Z_NO_FLUSH) {
  6790. return BS_NEED_MORE;
  6791. }
  6792. break; /* flush the current block */
  6793. }
  6794. }
  6795. /* Output a literal byte */
  6796. s.match_length = 0;
  6797. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6798. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6799. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6800. s.lookahead--;
  6801. s.strstart++;
  6802. if (bflush) {
  6803. /*** FLUSH_BLOCK(s, 0); ***/
  6804. flush_block_only(s, false);
  6805. if (s.strm.avail_out === 0) {
  6806. return BS_NEED_MORE;
  6807. }
  6808. /***/
  6809. }
  6810. }
  6811. s.insert = 0;
  6812. if (flush === Z_FINISH) {
  6813. /*** FLUSH_BLOCK(s, 1); ***/
  6814. flush_block_only(s, true);
  6815. if (s.strm.avail_out === 0) {
  6816. return BS_FINISH_STARTED;
  6817. }
  6818. /***/
  6819. return BS_FINISH_DONE;
  6820. }
  6821. if (s.last_lit) {
  6822. /*** FLUSH_BLOCK(s, 0); ***/
  6823. flush_block_only(s, false);
  6824. if (s.strm.avail_out === 0) {
  6825. return BS_NEED_MORE;
  6826. }
  6827. /***/
  6828. }
  6829. return BS_BLOCK_DONE;
  6830. }
  6831. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  6832. * the desired pack level (0..9). The values given below have been tuned to
  6833. * exclude worst case performance for pathological files. Better values may be
  6834. * found for specific files.
  6835. */
  6836. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  6837. this.good_length = good_length;
  6838. this.max_lazy = max_lazy;
  6839. this.nice_length = nice_length;
  6840. this.max_chain = max_chain;
  6841. this.func = func;
  6842. }
  6843. var configuration_table;
  6844. configuration_table = [
  6845. /* good lazy nice chain */
  6846. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  6847. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  6848. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  6849. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  6850. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  6851. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  6852. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  6853. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  6854. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  6855. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  6856. ];
  6857. /* ===========================================================================
  6858. * Initialize the "longest match" routines for a new zlib stream
  6859. */
  6860. function lm_init(s) {
  6861. s.window_size = 2 * s.w_size;
  6862. /*** CLEAR_HASH(s); ***/
  6863. zero(s.head); // Fill with NIL (= 0);
  6864. /* Set the default configuration parameters:
  6865. */
  6866. s.max_lazy_match = configuration_table[s.level].max_lazy;
  6867. s.good_match = configuration_table[s.level].good_length;
  6868. s.nice_match = configuration_table[s.level].nice_length;
  6869. s.max_chain_length = configuration_table[s.level].max_chain;
  6870. s.strstart = 0;
  6871. s.block_start = 0;
  6872. s.lookahead = 0;
  6873. s.insert = 0;
  6874. s.match_length = s.prev_length = MIN_MATCH - 1;
  6875. s.match_available = 0;
  6876. s.ins_h = 0;
  6877. }
  6878. function DeflateState() {
  6879. this.strm = null; /* pointer back to this zlib stream */
  6880. this.status = 0; /* as the name implies */
  6881. this.pending_buf = null; /* output still pending */
  6882. this.pending_buf_size = 0; /* size of pending_buf */
  6883. this.pending_out = 0; /* next pending byte to output to the stream */
  6884. this.pending = 0; /* nb of bytes in the pending buffer */
  6885. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  6886. this.gzhead = null; /* gzip header information to write */
  6887. this.gzindex = 0; /* where in extra, name, or comment */
  6888. this.method = Z_DEFLATED; /* can only be DEFLATED */
  6889. this.last_flush = -1; /* value of flush param for previous deflate call */
  6890. this.w_size = 0; /* LZ77 window size (32K by default) */
  6891. this.w_bits = 0; /* log2(w_size) (8..16) */
  6892. this.w_mask = 0; /* w_size - 1 */
  6893. this.window = null;
  6894. /* Sliding window. Input bytes are read into the second half of the window,
  6895. * and move to the first half later to keep a dictionary of at least wSize
  6896. * bytes. With this organization, matches are limited to a distance of
  6897. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  6898. * performed with a length multiple of the block size.
  6899. */
  6900. this.window_size = 0;
  6901. /* Actual size of window: 2*wSize, except when the user input buffer
  6902. * is directly used as sliding window.
  6903. */
  6904. this.prev = null;
  6905. /* Link to older string with same hash index. To limit the size of this
  6906. * array to 64K, this link is maintained only for the last 32K strings.
  6907. * An index in this array is thus a window index modulo 32K.
  6908. */
  6909. this.head = null; /* Heads of the hash chains or NIL. */
  6910. this.ins_h = 0; /* hash index of string to be inserted */
  6911. this.hash_size = 0; /* number of elements in hash table */
  6912. this.hash_bits = 0; /* log2(hash_size) */
  6913. this.hash_mask = 0; /* hash_size-1 */
  6914. this.hash_shift = 0;
  6915. /* Number of bits by which ins_h must be shifted at each input
  6916. * step. It must be such that after MIN_MATCH steps, the oldest
  6917. * byte no longer takes part in the hash key, that is:
  6918. * hash_shift * MIN_MATCH >= hash_bits
  6919. */
  6920. this.block_start = 0;
  6921. /* Window position at the beginning of the current output block. Gets
  6922. * negative when the window is moved backwards.
  6923. */
  6924. this.match_length = 0; /* length of best match */
  6925. this.prev_match = 0; /* previous match */
  6926. this.match_available = 0; /* set if previous match exists */
  6927. this.strstart = 0; /* start of string to insert */
  6928. this.match_start = 0; /* start of matching string */
  6929. this.lookahead = 0; /* number of valid bytes ahead in window */
  6930. this.prev_length = 0;
  6931. /* Length of the best match at previous step. Matches not greater than this
  6932. * are discarded. This is used in the lazy match evaluation.
  6933. */
  6934. this.max_chain_length = 0;
  6935. /* To speed up deflation, hash chains are never searched beyond this
  6936. * length. A higher limit improves compression ratio but degrades the
  6937. * speed.
  6938. */
  6939. this.max_lazy_match = 0;
  6940. /* Attempt to find a better match only when the current match is strictly
  6941. * smaller than this value. This mechanism is used only for compression
  6942. * levels >= 4.
  6943. */
  6944. // That's alias to max_lazy_match, don't use directly
  6945. //this.max_insert_length = 0;
  6946. /* Insert new strings in the hash table only if the match length is not
  6947. * greater than this length. This saves time but degrades compression.
  6948. * max_insert_length is used only for compression levels <= 3.
  6949. */
  6950. this.level = 0; /* compression level (1..9) */
  6951. this.strategy = 0; /* favor or force Huffman coding*/
  6952. this.good_match = 0;
  6953. /* Use a faster search when the previous match is longer than this */
  6954. this.nice_match = 0; /* Stop searching when current match exceeds this */
  6955. /* used by trees.c: */
  6956. /* Didn't use ct_data typedef below to suppress compiler warning */
  6957. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  6958. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  6959. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  6960. // Use flat array of DOUBLE size, with interleaved fata,
  6961. // because JS does not support effective
  6962. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  6963. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  6964. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  6965. zero(this.dyn_ltree);
  6966. zero(this.dyn_dtree);
  6967. zero(this.bl_tree);
  6968. this.l_desc = null; /* desc. for literal tree */
  6969. this.d_desc = null; /* desc. for distance tree */
  6970. this.bl_desc = null; /* desc. for bit length tree */
  6971. //ush bl_count[MAX_BITS+1];
  6972. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  6973. /* number of codes at each bit length for an optimal tree */
  6974. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  6975. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  6976. zero(this.heap);
  6977. this.heap_len = 0; /* number of elements in the heap */
  6978. this.heap_max = 0; /* element of largest frequency */
  6979. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  6980. * The same heap array is used to build all trees.
  6981. */
  6982. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  6983. zero(this.depth);
  6984. /* Depth of each subtree used as tie breaker for trees of equal frequency
  6985. */
  6986. this.l_buf = 0; /* buffer index for literals or lengths */
  6987. this.lit_bufsize = 0;
  6988. /* Size of match buffer for literals/lengths. There are 4 reasons for
  6989. * limiting lit_bufsize to 64K:
  6990. * - frequencies can be kept in 16 bit counters
  6991. * - if compression is not successful for the first block, all input
  6992. * data is still in the window so we can still emit a stored block even
  6993. * when input comes from standard input. (This can also be done for
  6994. * all blocks if lit_bufsize is not greater than 32K.)
  6995. * - if compression is not successful for a file smaller than 64K, we can
  6996. * even emit a stored file instead of a stored block (saving 5 bytes).
  6997. * This is applicable only for zip (not gzip or zlib).
  6998. * - creating new Huffman trees less frequently may not provide fast
  6999. * adaptation to changes in the input data statistics. (Take for
  7000. * example a binary file with poorly compressible code followed by
  7001. * a highly compressible string table.) Smaller buffer sizes give
  7002. * fast adaptation but have of course the overhead of transmitting
  7003. * trees more frequently.
  7004. * - I can't count above 4
  7005. */
  7006. this.last_lit = 0; /* running index in l_buf */
  7007. this.d_buf = 0;
  7008. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  7009. * the same number of elements. To use different lengths, an extra flag
  7010. * array would be necessary.
  7011. */
  7012. this.opt_len = 0; /* bit length of current block with optimal trees */
  7013. this.static_len = 0; /* bit length of current block with static trees */
  7014. this.matches = 0; /* number of string matches in current block */
  7015. this.insert = 0; /* bytes at end of window left to insert */
  7016. this.bi_buf = 0;
  7017. /* Output buffer. bits are inserted starting at the bottom (least
  7018. * significant bits).
  7019. */
  7020. this.bi_valid = 0;
  7021. /* Number of valid bits in bi_buf. All bits above the last valid bit
  7022. * are always zero.
  7023. */
  7024. // Used for window memory init. We safely ignore it for JS. That makes
  7025. // sense only for pointers and memory check tools.
  7026. //this.high_water = 0;
  7027. /* High water mark offset in window for initialized bytes -- bytes above
  7028. * this are set to zero in order to avoid memory check warnings when
  7029. * longest match routines access bytes past the input. This is then
  7030. * updated to the new high water mark.
  7031. */
  7032. }
  7033. function deflateResetKeep(strm) {
  7034. var s;
  7035. if (!strm || !strm.state) {
  7036. return err(strm, Z_STREAM_ERROR);
  7037. }
  7038. strm.total_in = strm.total_out = 0;
  7039. strm.data_type = Z_UNKNOWN;
  7040. s = strm.state;
  7041. s.pending = 0;
  7042. s.pending_out = 0;
  7043. if (s.wrap < 0) {
  7044. s.wrap = -s.wrap;
  7045. /* was made negative by deflate(..., Z_FINISH); */
  7046. }
  7047. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  7048. strm.adler = (s.wrap === 2) ?
  7049. 0 // crc32(0, Z_NULL, 0)
  7050. :
  7051. 1; // adler32(0, Z_NULL, 0)
  7052. s.last_flush = Z_NO_FLUSH;
  7053. trees._tr_init(s);
  7054. return Z_OK;
  7055. }
  7056. function deflateReset(strm) {
  7057. var ret = deflateResetKeep(strm);
  7058. if (ret === Z_OK) {
  7059. lm_init(strm.state);
  7060. }
  7061. return ret;
  7062. }
  7063. function deflateSetHeader(strm, head) {
  7064. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7065. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  7066. strm.state.gzhead = head;
  7067. return Z_OK;
  7068. }
  7069. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  7070. if (!strm) { // === Z_NULL
  7071. return Z_STREAM_ERROR;
  7072. }
  7073. var wrap = 1;
  7074. if (level === Z_DEFAULT_COMPRESSION) {
  7075. level = 6;
  7076. }
  7077. if (windowBits < 0) { /* suppress zlib wrapper */
  7078. wrap = 0;
  7079. windowBits = -windowBits;
  7080. }
  7081. else if (windowBits > 15) {
  7082. wrap = 2; /* write gzip wrapper instead */
  7083. windowBits -= 16;
  7084. }
  7085. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7086. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7087. strategy < 0 || strategy > Z_FIXED) {
  7088. return err(strm, Z_STREAM_ERROR);
  7089. }
  7090. if (windowBits === 8) {
  7091. windowBits = 9;
  7092. }
  7093. /* until 256-byte window bug fixed */
  7094. var s = new DeflateState();
  7095. strm.state = s;
  7096. s.strm = strm;
  7097. s.wrap = wrap;
  7098. s.gzhead = null;
  7099. s.w_bits = windowBits;
  7100. s.w_size = 1 << s.w_bits;
  7101. s.w_mask = s.w_size - 1;
  7102. s.hash_bits = memLevel + 7;
  7103. s.hash_size = 1 << s.hash_bits;
  7104. s.hash_mask = s.hash_size - 1;
  7105. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7106. s.window = new utils.Buf8(s.w_size * 2);
  7107. s.head = new utils.Buf16(s.hash_size);
  7108. s.prev = new utils.Buf16(s.w_size);
  7109. // Don't need mem init magic for JS.
  7110. //s.high_water = 0; /* nothing written to s->window yet */
  7111. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7112. s.pending_buf_size = s.lit_bufsize * 4;
  7113. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7114. s.d_buf = s.lit_bufsize >> 1;
  7115. s.l_buf = (1 + 2) * s.lit_bufsize;
  7116. s.level = level;
  7117. s.strategy = strategy;
  7118. s.method = method;
  7119. return deflateReset(strm);
  7120. }
  7121. function deflateInit(strm, level) {
  7122. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7123. }
  7124. function deflate(strm, flush) {
  7125. var old_flush, s;
  7126. var beg, val; // for gzip header write only
  7127. if (!strm || !strm.state ||
  7128. flush > Z_BLOCK || flush < 0) {
  7129. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7130. }
  7131. s = strm.state;
  7132. if (!strm.output ||
  7133. (!strm.input && strm.avail_in !== 0) ||
  7134. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7135. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7136. }
  7137. s.strm = strm; /* just in case */
  7138. old_flush = s.last_flush;
  7139. s.last_flush = flush;
  7140. /* Write the header */
  7141. if (s.status === INIT_STATE) {
  7142. if (s.wrap === 2) { // GZIP header
  7143. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7144. put_byte(s, 31);
  7145. put_byte(s, 139);
  7146. put_byte(s, 8);
  7147. if (!s.gzhead) { // s->gzhead == Z_NULL
  7148. put_byte(s, 0);
  7149. put_byte(s, 0);
  7150. put_byte(s, 0);
  7151. put_byte(s, 0);
  7152. put_byte(s, 0);
  7153. put_byte(s, s.level === 9 ? 2 :
  7154. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7155. 4 : 0));
  7156. put_byte(s, OS_CODE);
  7157. s.status = BUSY_STATE;
  7158. }
  7159. else {
  7160. put_byte(s, (s.gzhead.text ? 1 : 0) +
  7161. (s.gzhead.hcrc ? 2 : 0) +
  7162. (!s.gzhead.extra ? 0 : 4) +
  7163. (!s.gzhead.name ? 0 : 8) +
  7164. (!s.gzhead.comment ? 0 : 16)
  7165. );
  7166. put_byte(s, s.gzhead.time & 0xff);
  7167. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7168. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7169. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7170. put_byte(s, s.level === 9 ? 2 :
  7171. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7172. 4 : 0));
  7173. put_byte(s, s.gzhead.os & 0xff);
  7174. if (s.gzhead.extra && s.gzhead.extra.length) {
  7175. put_byte(s, s.gzhead.extra.length & 0xff);
  7176. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  7177. }
  7178. if (s.gzhead.hcrc) {
  7179. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  7180. }
  7181. s.gzindex = 0;
  7182. s.status = EXTRA_STATE;
  7183. }
  7184. }
  7185. else // DEFLATE header
  7186. {
  7187. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  7188. var level_flags = -1;
  7189. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  7190. level_flags = 0;
  7191. } else if (s.level < 6) {
  7192. level_flags = 1;
  7193. } else if (s.level === 6) {
  7194. level_flags = 2;
  7195. } else {
  7196. level_flags = 3;
  7197. }
  7198. header |= (level_flags << 6);
  7199. if (s.strstart !== 0) { header |= PRESET_DICT; }
  7200. header += 31 - (header % 31);
  7201. s.status = BUSY_STATE;
  7202. putShortMSB(s, header);
  7203. /* Save the adler32 of the preset dictionary: */
  7204. if (s.strstart !== 0) {
  7205. putShortMSB(s, strm.adler >>> 16);
  7206. putShortMSB(s, strm.adler & 0xffff);
  7207. }
  7208. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  7209. }
  7210. }
  7211. //#ifdef GZIP
  7212. if (s.status === EXTRA_STATE) {
  7213. if (s.gzhead.extra/* != Z_NULL*/) {
  7214. beg = s.pending; /* start of bytes to update crc */
  7215. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  7216. if (s.pending === s.pending_buf_size) {
  7217. if (s.gzhead.hcrc && s.pending > beg) {
  7218. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7219. }
  7220. flush_pending(strm);
  7221. beg = s.pending;
  7222. if (s.pending === s.pending_buf_size) {
  7223. break;
  7224. }
  7225. }
  7226. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  7227. s.gzindex++;
  7228. }
  7229. if (s.gzhead.hcrc && s.pending > beg) {
  7230. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7231. }
  7232. if (s.gzindex === s.gzhead.extra.length) {
  7233. s.gzindex = 0;
  7234. s.status = NAME_STATE;
  7235. }
  7236. }
  7237. else {
  7238. s.status = NAME_STATE;
  7239. }
  7240. }
  7241. if (s.status === NAME_STATE) {
  7242. if (s.gzhead.name/* != Z_NULL*/) {
  7243. beg = s.pending; /* start of bytes to update crc */
  7244. //int val;
  7245. do {
  7246. if (s.pending === s.pending_buf_size) {
  7247. if (s.gzhead.hcrc && s.pending > beg) {
  7248. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7249. }
  7250. flush_pending(strm);
  7251. beg = s.pending;
  7252. if (s.pending === s.pending_buf_size) {
  7253. val = 1;
  7254. break;
  7255. }
  7256. }
  7257. // JS specific: little magic to add zero terminator to end of string
  7258. if (s.gzindex < s.gzhead.name.length) {
  7259. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  7260. } else {
  7261. val = 0;
  7262. }
  7263. put_byte(s, val);
  7264. } while (val !== 0);
  7265. if (s.gzhead.hcrc && s.pending > beg) {
  7266. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7267. }
  7268. if (val === 0) {
  7269. s.gzindex = 0;
  7270. s.status = COMMENT_STATE;
  7271. }
  7272. }
  7273. else {
  7274. s.status = COMMENT_STATE;
  7275. }
  7276. }
  7277. if (s.status === COMMENT_STATE) {
  7278. if (s.gzhead.comment/* != Z_NULL*/) {
  7279. beg = s.pending; /* start of bytes to update crc */
  7280. //int val;
  7281. do {
  7282. if (s.pending === s.pending_buf_size) {
  7283. if (s.gzhead.hcrc && s.pending > beg) {
  7284. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7285. }
  7286. flush_pending(strm);
  7287. beg = s.pending;
  7288. if (s.pending === s.pending_buf_size) {
  7289. val = 1;
  7290. break;
  7291. }
  7292. }
  7293. // JS specific: little magic to add zero terminator to end of string
  7294. if (s.gzindex < s.gzhead.comment.length) {
  7295. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  7296. } else {
  7297. val = 0;
  7298. }
  7299. put_byte(s, val);
  7300. } while (val !== 0);
  7301. if (s.gzhead.hcrc && s.pending > beg) {
  7302. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7303. }
  7304. if (val === 0) {
  7305. s.status = HCRC_STATE;
  7306. }
  7307. }
  7308. else {
  7309. s.status = HCRC_STATE;
  7310. }
  7311. }
  7312. if (s.status === HCRC_STATE) {
  7313. if (s.gzhead.hcrc) {
  7314. if (s.pending + 2 > s.pending_buf_size) {
  7315. flush_pending(strm);
  7316. }
  7317. if (s.pending + 2 <= s.pending_buf_size) {
  7318. put_byte(s, strm.adler & 0xff);
  7319. put_byte(s, (strm.adler >> 8) & 0xff);
  7320. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7321. s.status = BUSY_STATE;
  7322. }
  7323. }
  7324. else {
  7325. s.status = BUSY_STATE;
  7326. }
  7327. }
  7328. //#endif
  7329. /* Flush as much pending output as possible */
  7330. if (s.pending !== 0) {
  7331. flush_pending(strm);
  7332. if (strm.avail_out === 0) {
  7333. /* Since avail_out is 0, deflate will be called again with
  7334. * more output space, but possibly with both pending and
  7335. * avail_in equal to zero. There won't be anything to do,
  7336. * but this is not an error situation so make sure we
  7337. * return OK instead of BUF_ERROR at next call of deflate:
  7338. */
  7339. s.last_flush = -1;
  7340. return Z_OK;
  7341. }
  7342. /* Make sure there is something to do and avoid duplicate consecutive
  7343. * flushes. For repeated and useless calls with Z_FINISH, we keep
  7344. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  7345. */
  7346. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  7347. flush !== Z_FINISH) {
  7348. return err(strm, Z_BUF_ERROR);
  7349. }
  7350. /* User must not provide more input after the first FINISH: */
  7351. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  7352. return err(strm, Z_BUF_ERROR);
  7353. }
  7354. /* Start a new block or continue the current one.
  7355. */
  7356. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  7357. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  7358. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  7359. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  7360. configuration_table[s.level].func(s, flush));
  7361. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  7362. s.status = FINISH_STATE;
  7363. }
  7364. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  7365. if (strm.avail_out === 0) {
  7366. s.last_flush = -1;
  7367. /* avoid BUF_ERROR next call, see above */
  7368. }
  7369. return Z_OK;
  7370. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  7371. * of deflate should use the same flush parameter to make sure
  7372. * that the flush is complete. So we don't have to output an
  7373. * empty block here, this will be done at next call. This also
  7374. * ensures that for a very small output buffer, we emit at most
  7375. * one empty block.
  7376. */
  7377. }
  7378. if (bstate === BS_BLOCK_DONE) {
  7379. if (flush === Z_PARTIAL_FLUSH) {
  7380. trees._tr_align(s);
  7381. }
  7382. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  7383. trees._tr_stored_block(s, 0, 0, false);
  7384. /* For a full flush, this empty block will be recognized
  7385. * as a special marker by inflate_sync().
  7386. */
  7387. if (flush === Z_FULL_FLUSH) {
  7388. /*** CLEAR_HASH(s); ***/ /* forget history */
  7389. zero(s.head); // Fill with NIL (= 0);
  7390. if (s.lookahead === 0) {
  7391. s.strstart = 0;
  7392. s.block_start = 0;
  7393. s.insert = 0;
  7394. }
  7395. }
  7396. }
  7397. flush_pending(strm);
  7398. if (strm.avail_out === 0) {
  7399. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  7400. return Z_OK;
  7401. }
  7402. }
  7403. }
  7404. //Assert(strm->avail_out > 0, "bug2");
  7405. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  7406. if (flush !== Z_FINISH) { return Z_OK; }
  7407. if (s.wrap <= 0) { return Z_STREAM_END; }
  7408. /* Write the trailer */
  7409. if (s.wrap === 2) {
  7410. put_byte(s, strm.adler & 0xff);
  7411. put_byte(s, (strm.adler >> 8) & 0xff);
  7412. put_byte(s, (strm.adler >> 16) & 0xff);
  7413. put_byte(s, (strm.adler >> 24) & 0xff);
  7414. put_byte(s, strm.total_in & 0xff);
  7415. put_byte(s, (strm.total_in >> 8) & 0xff);
  7416. put_byte(s, (strm.total_in >> 16) & 0xff);
  7417. put_byte(s, (strm.total_in >> 24) & 0xff);
  7418. }
  7419. else
  7420. {
  7421. putShortMSB(s, strm.adler >>> 16);
  7422. putShortMSB(s, strm.adler & 0xffff);
  7423. }
  7424. flush_pending(strm);
  7425. /* If avail_out is zero, the application will call deflate again
  7426. * to flush the rest.
  7427. */
  7428. if (s.wrap > 0) { s.wrap = -s.wrap; }
  7429. /* write the trailer only once! */
  7430. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  7431. }
  7432. function deflateEnd(strm) {
  7433. var status;
  7434. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7435. return Z_STREAM_ERROR;
  7436. }
  7437. status = strm.state.status;
  7438. if (status !== INIT_STATE &&
  7439. status !== EXTRA_STATE &&
  7440. status !== NAME_STATE &&
  7441. status !== COMMENT_STATE &&
  7442. status !== HCRC_STATE &&
  7443. status !== BUSY_STATE &&
  7444. status !== FINISH_STATE
  7445. ) {
  7446. return err(strm, Z_STREAM_ERROR);
  7447. }
  7448. strm.state = null;
  7449. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  7450. }
  7451. /* =========================================================================
  7452. * Initializes the compression dictionary from the given byte
  7453. * sequence without producing any compressed output.
  7454. */
  7455. function deflateSetDictionary(strm, dictionary) {
  7456. var dictLength = dictionary.length;
  7457. var s;
  7458. var str, n;
  7459. var wrap;
  7460. var avail;
  7461. var next;
  7462. var input;
  7463. var tmpDict;
  7464. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7465. return Z_STREAM_ERROR;
  7466. }
  7467. s = strm.state;
  7468. wrap = s.wrap;
  7469. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  7470. return Z_STREAM_ERROR;
  7471. }
  7472. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  7473. if (wrap === 1) {
  7474. /* adler32(strm->adler, dictionary, dictLength); */
  7475. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  7476. }
  7477. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  7478. /* if dictionary would fill window, just replace the history */
  7479. if (dictLength >= s.w_size) {
  7480. if (wrap === 0) { /* already empty otherwise */
  7481. /*** CLEAR_HASH(s); ***/
  7482. zero(s.head); // Fill with NIL (= 0);
  7483. s.strstart = 0;
  7484. s.block_start = 0;
  7485. s.insert = 0;
  7486. }
  7487. /* use the tail */
  7488. // dictionary = dictionary.slice(dictLength - s.w_size);
  7489. tmpDict = new utils.Buf8(s.w_size);
  7490. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  7491. dictionary = tmpDict;
  7492. dictLength = s.w_size;
  7493. }
  7494. /* insert dictionary into window and hash */
  7495. avail = strm.avail_in;
  7496. next = strm.next_in;
  7497. input = strm.input;
  7498. strm.avail_in = dictLength;
  7499. strm.next_in = 0;
  7500. strm.input = dictionary;
  7501. fill_window(s);
  7502. while (s.lookahead >= MIN_MATCH) {
  7503. str = s.strstart;
  7504. n = s.lookahead - (MIN_MATCH - 1);
  7505. do {
  7506. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  7507. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  7508. s.prev[str & s.w_mask] = s.head[s.ins_h];
  7509. s.head[s.ins_h] = str;
  7510. str++;
  7511. } while (--n);
  7512. s.strstart = str;
  7513. s.lookahead = MIN_MATCH - 1;
  7514. fill_window(s);
  7515. }
  7516. s.strstart += s.lookahead;
  7517. s.block_start = s.strstart;
  7518. s.insert = s.lookahead;
  7519. s.lookahead = 0;
  7520. s.match_length = s.prev_length = MIN_MATCH - 1;
  7521. s.match_available = 0;
  7522. strm.next_in = next;
  7523. strm.input = input;
  7524. strm.avail_in = avail;
  7525. s.wrap = wrap;
  7526. return Z_OK;
  7527. }
  7528. exports.deflateInit = deflateInit;
  7529. exports.deflateInit2 = deflateInit2;
  7530. exports.deflateReset = deflateReset;
  7531. exports.deflateResetKeep = deflateResetKeep;
  7532. exports.deflateSetHeader = deflateSetHeader;
  7533. exports.deflate = deflate;
  7534. exports.deflateEnd = deflateEnd;
  7535. exports.deflateSetDictionary = deflateSetDictionary;
  7536. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  7537. /* Not implemented
  7538. exports.deflateBound = deflateBound;
  7539. exports.deflateCopy = deflateCopy;
  7540. exports.deflateParams = deflateParams;
  7541. exports.deflatePending = deflatePending;
  7542. exports.deflatePrime = deflatePrime;
  7543. exports.deflateTune = deflateTune;
  7544. */
  7545. },{"../utils/common":32,"./adler32":34,"./crc32":36,"./messages":42,"./trees":43}],38:[function(_dereq_,module,exports){
  7546. 'use strict';
  7547. function GZheader() {
  7548. /* true if compressed data believed to be text */
  7549. this.text = 0;
  7550. /* modification time */
  7551. this.time = 0;
  7552. /* extra flags (not used when writing a gzip file) */
  7553. this.xflags = 0;
  7554. /* operating system */
  7555. this.os = 0;
  7556. /* pointer to extra field or Z_NULL if none */
  7557. this.extra = null;
  7558. /* extra field length (valid if extra != Z_NULL) */
  7559. this.extra_len = 0; // Actually, we don't need it in JS,
  7560. // but leave for few code modifications
  7561. //
  7562. // Setup limits is not necessary because in js we should not preallocate memory
  7563. // for inflate use constant limit in 65536 bytes
  7564. //
  7565. /* space at extra (only when reading header) */
  7566. // this.extra_max = 0;
  7567. /* pointer to zero-terminated file name or Z_NULL */
  7568. this.name = '';
  7569. /* space at name (only when reading header) */
  7570. // this.name_max = 0;
  7571. /* pointer to zero-terminated comment or Z_NULL */
  7572. this.comment = '';
  7573. /* space at comment (only when reading header) */
  7574. // this.comm_max = 0;
  7575. /* true if there was or will be a header crc */
  7576. this.hcrc = 0;
  7577. /* true when done reading gzip header (not used when writing a gzip file) */
  7578. this.done = false;
  7579. }
  7580. module.exports = GZheader;
  7581. },{}],39:[function(_dereq_,module,exports){
  7582. 'use strict';
  7583. // See state defs from inflate.js
  7584. var BAD = 30; /* got a data error -- remain here until reset */
  7585. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7586. /*
  7587. Decode literal, length, and distance codes and write out the resulting
  7588. literal and match bytes until either not enough input or output is
  7589. available, an end-of-block is encountered, or a data error is encountered.
  7590. When large enough input and output buffers are supplied to inflate(), for
  7591. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  7592. inflate execution time is spent in this routine.
  7593. Entry assumptions:
  7594. state.mode === LEN
  7595. strm.avail_in >= 6
  7596. strm.avail_out >= 258
  7597. start >= strm.avail_out
  7598. state.bits < 8
  7599. On return, state.mode is one of:
  7600. LEN -- ran out of enough output space or enough available input
  7601. TYPE -- reached end of block code, inflate() to interpret next block
  7602. BAD -- error in block data
  7603. Notes:
  7604. - The maximum input bits used by a length/distance pair is 15 bits for the
  7605. length code, 5 bits for the length extra, 15 bits for the distance code,
  7606. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  7607. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  7608. checking for available input while decoding.
  7609. - The maximum bytes that a single length/distance pair can output is 258
  7610. bytes, which is the maximum length that can be coded. inflate_fast()
  7611. requires strm.avail_out >= 258 for each loop to avoid checking for
  7612. output space.
  7613. */
  7614. module.exports = function inflate_fast(strm, start) {
  7615. var state;
  7616. var _in; /* local strm.input */
  7617. var last; /* have enough input while in < last */
  7618. var _out; /* local strm.output */
  7619. var beg; /* inflate()'s initial strm.output */
  7620. var end; /* while out < end, enough space available */
  7621. //#ifdef INFLATE_STRICT
  7622. var dmax; /* maximum distance from zlib header */
  7623. //#endif
  7624. var wsize; /* window size or zero if not using window */
  7625. var whave; /* valid bytes in the window */
  7626. var wnext; /* window write index */
  7627. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  7628. var s_window; /* allocated sliding window, if wsize != 0 */
  7629. var hold; /* local strm.hold */
  7630. var bits; /* local strm.bits */
  7631. var lcode; /* local strm.lencode */
  7632. var dcode; /* local strm.distcode */
  7633. var lmask; /* mask for first level of length codes */
  7634. var dmask; /* mask for first level of distance codes */
  7635. var here; /* retrieved table entry */
  7636. var op; /* code bits, operation, extra bits, or */
  7637. /* window position, window bytes to copy */
  7638. var len; /* match length, unused bytes */
  7639. var dist; /* match distance */
  7640. var from; /* where to copy match from */
  7641. var from_source;
  7642. var input, output; // JS specific, because we have no pointers
  7643. /* copy state to local variables */
  7644. state = strm.state;
  7645. //here = state.here;
  7646. _in = strm.next_in;
  7647. input = strm.input;
  7648. last = _in + (strm.avail_in - 5);
  7649. _out = strm.next_out;
  7650. output = strm.output;
  7651. beg = _out - (start - strm.avail_out);
  7652. end = _out + (strm.avail_out - 257);
  7653. //#ifdef INFLATE_STRICT
  7654. dmax = state.dmax;
  7655. //#endif
  7656. wsize = state.wsize;
  7657. whave = state.whave;
  7658. wnext = state.wnext;
  7659. s_window = state.window;
  7660. hold = state.hold;
  7661. bits = state.bits;
  7662. lcode = state.lencode;
  7663. dcode = state.distcode;
  7664. lmask = (1 << state.lenbits) - 1;
  7665. dmask = (1 << state.distbits) - 1;
  7666. /* decode literals and length/distances until end-of-block or not enough
  7667. input data or output space */
  7668. top:
  7669. do {
  7670. if (bits < 15) {
  7671. hold += input[_in++] << bits;
  7672. bits += 8;
  7673. hold += input[_in++] << bits;
  7674. bits += 8;
  7675. }
  7676. here = lcode[hold & lmask];
  7677. dolen:
  7678. for (;;) { // Goto emulation
  7679. op = here >>> 24/*here.bits*/;
  7680. hold >>>= op;
  7681. bits -= op;
  7682. op = (here >>> 16) & 0xff/*here.op*/;
  7683. if (op === 0) { /* literal */
  7684. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  7685. // "inflate: literal '%c'\n" :
  7686. // "inflate: literal 0x%02x\n", here.val));
  7687. output[_out++] = here & 0xffff/*here.val*/;
  7688. }
  7689. else if (op & 16) { /* length base */
  7690. len = here & 0xffff/*here.val*/;
  7691. op &= 15; /* number of extra bits */
  7692. if (op) {
  7693. if (bits < op) {
  7694. hold += input[_in++] << bits;
  7695. bits += 8;
  7696. }
  7697. len += hold & ((1 << op) - 1);
  7698. hold >>>= op;
  7699. bits -= op;
  7700. }
  7701. //Tracevv((stderr, "inflate: length %u\n", len));
  7702. if (bits < 15) {
  7703. hold += input[_in++] << bits;
  7704. bits += 8;
  7705. hold += input[_in++] << bits;
  7706. bits += 8;
  7707. }
  7708. here = dcode[hold & dmask];
  7709. dodist:
  7710. for (;;) { // goto emulation
  7711. op = here >>> 24/*here.bits*/;
  7712. hold >>>= op;
  7713. bits -= op;
  7714. op = (here >>> 16) & 0xff/*here.op*/;
  7715. if (op & 16) { /* distance base */
  7716. dist = here & 0xffff/*here.val*/;
  7717. op &= 15; /* number of extra bits */
  7718. if (bits < op) {
  7719. hold += input[_in++] << bits;
  7720. bits += 8;
  7721. if (bits < op) {
  7722. hold += input[_in++] << bits;
  7723. bits += 8;
  7724. }
  7725. }
  7726. dist += hold & ((1 << op) - 1);
  7727. //#ifdef INFLATE_STRICT
  7728. if (dist > dmax) {
  7729. strm.msg = 'invalid distance too far back';
  7730. state.mode = BAD;
  7731. break top;
  7732. }
  7733. //#endif
  7734. hold >>>= op;
  7735. bits -= op;
  7736. //Tracevv((stderr, "inflate: distance %u\n", dist));
  7737. op = _out - beg; /* max distance in output */
  7738. if (dist > op) { /* see if copy from window */
  7739. op = dist - op; /* distance back in window */
  7740. if (op > whave) {
  7741. if (state.sane) {
  7742. strm.msg = 'invalid distance too far back';
  7743. state.mode = BAD;
  7744. break top;
  7745. }
  7746. // (!) This block is disabled in zlib defailts,
  7747. // don't enable it for binary compatibility
  7748. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  7749. // if (len <= op - whave) {
  7750. // do {
  7751. // output[_out++] = 0;
  7752. // } while (--len);
  7753. // continue top;
  7754. // }
  7755. // len -= op - whave;
  7756. // do {
  7757. // output[_out++] = 0;
  7758. // } while (--op > whave);
  7759. // if (op === 0) {
  7760. // from = _out - dist;
  7761. // do {
  7762. // output[_out++] = output[from++];
  7763. // } while (--len);
  7764. // continue top;
  7765. // }
  7766. //#endif
  7767. }
  7768. from = 0; // window index
  7769. from_source = s_window;
  7770. if (wnext === 0) { /* very common case */
  7771. from += wsize - op;
  7772. if (op < len) { /* some from window */
  7773. len -= op;
  7774. do {
  7775. output[_out++] = s_window[from++];
  7776. } while (--op);
  7777. from = _out - dist; /* rest from output */
  7778. from_source = output;
  7779. }
  7780. }
  7781. else if (wnext < op) { /* wrap around window */
  7782. from += wsize + wnext - op;
  7783. op -= wnext;
  7784. if (op < len) { /* some from end of window */
  7785. len -= op;
  7786. do {
  7787. output[_out++] = s_window[from++];
  7788. } while (--op);
  7789. from = 0;
  7790. if (wnext < len) { /* some from start of window */
  7791. op = wnext;
  7792. len -= op;
  7793. do {
  7794. output[_out++] = s_window[from++];
  7795. } while (--op);
  7796. from = _out - dist; /* rest from output */
  7797. from_source = output;
  7798. }
  7799. }
  7800. }
  7801. else { /* contiguous in window */
  7802. from += wnext - op;
  7803. if (op < len) { /* some from window */
  7804. len -= op;
  7805. do {
  7806. output[_out++] = s_window[from++];
  7807. } while (--op);
  7808. from = _out - dist; /* rest from output */
  7809. from_source = output;
  7810. }
  7811. }
  7812. while (len > 2) {
  7813. output[_out++] = from_source[from++];
  7814. output[_out++] = from_source[from++];
  7815. output[_out++] = from_source[from++];
  7816. len -= 3;
  7817. }
  7818. if (len) {
  7819. output[_out++] = from_source[from++];
  7820. if (len > 1) {
  7821. output[_out++] = from_source[from++];
  7822. }
  7823. }
  7824. }
  7825. else {
  7826. from = _out - dist; /* copy direct from output */
  7827. do { /* minimum length is three */
  7828. output[_out++] = output[from++];
  7829. output[_out++] = output[from++];
  7830. output[_out++] = output[from++];
  7831. len -= 3;
  7832. } while (len > 2);
  7833. if (len) {
  7834. output[_out++] = output[from++];
  7835. if (len > 1) {
  7836. output[_out++] = output[from++];
  7837. }
  7838. }
  7839. }
  7840. }
  7841. else if ((op & 64) === 0) { /* 2nd level distance code */
  7842. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  7843. continue dodist;
  7844. }
  7845. else {
  7846. strm.msg = 'invalid distance code';
  7847. state.mode = BAD;
  7848. break top;
  7849. }
  7850. break; // need to emulate goto via "continue"
  7851. }
  7852. }
  7853. else if ((op & 64) === 0) { /* 2nd level length code */
  7854. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  7855. continue dolen;
  7856. }
  7857. else if (op & 32) { /* end-of-block */
  7858. //Tracevv((stderr, "inflate: end of block\n"));
  7859. state.mode = TYPE;
  7860. break top;
  7861. }
  7862. else {
  7863. strm.msg = 'invalid literal/length code';
  7864. state.mode = BAD;
  7865. break top;
  7866. }
  7867. break; // need to emulate goto via "continue"
  7868. }
  7869. } while (_in < last && _out < end);
  7870. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  7871. len = bits >> 3;
  7872. _in -= len;
  7873. bits -= len << 3;
  7874. hold &= (1 << bits) - 1;
  7875. /* update state and return */
  7876. strm.next_in = _in;
  7877. strm.next_out = _out;
  7878. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  7879. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  7880. state.hold = hold;
  7881. state.bits = bits;
  7882. return;
  7883. };
  7884. },{}],40:[function(_dereq_,module,exports){
  7885. 'use strict';
  7886. var utils = _dereq_('../utils/common');
  7887. var adler32 = _dereq_('./adler32');
  7888. var crc32 = _dereq_('./crc32');
  7889. var inflate_fast = _dereq_('./inffast');
  7890. var inflate_table = _dereq_('./inftrees');
  7891. var CODES = 0;
  7892. var LENS = 1;
  7893. var DISTS = 2;
  7894. /* Public constants ==========================================================*/
  7895. /* ===========================================================================*/
  7896. /* Allowed flush values; see deflate() and inflate() below for details */
  7897. //var Z_NO_FLUSH = 0;
  7898. //var Z_PARTIAL_FLUSH = 1;
  7899. //var Z_SYNC_FLUSH = 2;
  7900. //var Z_FULL_FLUSH = 3;
  7901. var Z_FINISH = 4;
  7902. var Z_BLOCK = 5;
  7903. var Z_TREES = 6;
  7904. /* Return codes for the compression/decompression functions. Negative values
  7905. * are errors, positive values are used for special but normal events.
  7906. */
  7907. var Z_OK = 0;
  7908. var Z_STREAM_END = 1;
  7909. var Z_NEED_DICT = 2;
  7910. //var Z_ERRNO = -1;
  7911. var Z_STREAM_ERROR = -2;
  7912. var Z_DATA_ERROR = -3;
  7913. var Z_MEM_ERROR = -4;
  7914. var Z_BUF_ERROR = -5;
  7915. //var Z_VERSION_ERROR = -6;
  7916. /* The deflate compression method */
  7917. var Z_DEFLATED = 8;
  7918. /* STATES ====================================================================*/
  7919. /* ===========================================================================*/
  7920. var HEAD = 1; /* i: waiting for magic header */
  7921. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  7922. var TIME = 3; /* i: waiting for modification time (gzip) */
  7923. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  7924. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  7925. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  7926. var NAME = 7; /* i: waiting for end of file name (gzip) */
  7927. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  7928. var HCRC = 9; /* i: waiting for header crc (gzip) */
  7929. var DICTID = 10; /* i: waiting for dictionary check value */
  7930. var DICT = 11; /* waiting for inflateSetDictionary() call */
  7931. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7932. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  7933. var STORED = 14; /* i: waiting for stored size (length and complement) */
  7934. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  7935. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  7936. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  7937. var LENLENS = 18; /* i: waiting for code length code lengths */
  7938. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  7939. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  7940. var LEN = 21; /* i: waiting for length/lit/eob code */
  7941. var LENEXT = 22; /* i: waiting for length extra bits */
  7942. var DIST = 23; /* i: waiting for distance code */
  7943. var DISTEXT = 24; /* i: waiting for distance extra bits */
  7944. var MATCH = 25; /* o: waiting for output space to copy string */
  7945. var LIT = 26; /* o: waiting for output space to write literal */
  7946. var CHECK = 27; /* i: waiting for 32-bit check value */
  7947. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  7948. var DONE = 29; /* finished check, done -- remain here until reset */
  7949. var BAD = 30; /* got a data error -- remain here until reset */
  7950. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  7951. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  7952. /* ===========================================================================*/
  7953. var ENOUGH_LENS = 852;
  7954. var ENOUGH_DISTS = 592;
  7955. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  7956. var MAX_WBITS = 15;
  7957. /* 32K LZ77 window */
  7958. var DEF_WBITS = MAX_WBITS;
  7959. function zswap32(q) {
  7960. return (((q >>> 24) & 0xff) +
  7961. ((q >>> 8) & 0xff00) +
  7962. ((q & 0xff00) << 8) +
  7963. ((q & 0xff) << 24));
  7964. }
  7965. function InflateState() {
  7966. this.mode = 0; /* current inflate mode */
  7967. this.last = false; /* true if processing last block */
  7968. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7969. this.havedict = false; /* true if dictionary provided */
  7970. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  7971. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  7972. this.check = 0; /* protected copy of check value */
  7973. this.total = 0; /* protected copy of output count */
  7974. // TODO: may be {}
  7975. this.head = null; /* where to save gzip header information */
  7976. /* sliding window */
  7977. this.wbits = 0; /* log base 2 of requested window size */
  7978. this.wsize = 0; /* window size or zero if not using window */
  7979. this.whave = 0; /* valid bytes in the window */
  7980. this.wnext = 0; /* window write index */
  7981. this.window = null; /* allocated sliding window, if needed */
  7982. /* bit accumulator */
  7983. this.hold = 0; /* input bit accumulator */
  7984. this.bits = 0; /* number of bits in "in" */
  7985. /* for string and stored block copying */
  7986. this.length = 0; /* literal or length of data to copy */
  7987. this.offset = 0; /* distance back to copy string from */
  7988. /* for table and code decoding */
  7989. this.extra = 0; /* extra bits needed */
  7990. /* fixed and dynamic code tables */
  7991. this.lencode = null; /* starting table for length/literal codes */
  7992. this.distcode = null; /* starting table for distance codes */
  7993. this.lenbits = 0; /* index bits for lencode */
  7994. this.distbits = 0; /* index bits for distcode */
  7995. /* dynamic table building */
  7996. this.ncode = 0; /* number of code length code lengths */
  7997. this.nlen = 0; /* number of length code lengths */
  7998. this.ndist = 0; /* number of distance code lengths */
  7999. this.have = 0; /* number of code lengths in lens[] */
  8000. this.next = null; /* next available space in codes[] */
  8001. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  8002. this.work = new utils.Buf16(288); /* work area for code table building */
  8003. /*
  8004. because we don't have pointers in js, we use lencode and distcode directly
  8005. as buffers so we don't need codes
  8006. */
  8007. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  8008. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  8009. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  8010. this.sane = 0; /* if false, allow invalid distance too far */
  8011. this.back = 0; /* bits back of last unprocessed length/lit */
  8012. this.was = 0; /* initial length of match */
  8013. }
  8014. function inflateResetKeep(strm) {
  8015. var state;
  8016. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8017. state = strm.state;
  8018. strm.total_in = strm.total_out = state.total = 0;
  8019. strm.msg = ''; /*Z_NULL*/
  8020. if (state.wrap) { /* to support ill-conceived Java test suite */
  8021. strm.adler = state.wrap & 1;
  8022. }
  8023. state.mode = HEAD;
  8024. state.last = 0;
  8025. state.havedict = 0;
  8026. state.dmax = 32768;
  8027. state.head = null/*Z_NULL*/;
  8028. state.hold = 0;
  8029. state.bits = 0;
  8030. //state.lencode = state.distcode = state.next = state.codes;
  8031. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  8032. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  8033. state.sane = 1;
  8034. state.back = -1;
  8035. //Tracev((stderr, "inflate: reset\n"));
  8036. return Z_OK;
  8037. }
  8038. function inflateReset(strm) {
  8039. var state;
  8040. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8041. state = strm.state;
  8042. state.wsize = 0;
  8043. state.whave = 0;
  8044. state.wnext = 0;
  8045. return inflateResetKeep(strm);
  8046. }
  8047. function inflateReset2(strm, windowBits) {
  8048. var wrap;
  8049. var state;
  8050. /* get the state */
  8051. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8052. state = strm.state;
  8053. /* extract wrap request from windowBits parameter */
  8054. if (windowBits < 0) {
  8055. wrap = 0;
  8056. windowBits = -windowBits;
  8057. }
  8058. else {
  8059. wrap = (windowBits >> 4) + 1;
  8060. if (windowBits < 48) {
  8061. windowBits &= 15;
  8062. }
  8063. }
  8064. /* set number of window bits, free window if different */
  8065. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  8066. return Z_STREAM_ERROR;
  8067. }
  8068. if (state.window !== null && state.wbits !== windowBits) {
  8069. state.window = null;
  8070. }
  8071. /* update state and reset the rest of it */
  8072. state.wrap = wrap;
  8073. state.wbits = windowBits;
  8074. return inflateReset(strm);
  8075. }
  8076. function inflateInit2(strm, windowBits) {
  8077. var ret;
  8078. var state;
  8079. if (!strm) { return Z_STREAM_ERROR; }
  8080. //strm.msg = Z_NULL; /* in case we return an error */
  8081. state = new InflateState();
  8082. //if (state === Z_NULL) return Z_MEM_ERROR;
  8083. //Tracev((stderr, "inflate: allocated\n"));
  8084. strm.state = state;
  8085. state.window = null/*Z_NULL*/;
  8086. ret = inflateReset2(strm, windowBits);
  8087. if (ret !== Z_OK) {
  8088. strm.state = null/*Z_NULL*/;
  8089. }
  8090. return ret;
  8091. }
  8092. function inflateInit(strm) {
  8093. return inflateInit2(strm, DEF_WBITS);
  8094. }
  8095. /*
  8096. Return state with length and distance decoding tables and index sizes set to
  8097. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  8098. If BUILDFIXED is defined, then instead this routine builds the tables the
  8099. first time it's called, and returns those tables the first time and
  8100. thereafter. This reduces the size of the code by about 2K bytes, in
  8101. exchange for a little execution time. However, BUILDFIXED should not be
  8102. used for threaded applications, since the rewriting of the tables and virgin
  8103. may not be thread-safe.
  8104. */
  8105. var virgin = true;
  8106. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  8107. function fixedtables(state) {
  8108. /* build fixed huffman tables if first call (may not be thread safe) */
  8109. if (virgin) {
  8110. var sym;
  8111. lenfix = new utils.Buf32(512);
  8112. distfix = new utils.Buf32(32);
  8113. /* literal/length table */
  8114. sym = 0;
  8115. while (sym < 144) { state.lens[sym++] = 8; }
  8116. while (sym < 256) { state.lens[sym++] = 9; }
  8117. while (sym < 280) { state.lens[sym++] = 7; }
  8118. while (sym < 288) { state.lens[sym++] = 8; }
  8119. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  8120. /* distance table */
  8121. sym = 0;
  8122. while (sym < 32) { state.lens[sym++] = 5; }
  8123. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  8124. /* do this just once */
  8125. virgin = false;
  8126. }
  8127. state.lencode = lenfix;
  8128. state.lenbits = 9;
  8129. state.distcode = distfix;
  8130. state.distbits = 5;
  8131. }
  8132. /*
  8133. Update the window with the last wsize (normally 32K) bytes written before
  8134. returning. If window does not exist yet, create it. This is only called
  8135. when a window is already in use, or when output has been written during this
  8136. inflate call, but the end of the deflate stream has not been reached yet.
  8137. It is also called to create a window for dictionary data when a dictionary
  8138. is loaded.
  8139. Providing output buffers larger than 32K to inflate() should provide a speed
  8140. advantage, since only the last 32K of output is copied to the sliding window
  8141. upon return from inflate(), and since all distances after the first 32K of
  8142. output will fall in the output data, making match copies simpler and faster.
  8143. The advantage may be dependent on the size of the processor's data caches.
  8144. */
  8145. function updatewindow(strm, src, end, copy) {
  8146. var dist;
  8147. var state = strm.state;
  8148. /* if it hasn't been done already, allocate space for the window */
  8149. if (state.window === null) {
  8150. state.wsize = 1 << state.wbits;
  8151. state.wnext = 0;
  8152. state.whave = 0;
  8153. state.window = new utils.Buf8(state.wsize);
  8154. }
  8155. /* copy state->wsize or less output bytes into the circular window */
  8156. if (copy >= state.wsize) {
  8157. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  8158. state.wnext = 0;
  8159. state.whave = state.wsize;
  8160. }
  8161. else {
  8162. dist = state.wsize - state.wnext;
  8163. if (dist > copy) {
  8164. dist = copy;
  8165. }
  8166. //zmemcpy(state->window + state->wnext, end - copy, dist);
  8167. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  8168. copy -= dist;
  8169. if (copy) {
  8170. //zmemcpy(state->window, end - copy, copy);
  8171. utils.arraySet(state.window, src, end - copy, copy, 0);
  8172. state.wnext = copy;
  8173. state.whave = state.wsize;
  8174. }
  8175. else {
  8176. state.wnext += dist;
  8177. if (state.wnext === state.wsize) { state.wnext = 0; }
  8178. if (state.whave < state.wsize) { state.whave += dist; }
  8179. }
  8180. }
  8181. return 0;
  8182. }
  8183. function inflate(strm, flush) {
  8184. var state;
  8185. var input, output; // input/output buffers
  8186. var next; /* next input INDEX */
  8187. var put; /* next output INDEX */
  8188. var have, left; /* available input and output */
  8189. var hold; /* bit buffer */
  8190. var bits; /* bits in bit buffer */
  8191. var _in, _out; /* save starting available input and output */
  8192. var copy; /* number of stored or match bytes to copy */
  8193. var from; /* where to copy match bytes from */
  8194. var from_source;
  8195. var here = 0; /* current decoding table entry */
  8196. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  8197. //var last; /* parent table entry */
  8198. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  8199. var len; /* length to copy for repeats, bits to drop */
  8200. var ret; /* return code */
  8201. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  8202. var opts;
  8203. var n; // temporary var for NEED_BITS
  8204. var order = /* permutation of code lengths */
  8205. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  8206. if (!strm || !strm.state || !strm.output ||
  8207. (!strm.input && strm.avail_in !== 0)) {
  8208. return Z_STREAM_ERROR;
  8209. }
  8210. state = strm.state;
  8211. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  8212. //--- LOAD() ---
  8213. put = strm.next_out;
  8214. output = strm.output;
  8215. left = strm.avail_out;
  8216. next = strm.next_in;
  8217. input = strm.input;
  8218. have = strm.avail_in;
  8219. hold = state.hold;
  8220. bits = state.bits;
  8221. //---
  8222. _in = have;
  8223. _out = left;
  8224. ret = Z_OK;
  8225. inf_leave: // goto emulation
  8226. for (;;) {
  8227. switch (state.mode) {
  8228. case HEAD:
  8229. if (state.wrap === 0) {
  8230. state.mode = TYPEDO;
  8231. break;
  8232. }
  8233. //=== NEEDBITS(16);
  8234. while (bits < 16) {
  8235. if (have === 0) { break inf_leave; }
  8236. have--;
  8237. hold += input[next++] << bits;
  8238. bits += 8;
  8239. }
  8240. //===//
  8241. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  8242. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  8243. //=== CRC2(state.check, hold);
  8244. hbuf[0] = hold & 0xff;
  8245. hbuf[1] = (hold >>> 8) & 0xff;
  8246. state.check = crc32(state.check, hbuf, 2, 0);
  8247. //===//
  8248. //=== INITBITS();
  8249. hold = 0;
  8250. bits = 0;
  8251. //===//
  8252. state.mode = FLAGS;
  8253. break;
  8254. }
  8255. state.flags = 0; /* expect zlib header */
  8256. if (state.head) {
  8257. state.head.done = false;
  8258. }
  8259. if (!(state.wrap & 1) || /* check if zlib header allowed */
  8260. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  8261. strm.msg = 'incorrect header check';
  8262. state.mode = BAD;
  8263. break;
  8264. }
  8265. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  8266. strm.msg = 'unknown compression method';
  8267. state.mode = BAD;
  8268. break;
  8269. }
  8270. //--- DROPBITS(4) ---//
  8271. hold >>>= 4;
  8272. bits -= 4;
  8273. //---//
  8274. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  8275. if (state.wbits === 0) {
  8276. state.wbits = len;
  8277. }
  8278. else if (len > state.wbits) {
  8279. strm.msg = 'invalid window size';
  8280. state.mode = BAD;
  8281. break;
  8282. }
  8283. state.dmax = 1 << len;
  8284. //Tracev((stderr, "inflate: zlib header ok\n"));
  8285. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8286. state.mode = hold & 0x200 ? DICTID : TYPE;
  8287. //=== INITBITS();
  8288. hold = 0;
  8289. bits = 0;
  8290. //===//
  8291. break;
  8292. case FLAGS:
  8293. //=== NEEDBITS(16); */
  8294. while (bits < 16) {
  8295. if (have === 0) { break inf_leave; }
  8296. have--;
  8297. hold += input[next++] << bits;
  8298. bits += 8;
  8299. }
  8300. //===//
  8301. state.flags = hold;
  8302. if ((state.flags & 0xff) !== Z_DEFLATED) {
  8303. strm.msg = 'unknown compression method';
  8304. state.mode = BAD;
  8305. break;
  8306. }
  8307. if (state.flags & 0xe000) {
  8308. strm.msg = 'unknown header flags set';
  8309. state.mode = BAD;
  8310. break;
  8311. }
  8312. if (state.head) {
  8313. state.head.text = ((hold >> 8) & 1);
  8314. }
  8315. if (state.flags & 0x0200) {
  8316. //=== CRC2(state.check, hold);
  8317. hbuf[0] = hold & 0xff;
  8318. hbuf[1] = (hold >>> 8) & 0xff;
  8319. state.check = crc32(state.check, hbuf, 2, 0);
  8320. //===//
  8321. }
  8322. //=== INITBITS();
  8323. hold = 0;
  8324. bits = 0;
  8325. //===//
  8326. state.mode = TIME;
  8327. /* falls through */
  8328. case TIME:
  8329. //=== NEEDBITS(32); */
  8330. while (bits < 32) {
  8331. if (have === 0) { break inf_leave; }
  8332. have--;
  8333. hold += input[next++] << bits;
  8334. bits += 8;
  8335. }
  8336. //===//
  8337. if (state.head) {
  8338. state.head.time = hold;
  8339. }
  8340. if (state.flags & 0x0200) {
  8341. //=== CRC4(state.check, hold)
  8342. hbuf[0] = hold & 0xff;
  8343. hbuf[1] = (hold >>> 8) & 0xff;
  8344. hbuf[2] = (hold >>> 16) & 0xff;
  8345. hbuf[3] = (hold >>> 24) & 0xff;
  8346. state.check = crc32(state.check, hbuf, 4, 0);
  8347. //===
  8348. }
  8349. //=== INITBITS();
  8350. hold = 0;
  8351. bits = 0;
  8352. //===//
  8353. state.mode = OS;
  8354. /* falls through */
  8355. case OS:
  8356. //=== NEEDBITS(16); */
  8357. while (bits < 16) {
  8358. if (have === 0) { break inf_leave; }
  8359. have--;
  8360. hold += input[next++] << bits;
  8361. bits += 8;
  8362. }
  8363. //===//
  8364. if (state.head) {
  8365. state.head.xflags = (hold & 0xff);
  8366. state.head.os = (hold >> 8);
  8367. }
  8368. if (state.flags & 0x0200) {
  8369. //=== CRC2(state.check, hold);
  8370. hbuf[0] = hold & 0xff;
  8371. hbuf[1] = (hold >>> 8) & 0xff;
  8372. state.check = crc32(state.check, hbuf, 2, 0);
  8373. //===//
  8374. }
  8375. //=== INITBITS();
  8376. hold = 0;
  8377. bits = 0;
  8378. //===//
  8379. state.mode = EXLEN;
  8380. /* falls through */
  8381. case EXLEN:
  8382. if (state.flags & 0x0400) {
  8383. //=== NEEDBITS(16); */
  8384. while (bits < 16) {
  8385. if (have === 0) { break inf_leave; }
  8386. have--;
  8387. hold += input[next++] << bits;
  8388. bits += 8;
  8389. }
  8390. //===//
  8391. state.length = hold;
  8392. if (state.head) {
  8393. state.head.extra_len = hold;
  8394. }
  8395. if (state.flags & 0x0200) {
  8396. //=== CRC2(state.check, hold);
  8397. hbuf[0] = hold & 0xff;
  8398. hbuf[1] = (hold >>> 8) & 0xff;
  8399. state.check = crc32(state.check, hbuf, 2, 0);
  8400. //===//
  8401. }
  8402. //=== INITBITS();
  8403. hold = 0;
  8404. bits = 0;
  8405. //===//
  8406. }
  8407. else if (state.head) {
  8408. state.head.extra = null/*Z_NULL*/;
  8409. }
  8410. state.mode = EXTRA;
  8411. /* falls through */
  8412. case EXTRA:
  8413. if (state.flags & 0x0400) {
  8414. copy = state.length;
  8415. if (copy > have) { copy = have; }
  8416. if (copy) {
  8417. if (state.head) {
  8418. len = state.head.extra_len - state.length;
  8419. if (!state.head.extra) {
  8420. // Use untyped array for more conveniend processing later
  8421. state.head.extra = new Array(state.head.extra_len);
  8422. }
  8423. utils.arraySet(
  8424. state.head.extra,
  8425. input,
  8426. next,
  8427. // extra field is limited to 65536 bytes
  8428. // - no need for additional size check
  8429. copy,
  8430. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  8431. len
  8432. );
  8433. //zmemcpy(state.head.extra + len, next,
  8434. // len + copy > state.head.extra_max ?
  8435. // state.head.extra_max - len : copy);
  8436. }
  8437. if (state.flags & 0x0200) {
  8438. state.check = crc32(state.check, input, copy, next);
  8439. }
  8440. have -= copy;
  8441. next += copy;
  8442. state.length -= copy;
  8443. }
  8444. if (state.length) { break inf_leave; }
  8445. }
  8446. state.length = 0;
  8447. state.mode = NAME;
  8448. /* falls through */
  8449. case NAME:
  8450. if (state.flags & 0x0800) {
  8451. if (have === 0) { break inf_leave; }
  8452. copy = 0;
  8453. do {
  8454. // TODO: 2 or 1 bytes?
  8455. len = input[next + copy++];
  8456. /* use constant limit because in js we should not preallocate memory */
  8457. if (state.head && len &&
  8458. (state.length < 65536 /*state.head.name_max*/)) {
  8459. state.head.name += String.fromCharCode(len);
  8460. }
  8461. } while (len && copy < have);
  8462. if (state.flags & 0x0200) {
  8463. state.check = crc32(state.check, input, copy, next);
  8464. }
  8465. have -= copy;
  8466. next += copy;
  8467. if (len) { break inf_leave; }
  8468. }
  8469. else if (state.head) {
  8470. state.head.name = null;
  8471. }
  8472. state.length = 0;
  8473. state.mode = COMMENT;
  8474. /* falls through */
  8475. case COMMENT:
  8476. if (state.flags & 0x1000) {
  8477. if (have === 0) { break inf_leave; }
  8478. copy = 0;
  8479. do {
  8480. len = input[next + copy++];
  8481. /* use constant limit because in js we should not preallocate memory */
  8482. if (state.head && len &&
  8483. (state.length < 65536 /*state.head.comm_max*/)) {
  8484. state.head.comment += String.fromCharCode(len);
  8485. }
  8486. } while (len && copy < have);
  8487. if (state.flags & 0x0200) {
  8488. state.check = crc32(state.check, input, copy, next);
  8489. }
  8490. have -= copy;
  8491. next += copy;
  8492. if (len) { break inf_leave; }
  8493. }
  8494. else if (state.head) {
  8495. state.head.comment = null;
  8496. }
  8497. state.mode = HCRC;
  8498. /* falls through */
  8499. case HCRC:
  8500. if (state.flags & 0x0200) {
  8501. //=== NEEDBITS(16); */
  8502. while (bits < 16) {
  8503. if (have === 0) { break inf_leave; }
  8504. have--;
  8505. hold += input[next++] << bits;
  8506. bits += 8;
  8507. }
  8508. //===//
  8509. if (hold !== (state.check & 0xffff)) {
  8510. strm.msg = 'header crc mismatch';
  8511. state.mode = BAD;
  8512. break;
  8513. }
  8514. //=== INITBITS();
  8515. hold = 0;
  8516. bits = 0;
  8517. //===//
  8518. }
  8519. if (state.head) {
  8520. state.head.hcrc = ((state.flags >> 9) & 1);
  8521. state.head.done = true;
  8522. }
  8523. strm.adler = state.check = 0;
  8524. state.mode = TYPE;
  8525. break;
  8526. case DICTID:
  8527. //=== NEEDBITS(32); */
  8528. while (bits < 32) {
  8529. if (have === 0) { break inf_leave; }
  8530. have--;
  8531. hold += input[next++] << bits;
  8532. bits += 8;
  8533. }
  8534. //===//
  8535. strm.adler = state.check = zswap32(hold);
  8536. //=== INITBITS();
  8537. hold = 0;
  8538. bits = 0;
  8539. //===//
  8540. state.mode = DICT;
  8541. /* falls through */
  8542. case DICT:
  8543. if (state.havedict === 0) {
  8544. //--- RESTORE() ---
  8545. strm.next_out = put;
  8546. strm.avail_out = left;
  8547. strm.next_in = next;
  8548. strm.avail_in = have;
  8549. state.hold = hold;
  8550. state.bits = bits;
  8551. //---
  8552. return Z_NEED_DICT;
  8553. }
  8554. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8555. state.mode = TYPE;
  8556. /* falls through */
  8557. case TYPE:
  8558. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  8559. /* falls through */
  8560. case TYPEDO:
  8561. if (state.last) {
  8562. //--- BYTEBITS() ---//
  8563. hold >>>= bits & 7;
  8564. bits -= bits & 7;
  8565. //---//
  8566. state.mode = CHECK;
  8567. break;
  8568. }
  8569. //=== NEEDBITS(3); */
  8570. while (bits < 3) {
  8571. if (have === 0) { break inf_leave; }
  8572. have--;
  8573. hold += input[next++] << bits;
  8574. bits += 8;
  8575. }
  8576. //===//
  8577. state.last = (hold & 0x01)/*BITS(1)*/;
  8578. //--- DROPBITS(1) ---//
  8579. hold >>>= 1;
  8580. bits -= 1;
  8581. //---//
  8582. switch ((hold & 0x03)/*BITS(2)*/) {
  8583. case 0: /* stored block */
  8584. //Tracev((stderr, "inflate: stored block%s\n",
  8585. // state.last ? " (last)" : ""));
  8586. state.mode = STORED;
  8587. break;
  8588. case 1: /* fixed block */
  8589. fixedtables(state);
  8590. //Tracev((stderr, "inflate: fixed codes block%s\n",
  8591. // state.last ? " (last)" : ""));
  8592. state.mode = LEN_; /* decode codes */
  8593. if (flush === Z_TREES) {
  8594. //--- DROPBITS(2) ---//
  8595. hold >>>= 2;
  8596. bits -= 2;
  8597. //---//
  8598. break inf_leave;
  8599. }
  8600. break;
  8601. case 2: /* dynamic block */
  8602. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  8603. // state.last ? " (last)" : ""));
  8604. state.mode = TABLE;
  8605. break;
  8606. case 3:
  8607. strm.msg = 'invalid block type';
  8608. state.mode = BAD;
  8609. }
  8610. //--- DROPBITS(2) ---//
  8611. hold >>>= 2;
  8612. bits -= 2;
  8613. //---//
  8614. break;
  8615. case STORED:
  8616. //--- BYTEBITS() ---// /* go to byte boundary */
  8617. hold >>>= bits & 7;
  8618. bits -= bits & 7;
  8619. //---//
  8620. //=== NEEDBITS(32); */
  8621. while (bits < 32) {
  8622. if (have === 0) { break inf_leave; }
  8623. have--;
  8624. hold += input[next++] << bits;
  8625. bits += 8;
  8626. }
  8627. //===//
  8628. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  8629. strm.msg = 'invalid stored block lengths';
  8630. state.mode = BAD;
  8631. break;
  8632. }
  8633. state.length = hold & 0xffff;
  8634. //Tracev((stderr, "inflate: stored length %u\n",
  8635. // state.length));
  8636. //=== INITBITS();
  8637. hold = 0;
  8638. bits = 0;
  8639. //===//
  8640. state.mode = COPY_;
  8641. if (flush === Z_TREES) { break inf_leave; }
  8642. /* falls through */
  8643. case COPY_:
  8644. state.mode = COPY;
  8645. /* falls through */
  8646. case COPY:
  8647. copy = state.length;
  8648. if (copy) {
  8649. if (copy > have) { copy = have; }
  8650. if (copy > left) { copy = left; }
  8651. if (copy === 0) { break inf_leave; }
  8652. //--- zmemcpy(put, next, copy); ---
  8653. utils.arraySet(output, input, next, copy, put);
  8654. //---//
  8655. have -= copy;
  8656. next += copy;
  8657. left -= copy;
  8658. put += copy;
  8659. state.length -= copy;
  8660. break;
  8661. }
  8662. //Tracev((stderr, "inflate: stored end\n"));
  8663. state.mode = TYPE;
  8664. break;
  8665. case TABLE:
  8666. //=== NEEDBITS(14); */
  8667. while (bits < 14) {
  8668. if (have === 0) { break inf_leave; }
  8669. have--;
  8670. hold += input[next++] << bits;
  8671. bits += 8;
  8672. }
  8673. //===//
  8674. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  8675. //--- DROPBITS(5) ---//
  8676. hold >>>= 5;
  8677. bits -= 5;
  8678. //---//
  8679. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  8680. //--- DROPBITS(5) ---//
  8681. hold >>>= 5;
  8682. bits -= 5;
  8683. //---//
  8684. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  8685. //--- DROPBITS(4) ---//
  8686. hold >>>= 4;
  8687. bits -= 4;
  8688. //---//
  8689. //#ifndef PKZIP_BUG_WORKAROUND
  8690. if (state.nlen > 286 || state.ndist > 30) {
  8691. strm.msg = 'too many length or distance symbols';
  8692. state.mode = BAD;
  8693. break;
  8694. }
  8695. //#endif
  8696. //Tracev((stderr, "inflate: table sizes ok\n"));
  8697. state.have = 0;
  8698. state.mode = LENLENS;
  8699. /* falls through */
  8700. case LENLENS:
  8701. while (state.have < state.ncode) {
  8702. //=== NEEDBITS(3);
  8703. while (bits < 3) {
  8704. if (have === 0) { break inf_leave; }
  8705. have--;
  8706. hold += input[next++] << bits;
  8707. bits += 8;
  8708. }
  8709. //===//
  8710. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  8711. //--- DROPBITS(3) ---//
  8712. hold >>>= 3;
  8713. bits -= 3;
  8714. //---//
  8715. }
  8716. while (state.have < 19) {
  8717. state.lens[order[state.have++]] = 0;
  8718. }
  8719. // We have separate tables & no pointers. 2 commented lines below not needed.
  8720. //state.next = state.codes;
  8721. //state.lencode = state.next;
  8722. // Switch to use dynamic table
  8723. state.lencode = state.lendyn;
  8724. state.lenbits = 7;
  8725. opts = { bits: state.lenbits };
  8726. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  8727. state.lenbits = opts.bits;
  8728. if (ret) {
  8729. strm.msg = 'invalid code lengths set';
  8730. state.mode = BAD;
  8731. break;
  8732. }
  8733. //Tracev((stderr, "inflate: code lengths ok\n"));
  8734. state.have = 0;
  8735. state.mode = CODELENS;
  8736. /* falls through */
  8737. case CODELENS:
  8738. while (state.have < state.nlen + state.ndist) {
  8739. for (;;) {
  8740. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  8741. here_bits = here >>> 24;
  8742. here_op = (here >>> 16) & 0xff;
  8743. here_val = here & 0xffff;
  8744. if ((here_bits) <= bits) { break; }
  8745. //--- PULLBYTE() ---//
  8746. if (have === 0) { break inf_leave; }
  8747. have--;
  8748. hold += input[next++] << bits;
  8749. bits += 8;
  8750. //---//
  8751. }
  8752. if (here_val < 16) {
  8753. //--- DROPBITS(here.bits) ---//
  8754. hold >>>= here_bits;
  8755. bits -= here_bits;
  8756. //---//
  8757. state.lens[state.have++] = here_val;
  8758. }
  8759. else {
  8760. if (here_val === 16) {
  8761. //=== NEEDBITS(here.bits + 2);
  8762. n = here_bits + 2;
  8763. while (bits < n) {
  8764. if (have === 0) { break inf_leave; }
  8765. have--;
  8766. hold += input[next++] << bits;
  8767. bits += 8;
  8768. }
  8769. //===//
  8770. //--- DROPBITS(here.bits) ---//
  8771. hold >>>= here_bits;
  8772. bits -= here_bits;
  8773. //---//
  8774. if (state.have === 0) {
  8775. strm.msg = 'invalid bit length repeat';
  8776. state.mode = BAD;
  8777. break;
  8778. }
  8779. len = state.lens[state.have - 1];
  8780. copy = 3 + (hold & 0x03);//BITS(2);
  8781. //--- DROPBITS(2) ---//
  8782. hold >>>= 2;
  8783. bits -= 2;
  8784. //---//
  8785. }
  8786. else if (here_val === 17) {
  8787. //=== NEEDBITS(here.bits + 3);
  8788. n = here_bits + 3;
  8789. while (bits < n) {
  8790. if (have === 0) { break inf_leave; }
  8791. have--;
  8792. hold += input[next++] << bits;
  8793. bits += 8;
  8794. }
  8795. //===//
  8796. //--- DROPBITS(here.bits) ---//
  8797. hold >>>= here_bits;
  8798. bits -= here_bits;
  8799. //---//
  8800. len = 0;
  8801. copy = 3 + (hold & 0x07);//BITS(3);
  8802. //--- DROPBITS(3) ---//
  8803. hold >>>= 3;
  8804. bits -= 3;
  8805. //---//
  8806. }
  8807. else {
  8808. //=== NEEDBITS(here.bits + 7);
  8809. n = here_bits + 7;
  8810. while (bits < n) {
  8811. if (have === 0) { break inf_leave; }
  8812. have--;
  8813. hold += input[next++] << bits;
  8814. bits += 8;
  8815. }
  8816. //===//
  8817. //--- DROPBITS(here.bits) ---//
  8818. hold >>>= here_bits;
  8819. bits -= here_bits;
  8820. //---//
  8821. len = 0;
  8822. copy = 11 + (hold & 0x7f);//BITS(7);
  8823. //--- DROPBITS(7) ---//
  8824. hold >>>= 7;
  8825. bits -= 7;
  8826. //---//
  8827. }
  8828. if (state.have + copy > state.nlen + state.ndist) {
  8829. strm.msg = 'invalid bit length repeat';
  8830. state.mode = BAD;
  8831. break;
  8832. }
  8833. while (copy--) {
  8834. state.lens[state.have++] = len;
  8835. }
  8836. }
  8837. }
  8838. /* handle error breaks in while */
  8839. if (state.mode === BAD) { break; }
  8840. /* check for end-of-block code (better have one) */
  8841. if (state.lens[256] === 0) {
  8842. strm.msg = 'invalid code -- missing end-of-block';
  8843. state.mode = BAD;
  8844. break;
  8845. }
  8846. /* build code tables -- note: do not change the lenbits or distbits
  8847. values here (9 and 6) without reading the comments in inftrees.h
  8848. concerning the ENOUGH constants, which depend on those values */
  8849. state.lenbits = 9;
  8850. opts = { bits: state.lenbits };
  8851. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  8852. // We have separate tables & no pointers. 2 commented lines below not needed.
  8853. // state.next_index = opts.table_index;
  8854. state.lenbits = opts.bits;
  8855. // state.lencode = state.next;
  8856. if (ret) {
  8857. strm.msg = 'invalid literal/lengths set';
  8858. state.mode = BAD;
  8859. break;
  8860. }
  8861. state.distbits = 6;
  8862. //state.distcode.copy(state.codes);
  8863. // Switch to use dynamic table
  8864. state.distcode = state.distdyn;
  8865. opts = { bits: state.distbits };
  8866. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  8867. // We have separate tables & no pointers. 2 commented lines below not needed.
  8868. // state.next_index = opts.table_index;
  8869. state.distbits = opts.bits;
  8870. // state.distcode = state.next;
  8871. if (ret) {
  8872. strm.msg = 'invalid distances set';
  8873. state.mode = BAD;
  8874. break;
  8875. }
  8876. //Tracev((stderr, 'inflate: codes ok\n'));
  8877. state.mode = LEN_;
  8878. if (flush === Z_TREES) { break inf_leave; }
  8879. /* falls through */
  8880. case LEN_:
  8881. state.mode = LEN;
  8882. /* falls through */
  8883. case LEN:
  8884. if (have >= 6 && left >= 258) {
  8885. //--- RESTORE() ---
  8886. strm.next_out = put;
  8887. strm.avail_out = left;
  8888. strm.next_in = next;
  8889. strm.avail_in = have;
  8890. state.hold = hold;
  8891. state.bits = bits;
  8892. //---
  8893. inflate_fast(strm, _out);
  8894. //--- LOAD() ---
  8895. put = strm.next_out;
  8896. output = strm.output;
  8897. left = strm.avail_out;
  8898. next = strm.next_in;
  8899. input = strm.input;
  8900. have = strm.avail_in;
  8901. hold = state.hold;
  8902. bits = state.bits;
  8903. //---
  8904. if (state.mode === TYPE) {
  8905. state.back = -1;
  8906. }
  8907. break;
  8908. }
  8909. state.back = 0;
  8910. for (;;) {
  8911. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  8912. here_bits = here >>> 24;
  8913. here_op = (here >>> 16) & 0xff;
  8914. here_val = here & 0xffff;
  8915. if (here_bits <= bits) { break; }
  8916. //--- PULLBYTE() ---//
  8917. if (have === 0) { break inf_leave; }
  8918. have--;
  8919. hold += input[next++] << bits;
  8920. bits += 8;
  8921. //---//
  8922. }
  8923. if (here_op && (here_op & 0xf0) === 0) {
  8924. last_bits = here_bits;
  8925. last_op = here_op;
  8926. last_val = here_val;
  8927. for (;;) {
  8928. here = state.lencode[last_val +
  8929. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  8930. here_bits = here >>> 24;
  8931. here_op = (here >>> 16) & 0xff;
  8932. here_val = here & 0xffff;
  8933. if ((last_bits + here_bits) <= bits) { break; }
  8934. //--- PULLBYTE() ---//
  8935. if (have === 0) { break inf_leave; }
  8936. have--;
  8937. hold += input[next++] << bits;
  8938. bits += 8;
  8939. //---//
  8940. }
  8941. //--- DROPBITS(last.bits) ---//
  8942. hold >>>= last_bits;
  8943. bits -= last_bits;
  8944. //---//
  8945. state.back += last_bits;
  8946. }
  8947. //--- DROPBITS(here.bits) ---//
  8948. hold >>>= here_bits;
  8949. bits -= here_bits;
  8950. //---//
  8951. state.back += here_bits;
  8952. state.length = here_val;
  8953. if (here_op === 0) {
  8954. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8955. // "inflate: literal '%c'\n" :
  8956. // "inflate: literal 0x%02x\n", here.val));
  8957. state.mode = LIT;
  8958. break;
  8959. }
  8960. if (here_op & 32) {
  8961. //Tracevv((stderr, "inflate: end of block\n"));
  8962. state.back = -1;
  8963. state.mode = TYPE;
  8964. break;
  8965. }
  8966. if (here_op & 64) {
  8967. strm.msg = 'invalid literal/length code';
  8968. state.mode = BAD;
  8969. break;
  8970. }
  8971. state.extra = here_op & 15;
  8972. state.mode = LENEXT;
  8973. /* falls through */
  8974. case LENEXT:
  8975. if (state.extra) {
  8976. //=== NEEDBITS(state.extra);
  8977. n = state.extra;
  8978. while (bits < n) {
  8979. if (have === 0) { break inf_leave; }
  8980. have--;
  8981. hold += input[next++] << bits;
  8982. bits += 8;
  8983. }
  8984. //===//
  8985. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  8986. //--- DROPBITS(state.extra) ---//
  8987. hold >>>= state.extra;
  8988. bits -= state.extra;
  8989. //---//
  8990. state.back += state.extra;
  8991. }
  8992. //Tracevv((stderr, "inflate: length %u\n", state.length));
  8993. state.was = state.length;
  8994. state.mode = DIST;
  8995. /* falls through */
  8996. case DIST:
  8997. for (;;) {
  8998. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  8999. here_bits = here >>> 24;
  9000. here_op = (here >>> 16) & 0xff;
  9001. here_val = here & 0xffff;
  9002. if ((here_bits) <= bits) { break; }
  9003. //--- PULLBYTE() ---//
  9004. if (have === 0) { break inf_leave; }
  9005. have--;
  9006. hold += input[next++] << bits;
  9007. bits += 8;
  9008. //---//
  9009. }
  9010. if ((here_op & 0xf0) === 0) {
  9011. last_bits = here_bits;
  9012. last_op = here_op;
  9013. last_val = here_val;
  9014. for (;;) {
  9015. here = state.distcode[last_val +
  9016. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9017. here_bits = here >>> 24;
  9018. here_op = (here >>> 16) & 0xff;
  9019. here_val = here & 0xffff;
  9020. if ((last_bits + here_bits) <= bits) { break; }
  9021. //--- PULLBYTE() ---//
  9022. if (have === 0) { break inf_leave; }
  9023. have--;
  9024. hold += input[next++] << bits;
  9025. bits += 8;
  9026. //---//
  9027. }
  9028. //--- DROPBITS(last.bits) ---//
  9029. hold >>>= last_bits;
  9030. bits -= last_bits;
  9031. //---//
  9032. state.back += last_bits;
  9033. }
  9034. //--- DROPBITS(here.bits) ---//
  9035. hold >>>= here_bits;
  9036. bits -= here_bits;
  9037. //---//
  9038. state.back += here_bits;
  9039. if (here_op & 64) {
  9040. strm.msg = 'invalid distance code';
  9041. state.mode = BAD;
  9042. break;
  9043. }
  9044. state.offset = here_val;
  9045. state.extra = (here_op) & 15;
  9046. state.mode = DISTEXT;
  9047. /* falls through */
  9048. case DISTEXT:
  9049. if (state.extra) {
  9050. //=== NEEDBITS(state.extra);
  9051. n = state.extra;
  9052. while (bits < n) {
  9053. if (have === 0) { break inf_leave; }
  9054. have--;
  9055. hold += input[next++] << bits;
  9056. bits += 8;
  9057. }
  9058. //===//
  9059. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9060. //--- DROPBITS(state.extra) ---//
  9061. hold >>>= state.extra;
  9062. bits -= state.extra;
  9063. //---//
  9064. state.back += state.extra;
  9065. }
  9066. //#ifdef INFLATE_STRICT
  9067. if (state.offset > state.dmax) {
  9068. strm.msg = 'invalid distance too far back';
  9069. state.mode = BAD;
  9070. break;
  9071. }
  9072. //#endif
  9073. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  9074. state.mode = MATCH;
  9075. /* falls through */
  9076. case MATCH:
  9077. if (left === 0) { break inf_leave; }
  9078. copy = _out - left;
  9079. if (state.offset > copy) { /* copy from window */
  9080. copy = state.offset - copy;
  9081. if (copy > state.whave) {
  9082. if (state.sane) {
  9083. strm.msg = 'invalid distance too far back';
  9084. state.mode = BAD;
  9085. break;
  9086. }
  9087. // (!) This block is disabled in zlib defailts,
  9088. // don't enable it for binary compatibility
  9089. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9090. // Trace((stderr, "inflate.c too far\n"));
  9091. // copy -= state.whave;
  9092. // if (copy > state.length) { copy = state.length; }
  9093. // if (copy > left) { copy = left; }
  9094. // left -= copy;
  9095. // state.length -= copy;
  9096. // do {
  9097. // output[put++] = 0;
  9098. // } while (--copy);
  9099. // if (state.length === 0) { state.mode = LEN; }
  9100. // break;
  9101. //#endif
  9102. }
  9103. if (copy > state.wnext) {
  9104. copy -= state.wnext;
  9105. from = state.wsize - copy;
  9106. }
  9107. else {
  9108. from = state.wnext - copy;
  9109. }
  9110. if (copy > state.length) { copy = state.length; }
  9111. from_source = state.window;
  9112. }
  9113. else { /* copy from output */
  9114. from_source = output;
  9115. from = put - state.offset;
  9116. copy = state.length;
  9117. }
  9118. if (copy > left) { copy = left; }
  9119. left -= copy;
  9120. state.length -= copy;
  9121. do {
  9122. output[put++] = from_source[from++];
  9123. } while (--copy);
  9124. if (state.length === 0) { state.mode = LEN; }
  9125. break;
  9126. case LIT:
  9127. if (left === 0) { break inf_leave; }
  9128. output[put++] = state.length;
  9129. left--;
  9130. state.mode = LEN;
  9131. break;
  9132. case CHECK:
  9133. if (state.wrap) {
  9134. //=== NEEDBITS(32);
  9135. while (bits < 32) {
  9136. if (have === 0) { break inf_leave; }
  9137. have--;
  9138. // Use '|' insdead of '+' to make sure that result is signed
  9139. hold |= input[next++] << bits;
  9140. bits += 8;
  9141. }
  9142. //===//
  9143. _out -= left;
  9144. strm.total_out += _out;
  9145. state.total += _out;
  9146. if (_out) {
  9147. strm.adler = state.check =
  9148. /*UPDATE(state.check, put - _out, _out);*/
  9149. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  9150. }
  9151. _out = left;
  9152. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  9153. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  9154. strm.msg = 'incorrect data check';
  9155. state.mode = BAD;
  9156. break;
  9157. }
  9158. //=== INITBITS();
  9159. hold = 0;
  9160. bits = 0;
  9161. //===//
  9162. //Tracev((stderr, "inflate: check matches trailer\n"));
  9163. }
  9164. state.mode = LENGTH;
  9165. /* falls through */
  9166. case LENGTH:
  9167. if (state.wrap && state.flags) {
  9168. //=== NEEDBITS(32);
  9169. while (bits < 32) {
  9170. if (have === 0) { break inf_leave; }
  9171. have--;
  9172. hold += input[next++] << bits;
  9173. bits += 8;
  9174. }
  9175. //===//
  9176. if (hold !== (state.total & 0xffffffff)) {
  9177. strm.msg = 'incorrect length check';
  9178. state.mode = BAD;
  9179. break;
  9180. }
  9181. //=== INITBITS();
  9182. hold = 0;
  9183. bits = 0;
  9184. //===//
  9185. //Tracev((stderr, "inflate: length matches trailer\n"));
  9186. }
  9187. state.mode = DONE;
  9188. /* falls through */
  9189. case DONE:
  9190. ret = Z_STREAM_END;
  9191. break inf_leave;
  9192. case BAD:
  9193. ret = Z_DATA_ERROR;
  9194. break inf_leave;
  9195. case MEM:
  9196. return Z_MEM_ERROR;
  9197. case SYNC:
  9198. /* falls through */
  9199. default:
  9200. return Z_STREAM_ERROR;
  9201. }
  9202. }
  9203. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  9204. /*
  9205. Return from inflate(), updating the total counts and the check value.
  9206. If there was no progress during the inflate() call, return a buffer
  9207. error. Call updatewindow() to create and/or update the window state.
  9208. Note: a memory error from inflate() is non-recoverable.
  9209. */
  9210. //--- RESTORE() ---
  9211. strm.next_out = put;
  9212. strm.avail_out = left;
  9213. strm.next_in = next;
  9214. strm.avail_in = have;
  9215. state.hold = hold;
  9216. state.bits = bits;
  9217. //---
  9218. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  9219. (state.mode < CHECK || flush !== Z_FINISH))) {
  9220. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  9221. state.mode = MEM;
  9222. return Z_MEM_ERROR;
  9223. }
  9224. }
  9225. _in -= strm.avail_in;
  9226. _out -= strm.avail_out;
  9227. strm.total_in += _in;
  9228. strm.total_out += _out;
  9229. state.total += _out;
  9230. if (state.wrap && _out) {
  9231. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  9232. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  9233. }
  9234. strm.data_type = state.bits + (state.last ? 64 : 0) +
  9235. (state.mode === TYPE ? 128 : 0) +
  9236. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  9237. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  9238. ret = Z_BUF_ERROR;
  9239. }
  9240. return ret;
  9241. }
  9242. function inflateEnd(strm) {
  9243. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  9244. return Z_STREAM_ERROR;
  9245. }
  9246. var state = strm.state;
  9247. if (state.window) {
  9248. state.window = null;
  9249. }
  9250. strm.state = null;
  9251. return Z_OK;
  9252. }
  9253. function inflateGetHeader(strm, head) {
  9254. var state;
  9255. /* check state */
  9256. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9257. state = strm.state;
  9258. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  9259. /* save header structure */
  9260. state.head = head;
  9261. head.done = false;
  9262. return Z_OK;
  9263. }
  9264. function inflateSetDictionary(strm, dictionary) {
  9265. var dictLength = dictionary.length;
  9266. var state;
  9267. var dictid;
  9268. var ret;
  9269. /* check state */
  9270. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  9271. state = strm.state;
  9272. if (state.wrap !== 0 && state.mode !== DICT) {
  9273. return Z_STREAM_ERROR;
  9274. }
  9275. /* check for correct dictionary identifier */
  9276. if (state.mode === DICT) {
  9277. dictid = 1; /* adler32(0, null, 0)*/
  9278. /* dictid = adler32(dictid, dictionary, dictLength); */
  9279. dictid = adler32(dictid, dictionary, dictLength, 0);
  9280. if (dictid !== state.check) {
  9281. return Z_DATA_ERROR;
  9282. }
  9283. }
  9284. /* copy dictionary to window using updatewindow(), which will amend the
  9285. existing dictionary if appropriate */
  9286. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  9287. if (ret) {
  9288. state.mode = MEM;
  9289. return Z_MEM_ERROR;
  9290. }
  9291. state.havedict = 1;
  9292. // Tracev((stderr, "inflate: dictionary set\n"));
  9293. return Z_OK;
  9294. }
  9295. exports.inflateReset = inflateReset;
  9296. exports.inflateReset2 = inflateReset2;
  9297. exports.inflateResetKeep = inflateResetKeep;
  9298. exports.inflateInit = inflateInit;
  9299. exports.inflateInit2 = inflateInit2;
  9300. exports.inflate = inflate;
  9301. exports.inflateEnd = inflateEnd;
  9302. exports.inflateGetHeader = inflateGetHeader;
  9303. exports.inflateSetDictionary = inflateSetDictionary;
  9304. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  9305. /* Not implemented
  9306. exports.inflateCopy = inflateCopy;
  9307. exports.inflateGetDictionary = inflateGetDictionary;
  9308. exports.inflateMark = inflateMark;
  9309. exports.inflatePrime = inflatePrime;
  9310. exports.inflateSync = inflateSync;
  9311. exports.inflateSyncPoint = inflateSyncPoint;
  9312. exports.inflateUndermine = inflateUndermine;
  9313. */
  9314. },{"../utils/common":32,"./adler32":34,"./crc32":36,"./inffast":39,"./inftrees":41}],41:[function(_dereq_,module,exports){
  9315. 'use strict';
  9316. var utils = _dereq_('../utils/common');
  9317. var MAXBITS = 15;
  9318. var ENOUGH_LENS = 852;
  9319. var ENOUGH_DISTS = 592;
  9320. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  9321. var CODES = 0;
  9322. var LENS = 1;
  9323. var DISTS = 2;
  9324. var lbase = [ /* Length codes 257..285 base */
  9325. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  9326. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  9327. ];
  9328. var lext = [ /* Length codes 257..285 extra */
  9329. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  9330. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  9331. ];
  9332. var dbase = [ /* Distance codes 0..29 base */
  9333. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  9334. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  9335. 8193, 12289, 16385, 24577, 0, 0
  9336. ];
  9337. var dext = [ /* Distance codes 0..29 extra */
  9338. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  9339. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  9340. 28, 28, 29, 29, 64, 64
  9341. ];
  9342. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  9343. {
  9344. var bits = opts.bits;
  9345. //here = opts.here; /* table entry for duplication */
  9346. var len = 0; /* a code's length in bits */
  9347. var sym = 0; /* index of code symbols */
  9348. var min = 0, max = 0; /* minimum and maximum code lengths */
  9349. var root = 0; /* number of index bits for root table */
  9350. var curr = 0; /* number of index bits for current table */
  9351. var drop = 0; /* code bits to drop for sub-table */
  9352. var left = 0; /* number of prefix codes available */
  9353. var used = 0; /* code entries in table used */
  9354. var huff = 0; /* Huffman code */
  9355. var incr; /* for incrementing code, index */
  9356. var fill; /* index for replicating entries */
  9357. var low; /* low bits for current root entry */
  9358. var mask; /* mask for low root bits */
  9359. var next; /* next available space in table */
  9360. var base = null; /* base value table to use */
  9361. var base_index = 0;
  9362. // var shoextra; /* extra bits table to use */
  9363. var end; /* use base and extra for symbol > end */
  9364. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  9365. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  9366. var extra = null;
  9367. var extra_index = 0;
  9368. var here_bits, here_op, here_val;
  9369. /*
  9370. Process a set of code lengths to create a canonical Huffman code. The
  9371. code lengths are lens[0..codes-1]. Each length corresponds to the
  9372. symbols 0..codes-1. The Huffman code is generated by first sorting the
  9373. symbols by length from short to long, and retaining the symbol order
  9374. for codes with equal lengths. Then the code starts with all zero bits
  9375. for the first code of the shortest length, and the codes are integer
  9376. increments for the same length, and zeros are appended as the length
  9377. increases. For the deflate format, these bits are stored backwards
  9378. from their more natural integer increment ordering, and so when the
  9379. decoding tables are built in the large loop below, the integer codes
  9380. are incremented backwards.
  9381. This routine assumes, but does not check, that all of the entries in
  9382. lens[] are in the range 0..MAXBITS. The caller must assure this.
  9383. 1..MAXBITS is interpreted as that code length. zero means that that
  9384. symbol does not occur in this code.
  9385. The codes are sorted by computing a count of codes for each length,
  9386. creating from that a table of starting indices for each length in the
  9387. sorted table, and then entering the symbols in order in the sorted
  9388. table. The sorted table is work[], with that space being provided by
  9389. the caller.
  9390. The length counts are used for other purposes as well, i.e. finding
  9391. the minimum and maximum length codes, determining if there are any
  9392. codes at all, checking for a valid set of lengths, and looking ahead
  9393. at length counts to determine sub-table sizes when building the
  9394. decoding tables.
  9395. */
  9396. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  9397. for (len = 0; len <= MAXBITS; len++) {
  9398. count[len] = 0;
  9399. }
  9400. for (sym = 0; sym < codes; sym++) {
  9401. count[lens[lens_index + sym]]++;
  9402. }
  9403. /* bound code lengths, force root to be within code lengths */
  9404. root = bits;
  9405. for (max = MAXBITS; max >= 1; max--) {
  9406. if (count[max] !== 0) { break; }
  9407. }
  9408. if (root > max) {
  9409. root = max;
  9410. }
  9411. if (max === 0) { /* no symbols to code at all */
  9412. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  9413. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  9414. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  9415. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9416. //table.op[opts.table_index] = 64;
  9417. //table.bits[opts.table_index] = 1;
  9418. //table.val[opts.table_index++] = 0;
  9419. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9420. opts.bits = 1;
  9421. return 0; /* no symbols, but wait for decoding to report error */
  9422. }
  9423. for (min = 1; min < max; min++) {
  9424. if (count[min] !== 0) { break; }
  9425. }
  9426. if (root < min) {
  9427. root = min;
  9428. }
  9429. /* check for an over-subscribed or incomplete set of lengths */
  9430. left = 1;
  9431. for (len = 1; len <= MAXBITS; len++) {
  9432. left <<= 1;
  9433. left -= count[len];
  9434. if (left < 0) {
  9435. return -1;
  9436. } /* over-subscribed */
  9437. }
  9438. if (left > 0 && (type === CODES || max !== 1)) {
  9439. return -1; /* incomplete set */
  9440. }
  9441. /* generate offsets into symbol table for each length for sorting */
  9442. offs[1] = 0;
  9443. for (len = 1; len < MAXBITS; len++) {
  9444. offs[len + 1] = offs[len] + count[len];
  9445. }
  9446. /* sort symbols by length, by symbol order within each length */
  9447. for (sym = 0; sym < codes; sym++) {
  9448. if (lens[lens_index + sym] !== 0) {
  9449. work[offs[lens[lens_index + sym]]++] = sym;
  9450. }
  9451. }
  9452. /*
  9453. Create and fill in decoding tables. In this loop, the table being
  9454. filled is at next and has curr index bits. The code being used is huff
  9455. with length len. That code is converted to an index by dropping drop
  9456. bits off of the bottom. For codes where len is less than drop + curr,
  9457. those top drop + curr - len bits are incremented through all values to
  9458. fill the table with replicated entries.
  9459. root is the number of index bits for the root table. When len exceeds
  9460. root, sub-tables are created pointed to by the root entry with an index
  9461. of the low root bits of huff. This is saved in low to check for when a
  9462. new sub-table should be started. drop is zero when the root table is
  9463. being filled, and drop is root when sub-tables are being filled.
  9464. When a new sub-table is needed, it is necessary to look ahead in the
  9465. code lengths to determine what size sub-table is needed. The length
  9466. counts are used for this, and so count[] is decremented as codes are
  9467. entered in the tables.
  9468. used keeps track of how many table entries have been allocated from the
  9469. provided *table space. It is checked for LENS and DIST tables against
  9470. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  9471. the initial root table size constants. See the comments in inftrees.h
  9472. for more information.
  9473. sym increments through all symbols, and the loop terminates when
  9474. all codes of length max, i.e. all codes, have been processed. This
  9475. routine permits incomplete codes, so another loop after this one fills
  9476. in the rest of the decoding tables with invalid code markers.
  9477. */
  9478. /* set up for code type */
  9479. // poor man optimization - use if-else instead of switch,
  9480. // to avoid deopts in old v8
  9481. if (type === CODES) {
  9482. base = extra = work; /* dummy value--not used */
  9483. end = 19;
  9484. } else if (type === LENS) {
  9485. base = lbase;
  9486. base_index -= 257;
  9487. extra = lext;
  9488. extra_index -= 257;
  9489. end = 256;
  9490. } else { /* DISTS */
  9491. base = dbase;
  9492. extra = dext;
  9493. end = -1;
  9494. }
  9495. /* initialize opts for loop */
  9496. huff = 0; /* starting code */
  9497. sym = 0; /* starting code symbol */
  9498. len = min; /* starting code length */
  9499. next = table_index; /* current table to fill in */
  9500. curr = root; /* current table index bits */
  9501. drop = 0; /* current bits to drop from code for index */
  9502. low = -1; /* trigger new sub-table when len > root */
  9503. used = 1 << root; /* use root table entries */
  9504. mask = used - 1; /* mask for comparing low */
  9505. /* check available table space */
  9506. if ((type === LENS && used > ENOUGH_LENS) ||
  9507. (type === DISTS && used > ENOUGH_DISTS)) {
  9508. return 1;
  9509. }
  9510. var i = 0;
  9511. /* process all codes and make table entries */
  9512. for (;;) {
  9513. i++;
  9514. /* create table entry */
  9515. here_bits = len - drop;
  9516. if (work[sym] < end) {
  9517. here_op = 0;
  9518. here_val = work[sym];
  9519. }
  9520. else if (work[sym] > end) {
  9521. here_op = extra[extra_index + work[sym]];
  9522. here_val = base[base_index + work[sym]];
  9523. }
  9524. else {
  9525. here_op = 32 + 64; /* end of block */
  9526. here_val = 0;
  9527. }
  9528. /* replicate for those indices with low len bits equal to huff */
  9529. incr = 1 << (len - drop);
  9530. fill = 1 << curr;
  9531. min = fill; /* save offset to next table */
  9532. do {
  9533. fill -= incr;
  9534. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  9535. } while (fill !== 0);
  9536. /* backwards increment the len-bit code huff */
  9537. incr = 1 << (len - 1);
  9538. while (huff & incr) {
  9539. incr >>= 1;
  9540. }
  9541. if (incr !== 0) {
  9542. huff &= incr - 1;
  9543. huff += incr;
  9544. } else {
  9545. huff = 0;
  9546. }
  9547. /* go to next symbol, update count, len */
  9548. sym++;
  9549. if (--count[len] === 0) {
  9550. if (len === max) { break; }
  9551. len = lens[lens_index + work[sym]];
  9552. }
  9553. /* create new sub-table if needed */
  9554. if (len > root && (huff & mask) !== low) {
  9555. /* if first time, transition to sub-tables */
  9556. if (drop === 0) {
  9557. drop = root;
  9558. }
  9559. /* increment past last table */
  9560. next += min; /* here min is 1 << curr */
  9561. /* determine length of next table */
  9562. curr = len - drop;
  9563. left = 1 << curr;
  9564. while (curr + drop < max) {
  9565. left -= count[curr + drop];
  9566. if (left <= 0) { break; }
  9567. curr++;
  9568. left <<= 1;
  9569. }
  9570. /* check for enough space */
  9571. used += 1 << curr;
  9572. if ((type === LENS && used > ENOUGH_LENS) ||
  9573. (type === DISTS && used > ENOUGH_DISTS)) {
  9574. return 1;
  9575. }
  9576. /* point entry in root table to sub-table */
  9577. low = huff & mask;
  9578. /*table.op[low] = curr;
  9579. table.bits[low] = root;
  9580. table.val[low] = next - opts.table_index;*/
  9581. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  9582. }
  9583. }
  9584. /* fill in remaining table entry if code is incomplete (guaranteed to have
  9585. at most one remaining entry, since if the code is incomplete, the
  9586. maximum code length that was allowed to get this far is one bit) */
  9587. if (huff !== 0) {
  9588. //table.op[next + huff] = 64; /* invalid code marker */
  9589. //table.bits[next + huff] = len - drop;
  9590. //table.val[next + huff] = 0;
  9591. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  9592. }
  9593. /* set return parameters */
  9594. //opts.table_index += used;
  9595. opts.bits = root;
  9596. return 0;
  9597. };
  9598. },{"../utils/common":32}],42:[function(_dereq_,module,exports){
  9599. 'use strict';
  9600. module.exports = {
  9601. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  9602. 1: 'stream end', /* Z_STREAM_END 1 */
  9603. 0: '', /* Z_OK 0 */
  9604. '-1': 'file error', /* Z_ERRNO (-1) */
  9605. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  9606. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  9607. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  9608. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  9609. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  9610. };
  9611. },{}],43:[function(_dereq_,module,exports){
  9612. 'use strict';
  9613. var utils = _dereq_('../utils/common');
  9614. /* Public constants ==========================================================*/
  9615. /* ===========================================================================*/
  9616. //var Z_FILTERED = 1;
  9617. //var Z_HUFFMAN_ONLY = 2;
  9618. //var Z_RLE = 3;
  9619. var Z_FIXED = 4;
  9620. //var Z_DEFAULT_STRATEGY = 0;
  9621. /* Possible values of the data_type field (though see inflate()) */
  9622. var Z_BINARY = 0;
  9623. var Z_TEXT = 1;
  9624. //var Z_ASCII = 1; // = Z_TEXT
  9625. var Z_UNKNOWN = 2;
  9626. /*============================================================================*/
  9627. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  9628. // From zutil.h
  9629. var STORED_BLOCK = 0;
  9630. var STATIC_TREES = 1;
  9631. var DYN_TREES = 2;
  9632. /* The three kinds of block type */
  9633. var MIN_MATCH = 3;
  9634. var MAX_MATCH = 258;
  9635. /* The minimum and maximum match lengths */
  9636. // From deflate.h
  9637. /* ===========================================================================
  9638. * Internal compression state.
  9639. */
  9640. var LENGTH_CODES = 29;
  9641. /* number of length codes, not counting the special END_BLOCK code */
  9642. var LITERALS = 256;
  9643. /* number of literal bytes 0..255 */
  9644. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  9645. /* number of Literal or Length codes, including the END_BLOCK code */
  9646. var D_CODES = 30;
  9647. /* number of distance codes */
  9648. var BL_CODES = 19;
  9649. /* number of codes used to transfer the bit lengths */
  9650. var HEAP_SIZE = 2 * L_CODES + 1;
  9651. /* maximum heap size */
  9652. var MAX_BITS = 15;
  9653. /* All codes must not exceed MAX_BITS bits */
  9654. var Buf_size = 16;
  9655. /* size of bit buffer in bi_buf */
  9656. /* ===========================================================================
  9657. * Constants
  9658. */
  9659. var MAX_BL_BITS = 7;
  9660. /* Bit length codes must not exceed MAX_BL_BITS bits */
  9661. var END_BLOCK = 256;
  9662. /* end of block literal code */
  9663. var REP_3_6 = 16;
  9664. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  9665. var REPZ_3_10 = 17;
  9666. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  9667. var REPZ_11_138 = 18;
  9668. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  9669. /* eslint-disable comma-spacing,array-bracket-spacing */
  9670. var extra_lbits = /* extra bits for each length code */
  9671. [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];
  9672. var extra_dbits = /* extra bits for each distance code */
  9673. [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];
  9674. var extra_blbits = /* extra bits for each bit length code */
  9675. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  9676. var bl_order =
  9677. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  9678. /* eslint-enable comma-spacing,array-bracket-spacing */
  9679. /* The lengths of the bit length codes are sent in order of decreasing
  9680. * probability, to avoid transmitting the lengths for unused bit length codes.
  9681. */
  9682. /* ===========================================================================
  9683. * Local data. These are initialized only once.
  9684. */
  9685. // We pre-fill arrays with 0 to avoid uninitialized gaps
  9686. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  9687. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  9688. var static_ltree = new Array((L_CODES + 2) * 2);
  9689. zero(static_ltree);
  9690. /* The static literal tree. Since the bit lengths are imposed, there is no
  9691. * need for the L_CODES extra codes used during heap construction. However
  9692. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  9693. * below).
  9694. */
  9695. var static_dtree = new Array(D_CODES * 2);
  9696. zero(static_dtree);
  9697. /* The static distance tree. (Actually a trivial tree since all codes use
  9698. * 5 bits.)
  9699. */
  9700. var _dist_code = new Array(DIST_CODE_LEN);
  9701. zero(_dist_code);
  9702. /* Distance codes. The first 256 values correspond to the distances
  9703. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  9704. * the 15 bit distances.
  9705. */
  9706. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  9707. zero(_length_code);
  9708. /* length code for each normalized match length (0 == MIN_MATCH) */
  9709. var base_length = new Array(LENGTH_CODES);
  9710. zero(base_length);
  9711. /* First normalized length for each code (0 = MIN_MATCH) */
  9712. var base_dist = new Array(D_CODES);
  9713. zero(base_dist);
  9714. /* First normalized distance for each code (0 = distance of 1) */
  9715. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  9716. this.static_tree = static_tree; /* static tree or NULL */
  9717. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  9718. this.extra_base = extra_base; /* base index for extra_bits */
  9719. this.elems = elems; /* max number of elements in the tree */
  9720. this.max_length = max_length; /* max bit length for the codes */
  9721. // show if `static_tree` has data or dummy - needed for monomorphic objects
  9722. this.has_stree = static_tree && static_tree.length;
  9723. }
  9724. var static_l_desc;
  9725. var static_d_desc;
  9726. var static_bl_desc;
  9727. function TreeDesc(dyn_tree, stat_desc) {
  9728. this.dyn_tree = dyn_tree; /* the dynamic tree */
  9729. this.max_code = 0; /* largest code with non zero frequency */
  9730. this.stat_desc = stat_desc; /* the corresponding static tree */
  9731. }
  9732. function d_code(dist) {
  9733. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  9734. }
  9735. /* ===========================================================================
  9736. * Output a short LSB first on the stream.
  9737. * IN assertion: there is enough room in pendingBuf.
  9738. */
  9739. function put_short(s, w) {
  9740. // put_byte(s, (uch)((w) & 0xff));
  9741. // put_byte(s, (uch)((ush)(w) >> 8));
  9742. s.pending_buf[s.pending++] = (w) & 0xff;
  9743. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  9744. }
  9745. /* ===========================================================================
  9746. * Send a value on a given number of bits.
  9747. * IN assertion: length <= 16 and value fits in length bits.
  9748. */
  9749. function send_bits(s, value, length) {
  9750. if (s.bi_valid > (Buf_size - length)) {
  9751. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  9752. put_short(s, s.bi_buf);
  9753. s.bi_buf = value >> (Buf_size - s.bi_valid);
  9754. s.bi_valid += length - Buf_size;
  9755. } else {
  9756. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  9757. s.bi_valid += length;
  9758. }
  9759. }
  9760. function send_code(s, c, tree) {
  9761. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  9762. }
  9763. /* ===========================================================================
  9764. * Reverse the first len bits of a code, using straightforward code (a faster
  9765. * method would use a table)
  9766. * IN assertion: 1 <= len <= 15
  9767. */
  9768. function bi_reverse(code, len) {
  9769. var res = 0;
  9770. do {
  9771. res |= code & 1;
  9772. code >>>= 1;
  9773. res <<= 1;
  9774. } while (--len > 0);
  9775. return res >>> 1;
  9776. }
  9777. /* ===========================================================================
  9778. * Flush the bit buffer, keeping at most 7 bits in it.
  9779. */
  9780. function bi_flush(s) {
  9781. if (s.bi_valid === 16) {
  9782. put_short(s, s.bi_buf);
  9783. s.bi_buf = 0;
  9784. s.bi_valid = 0;
  9785. } else if (s.bi_valid >= 8) {
  9786. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  9787. s.bi_buf >>= 8;
  9788. s.bi_valid -= 8;
  9789. }
  9790. }
  9791. /* ===========================================================================
  9792. * Compute the optimal bit lengths for a tree and update the total bit length
  9793. * for the current block.
  9794. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  9795. * above are the tree nodes sorted by increasing frequency.
  9796. * OUT assertions: the field len is set to the optimal bit length, the
  9797. * array bl_count contains the frequencies for each bit length.
  9798. * The length opt_len is updated; static_len is also updated if stree is
  9799. * not null.
  9800. */
  9801. function gen_bitlen(s, desc)
  9802. // deflate_state *s;
  9803. // tree_desc *desc; /* the tree descriptor */
  9804. {
  9805. var tree = desc.dyn_tree;
  9806. var max_code = desc.max_code;
  9807. var stree = desc.stat_desc.static_tree;
  9808. var has_stree = desc.stat_desc.has_stree;
  9809. var extra = desc.stat_desc.extra_bits;
  9810. var base = desc.stat_desc.extra_base;
  9811. var max_length = desc.stat_desc.max_length;
  9812. var h; /* heap index */
  9813. var n, m; /* iterate over the tree elements */
  9814. var bits; /* bit length */
  9815. var xbits; /* extra bits */
  9816. var f; /* frequency */
  9817. var overflow = 0; /* number of elements with bit length too large */
  9818. for (bits = 0; bits <= MAX_BITS; bits++) {
  9819. s.bl_count[bits] = 0;
  9820. }
  9821. /* In a first pass, compute the optimal bit lengths (which may
  9822. * overflow in the case of the bit length tree).
  9823. */
  9824. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  9825. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  9826. n = s.heap[h];
  9827. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  9828. if (bits > max_length) {
  9829. bits = max_length;
  9830. overflow++;
  9831. }
  9832. tree[n * 2 + 1]/*.Len*/ = bits;
  9833. /* We overwrite tree[n].Dad which is no longer needed */
  9834. if (n > max_code) { continue; } /* not a leaf node */
  9835. s.bl_count[bits]++;
  9836. xbits = 0;
  9837. if (n >= base) {
  9838. xbits = extra[n - base];
  9839. }
  9840. f = tree[n * 2]/*.Freq*/;
  9841. s.opt_len += f * (bits + xbits);
  9842. if (has_stree) {
  9843. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  9844. }
  9845. }
  9846. if (overflow === 0) { return; }
  9847. // Trace((stderr,"\nbit length overflow\n"));
  9848. /* This happens for example on obj2 and pic of the Calgary corpus */
  9849. /* Find the first bit length which could increase: */
  9850. do {
  9851. bits = max_length - 1;
  9852. while (s.bl_count[bits] === 0) { bits--; }
  9853. s.bl_count[bits]--; /* move one leaf down the tree */
  9854. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  9855. s.bl_count[max_length]--;
  9856. /* The brother of the overflow item also moves one step up,
  9857. * but this does not affect bl_count[max_length]
  9858. */
  9859. overflow -= 2;
  9860. } while (overflow > 0);
  9861. /* Now recompute all bit lengths, scanning in increasing frequency.
  9862. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  9863. * lengths instead of fixing only the wrong ones. This idea is taken
  9864. * from 'ar' written by Haruhiko Okumura.)
  9865. */
  9866. for (bits = max_length; bits !== 0; bits--) {
  9867. n = s.bl_count[bits];
  9868. while (n !== 0) {
  9869. m = s.heap[--h];
  9870. if (m > max_code) { continue; }
  9871. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  9872. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  9873. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  9874. tree[m * 2 + 1]/*.Len*/ = bits;
  9875. }
  9876. n--;
  9877. }
  9878. }
  9879. }
  9880. /* ===========================================================================
  9881. * Generate the codes for a given tree and bit counts (which need not be
  9882. * optimal).
  9883. * IN assertion: the array bl_count contains the bit length statistics for
  9884. * the given tree and the field len is set for all tree elements.
  9885. * OUT assertion: the field code is set for all tree elements of non
  9886. * zero code length.
  9887. */
  9888. function gen_codes(tree, max_code, bl_count)
  9889. // ct_data *tree; /* the tree to decorate */
  9890. // int max_code; /* largest code with non zero frequency */
  9891. // ushf *bl_count; /* number of codes at each bit length */
  9892. {
  9893. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  9894. var code = 0; /* running code value */
  9895. var bits; /* bit index */
  9896. var n; /* code index */
  9897. /* The distribution counts are first used to generate the code values
  9898. * without bit reversal.
  9899. */
  9900. for (bits = 1; bits <= MAX_BITS; bits++) {
  9901. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  9902. }
  9903. /* Check that the bit counts in bl_count are consistent. The last code
  9904. * must be all ones.
  9905. */
  9906. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  9907. // "inconsistent bit counts");
  9908. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  9909. for (n = 0; n <= max_code; n++) {
  9910. var len = tree[n * 2 + 1]/*.Len*/;
  9911. if (len === 0) { continue; }
  9912. /* Now reverse the bits */
  9913. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  9914. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  9915. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  9916. }
  9917. }
  9918. /* ===========================================================================
  9919. * Initialize the various 'constant' tables.
  9920. */
  9921. function tr_static_init() {
  9922. var n; /* iterates over tree elements */
  9923. var bits; /* bit counter */
  9924. var length; /* length value */
  9925. var code; /* code value */
  9926. var dist; /* distance index */
  9927. var bl_count = new Array(MAX_BITS + 1);
  9928. /* number of codes at each bit length for an optimal tree */
  9929. // do check in _tr_init()
  9930. //if (static_init_done) return;
  9931. /* For some embedded targets, global variables are not initialized: */
  9932. /*#ifdef NO_INIT_GLOBAL_POINTERS
  9933. static_l_desc.static_tree = static_ltree;
  9934. static_l_desc.extra_bits = extra_lbits;
  9935. static_d_desc.static_tree = static_dtree;
  9936. static_d_desc.extra_bits = extra_dbits;
  9937. static_bl_desc.extra_bits = extra_blbits;
  9938. #endif*/
  9939. /* Initialize the mapping length (0..255) -> length code (0..28) */
  9940. length = 0;
  9941. for (code = 0; code < LENGTH_CODES - 1; code++) {
  9942. base_length[code] = length;
  9943. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  9944. _length_code[length++] = code;
  9945. }
  9946. }
  9947. //Assert (length == 256, "tr_static_init: length != 256");
  9948. /* Note that the length 255 (match length 258) can be represented
  9949. * in two different ways: code 284 + 5 bits or code 285, so we
  9950. * overwrite length_code[255] to use the best encoding:
  9951. */
  9952. _length_code[length - 1] = code;
  9953. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  9954. dist = 0;
  9955. for (code = 0; code < 16; code++) {
  9956. base_dist[code] = dist;
  9957. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  9958. _dist_code[dist++] = code;
  9959. }
  9960. }
  9961. //Assert (dist == 256, "tr_static_init: dist != 256");
  9962. dist >>= 7; /* from now on, all distances are divided by 128 */
  9963. for (; code < D_CODES; code++) {
  9964. base_dist[code] = dist << 7;
  9965. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  9966. _dist_code[256 + dist++] = code;
  9967. }
  9968. }
  9969. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  9970. /* Construct the codes of the static literal tree */
  9971. for (bits = 0; bits <= MAX_BITS; bits++) {
  9972. bl_count[bits] = 0;
  9973. }
  9974. n = 0;
  9975. while (n <= 143) {
  9976. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  9977. n++;
  9978. bl_count[8]++;
  9979. }
  9980. while (n <= 255) {
  9981. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  9982. n++;
  9983. bl_count[9]++;
  9984. }
  9985. while (n <= 279) {
  9986. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  9987. n++;
  9988. bl_count[7]++;
  9989. }
  9990. while (n <= 287) {
  9991. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  9992. n++;
  9993. bl_count[8]++;
  9994. }
  9995. /* Codes 286 and 287 do not exist, but we must include them in the
  9996. * tree construction to get a canonical Huffman tree (longest code
  9997. * all ones)
  9998. */
  9999. gen_codes(static_ltree, L_CODES + 1, bl_count);
  10000. /* The static distance tree is trivial: */
  10001. for (n = 0; n < D_CODES; n++) {
  10002. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  10003. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  10004. }
  10005. // Now data ready and we can init static trees
  10006. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  10007. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  10008. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  10009. //static_init_done = true;
  10010. }
  10011. /* ===========================================================================
  10012. * Initialize a new block.
  10013. */
  10014. function init_block(s) {
  10015. var n; /* iterates over tree elements */
  10016. /* Initialize the trees. */
  10017. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  10018. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  10019. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  10020. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  10021. s.opt_len = s.static_len = 0;
  10022. s.last_lit = s.matches = 0;
  10023. }
  10024. /* ===========================================================================
  10025. * Flush the bit buffer and align the output on a byte boundary
  10026. */
  10027. function bi_windup(s)
  10028. {
  10029. if (s.bi_valid > 8) {
  10030. put_short(s, s.bi_buf);
  10031. } else if (s.bi_valid > 0) {
  10032. //put_byte(s, (Byte)s->bi_buf);
  10033. s.pending_buf[s.pending++] = s.bi_buf;
  10034. }
  10035. s.bi_buf = 0;
  10036. s.bi_valid = 0;
  10037. }
  10038. /* ===========================================================================
  10039. * Copy a stored block, storing first the length and its
  10040. * one's complement if requested.
  10041. */
  10042. function copy_block(s, buf, len, header)
  10043. //DeflateState *s;
  10044. //charf *buf; /* the input data */
  10045. //unsigned len; /* its length */
  10046. //int header; /* true if block header must be written */
  10047. {
  10048. bi_windup(s); /* align on byte boundary */
  10049. if (header) {
  10050. put_short(s, len);
  10051. put_short(s, ~len);
  10052. }
  10053. // while (len--) {
  10054. // put_byte(s, *buf++);
  10055. // }
  10056. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  10057. s.pending += len;
  10058. }
  10059. /* ===========================================================================
  10060. * Compares to subtrees, using the tree depth as tie breaker when
  10061. * the subtrees have equal frequency. This minimizes the worst case length.
  10062. */
  10063. function smaller(tree, n, m, depth) {
  10064. var _n2 = n * 2;
  10065. var _m2 = m * 2;
  10066. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  10067. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  10068. }
  10069. /* ===========================================================================
  10070. * Restore the heap property by moving down the tree starting at node k,
  10071. * exchanging a node with the smallest of its two sons if necessary, stopping
  10072. * when the heap property is re-established (each father smaller than its
  10073. * two sons).
  10074. */
  10075. function pqdownheap(s, tree, k)
  10076. // deflate_state *s;
  10077. // ct_data *tree; /* the tree to restore */
  10078. // int k; /* node to move down */
  10079. {
  10080. var v = s.heap[k];
  10081. var j = k << 1; /* left son of k */
  10082. while (j <= s.heap_len) {
  10083. /* Set j to the smallest of the two sons: */
  10084. if (j < s.heap_len &&
  10085. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  10086. j++;
  10087. }
  10088. /* Exit if v is smaller than both sons */
  10089. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  10090. /* Exchange v with the smallest son */
  10091. s.heap[k] = s.heap[j];
  10092. k = j;
  10093. /* And continue down the tree, setting j to the left son of k */
  10094. j <<= 1;
  10095. }
  10096. s.heap[k] = v;
  10097. }
  10098. // inlined manually
  10099. // var SMALLEST = 1;
  10100. /* ===========================================================================
  10101. * Send the block data compressed using the given Huffman trees
  10102. */
  10103. function compress_block(s, ltree, dtree)
  10104. // deflate_state *s;
  10105. // const ct_data *ltree; /* literal tree */
  10106. // const ct_data *dtree; /* distance tree */
  10107. {
  10108. var dist; /* distance of matched string */
  10109. var lc; /* match length or unmatched char (if dist == 0) */
  10110. var lx = 0; /* running index in l_buf */
  10111. var code; /* the code to send */
  10112. var extra; /* number of extra bits to send */
  10113. if (s.last_lit !== 0) {
  10114. do {
  10115. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  10116. lc = s.pending_buf[s.l_buf + lx];
  10117. lx++;
  10118. if (dist === 0) {
  10119. send_code(s, lc, ltree); /* send a literal byte */
  10120. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  10121. } else {
  10122. /* Here, lc is the match length - MIN_MATCH */
  10123. code = _length_code[lc];
  10124. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  10125. extra = extra_lbits[code];
  10126. if (extra !== 0) {
  10127. lc -= base_length[code];
  10128. send_bits(s, lc, extra); /* send the extra length bits */
  10129. }
  10130. dist--; /* dist is now the match distance - 1 */
  10131. code = d_code(dist);
  10132. //Assert (code < D_CODES, "bad d_code");
  10133. send_code(s, code, dtree); /* send the distance code */
  10134. extra = extra_dbits[code];
  10135. if (extra !== 0) {
  10136. dist -= base_dist[code];
  10137. send_bits(s, dist, extra); /* send the extra distance bits */
  10138. }
  10139. } /* literal or match pair ? */
  10140. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  10141. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  10142. // "pendingBuf overflow");
  10143. } while (lx < s.last_lit);
  10144. }
  10145. send_code(s, END_BLOCK, ltree);
  10146. }
  10147. /* ===========================================================================
  10148. * Construct one Huffman tree and assigns the code bit strings and lengths.
  10149. * Update the total bit length for the current block.
  10150. * IN assertion: the field freq is set for all tree elements.
  10151. * OUT assertions: the fields len and code are set to the optimal bit length
  10152. * and corresponding code. The length opt_len is updated; static_len is
  10153. * also updated if stree is not null. The field max_code is set.
  10154. */
  10155. function build_tree(s, desc)
  10156. // deflate_state *s;
  10157. // tree_desc *desc; /* the tree descriptor */
  10158. {
  10159. var tree = desc.dyn_tree;
  10160. var stree = desc.stat_desc.static_tree;
  10161. var has_stree = desc.stat_desc.has_stree;
  10162. var elems = desc.stat_desc.elems;
  10163. var n, m; /* iterate over heap elements */
  10164. var max_code = -1; /* largest code with non zero frequency */
  10165. var node; /* new node being created */
  10166. /* Construct the initial heap, with least frequent element in
  10167. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  10168. * heap[0] is not used.
  10169. */
  10170. s.heap_len = 0;
  10171. s.heap_max = HEAP_SIZE;
  10172. for (n = 0; n < elems; n++) {
  10173. if (tree[n * 2]/*.Freq*/ !== 0) {
  10174. s.heap[++s.heap_len] = max_code = n;
  10175. s.depth[n] = 0;
  10176. } else {
  10177. tree[n * 2 + 1]/*.Len*/ = 0;
  10178. }
  10179. }
  10180. /* The pkzip format requires that at least one distance code exists,
  10181. * and that at least one bit should be sent even if there is only one
  10182. * possible code. So to avoid special checks later on we force at least
  10183. * two codes of non zero frequency.
  10184. */
  10185. while (s.heap_len < 2) {
  10186. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  10187. tree[node * 2]/*.Freq*/ = 1;
  10188. s.depth[node] = 0;
  10189. s.opt_len--;
  10190. if (has_stree) {
  10191. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  10192. }
  10193. /* node is 0 or 1 so it does not have extra bits */
  10194. }
  10195. desc.max_code = max_code;
  10196. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  10197. * establish sub-heaps of increasing lengths:
  10198. */
  10199. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  10200. /* Construct the Huffman tree by repeatedly combining the least two
  10201. * frequent nodes.
  10202. */
  10203. node = elems; /* next internal node of the tree */
  10204. do {
  10205. //pqremove(s, tree, n); /* n = node of least frequency */
  10206. /*** pqremove ***/
  10207. n = s.heap[1/*SMALLEST*/];
  10208. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  10209. pqdownheap(s, tree, 1/*SMALLEST*/);
  10210. /***/
  10211. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  10212. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  10213. s.heap[--s.heap_max] = m;
  10214. /* Create a new node father of n and m */
  10215. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  10216. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  10217. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  10218. /* and insert the new node in the heap */
  10219. s.heap[1/*SMALLEST*/] = node++;
  10220. pqdownheap(s, tree, 1/*SMALLEST*/);
  10221. } while (s.heap_len >= 2);
  10222. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  10223. /* At this point, the fields freq and dad are set. We can now
  10224. * generate the bit lengths.
  10225. */
  10226. gen_bitlen(s, desc);
  10227. /* The field len is now set, we can generate the bit codes */
  10228. gen_codes(tree, max_code, s.bl_count);
  10229. }
  10230. /* ===========================================================================
  10231. * Scan a literal or distance tree to determine the frequencies of the codes
  10232. * in the bit length tree.
  10233. */
  10234. function scan_tree(s, tree, max_code)
  10235. // deflate_state *s;
  10236. // ct_data *tree; /* the tree to be scanned */
  10237. // int max_code; /* and its largest code of non zero frequency */
  10238. {
  10239. var n; /* iterates over all tree elements */
  10240. var prevlen = -1; /* last emitted length */
  10241. var curlen; /* length of current code */
  10242. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  10243. var count = 0; /* repeat count of the current code */
  10244. var max_count = 7; /* max repeat count */
  10245. var min_count = 4; /* min repeat count */
  10246. if (nextlen === 0) {
  10247. max_count = 138;
  10248. min_count = 3;
  10249. }
  10250. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  10251. for (n = 0; n <= max_code; n++) {
  10252. curlen = nextlen;
  10253. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  10254. if (++count < max_count && curlen === nextlen) {
  10255. continue;
  10256. } else if (count < min_count) {
  10257. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  10258. } else if (curlen !== 0) {
  10259. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  10260. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  10261. } else if (count <= 10) {
  10262. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  10263. } else {
  10264. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  10265. }
  10266. count = 0;
  10267. prevlen = curlen;
  10268. if (nextlen === 0) {
  10269. max_count = 138;
  10270. min_count = 3;
  10271. } else if (curlen === nextlen) {
  10272. max_count = 6;
  10273. min_count = 3;
  10274. } else {
  10275. max_count = 7;
  10276. min_count = 4;
  10277. }
  10278. }
  10279. }
  10280. /* ===========================================================================
  10281. * Send a literal or distance tree in compressed form, using the codes in
  10282. * bl_tree.
  10283. */
  10284. function send_tree(s, tree, max_code)
  10285. // deflate_state *s;
  10286. // ct_data *tree; /* the tree to be scanned */
  10287. // int max_code; /* and its largest code of non zero frequency */
  10288. {
  10289. var n; /* iterates over all tree elements */
  10290. var prevlen = -1; /* last emitted length */
  10291. var curlen; /* length of current code */
  10292. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  10293. var count = 0; /* repeat count of the current code */
  10294. var max_count = 7; /* max repeat count */
  10295. var min_count = 4; /* min repeat count */
  10296. /* tree[max_code+1].Len = -1; */ /* guard already set */
  10297. if (nextlen === 0) {
  10298. max_count = 138;
  10299. min_count = 3;
  10300. }
  10301. for (n = 0; n <= max_code; n++) {
  10302. curlen = nextlen;
  10303. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  10304. if (++count < max_count && curlen === nextlen) {
  10305. continue;
  10306. } else if (count < min_count) {
  10307. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  10308. } else if (curlen !== 0) {
  10309. if (curlen !== prevlen) {
  10310. send_code(s, curlen, s.bl_tree);
  10311. count--;
  10312. }
  10313. //Assert(count >= 3 && count <= 6, " 3_6?");
  10314. send_code(s, REP_3_6, s.bl_tree);
  10315. send_bits(s, count - 3, 2);
  10316. } else if (count <= 10) {
  10317. send_code(s, REPZ_3_10, s.bl_tree);
  10318. send_bits(s, count - 3, 3);
  10319. } else {
  10320. send_code(s, REPZ_11_138, s.bl_tree);
  10321. send_bits(s, count - 11, 7);
  10322. }
  10323. count = 0;
  10324. prevlen = curlen;
  10325. if (nextlen === 0) {
  10326. max_count = 138;
  10327. min_count = 3;
  10328. } else if (curlen === nextlen) {
  10329. max_count = 6;
  10330. min_count = 3;
  10331. } else {
  10332. max_count = 7;
  10333. min_count = 4;
  10334. }
  10335. }
  10336. }
  10337. /* ===========================================================================
  10338. * Construct the Huffman tree for the bit lengths and return the index in
  10339. * bl_order of the last bit length code to send.
  10340. */
  10341. function build_bl_tree(s) {
  10342. var max_blindex; /* index of last bit length code of non zero freq */
  10343. /* Determine the bit length frequencies for literal and distance trees */
  10344. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  10345. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  10346. /* Build the bit length tree: */
  10347. build_tree(s, s.bl_desc);
  10348. /* opt_len now includes the length of the tree representations, except
  10349. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  10350. */
  10351. /* Determine the number of bit length codes to send. The pkzip format
  10352. * requires that at least 4 bit length codes be sent. (appnote.txt says
  10353. * 3 but the actual value used is 4.)
  10354. */
  10355. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  10356. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  10357. break;
  10358. }
  10359. }
  10360. /* Update opt_len to include the bit length tree and counts */
  10361. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  10362. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  10363. // s->opt_len, s->static_len));
  10364. return max_blindex;
  10365. }
  10366. /* ===========================================================================
  10367. * Send the header for a block using dynamic Huffman trees: the counts, the
  10368. * lengths of the bit length codes, the literal tree and the distance tree.
  10369. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  10370. */
  10371. function send_all_trees(s, lcodes, dcodes, blcodes)
  10372. // deflate_state *s;
  10373. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  10374. {
  10375. var rank; /* index in bl_order */
  10376. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  10377. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  10378. // "too many codes");
  10379. //Tracev((stderr, "\nbl counts: "));
  10380. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  10381. send_bits(s, dcodes - 1, 5);
  10382. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  10383. for (rank = 0; rank < blcodes; rank++) {
  10384. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  10385. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  10386. }
  10387. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  10388. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  10389. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  10390. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  10391. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  10392. }
  10393. /* ===========================================================================
  10394. * Check if the data type is TEXT or BINARY, using the following algorithm:
  10395. * - TEXT if the two conditions below are satisfied:
  10396. * a) There are no non-portable control characters belonging to the
  10397. * "black list" (0..6, 14..25, 28..31).
  10398. * b) There is at least one printable character belonging to the
  10399. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  10400. * - BINARY otherwise.
  10401. * - The following partially-portable control characters form a
  10402. * "gray list" that is ignored in this detection algorithm:
  10403. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  10404. * IN assertion: the fields Freq of dyn_ltree are set.
  10405. */
  10406. function detect_data_type(s) {
  10407. /* black_mask is the bit mask of black-listed bytes
  10408. * set bits 0..6, 14..25, and 28..31
  10409. * 0xf3ffc07f = binary 11110011111111111100000001111111
  10410. */
  10411. var black_mask = 0xf3ffc07f;
  10412. var n;
  10413. /* Check for non-textual ("black-listed") bytes. */
  10414. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  10415. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  10416. return Z_BINARY;
  10417. }
  10418. }
  10419. /* Check for textual ("white-listed") bytes. */
  10420. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  10421. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  10422. return Z_TEXT;
  10423. }
  10424. for (n = 32; n < LITERALS; n++) {
  10425. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  10426. return Z_TEXT;
  10427. }
  10428. }
  10429. /* There are no "black-listed" or "white-listed" bytes:
  10430. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  10431. */
  10432. return Z_BINARY;
  10433. }
  10434. var static_init_done = false;
  10435. /* ===========================================================================
  10436. * Initialize the tree data structures for a new zlib stream.
  10437. */
  10438. function _tr_init(s)
  10439. {
  10440. if (!static_init_done) {
  10441. tr_static_init();
  10442. static_init_done = true;
  10443. }
  10444. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  10445. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  10446. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  10447. s.bi_buf = 0;
  10448. s.bi_valid = 0;
  10449. /* Initialize the first block of the first file: */
  10450. init_block(s);
  10451. }
  10452. /* ===========================================================================
  10453. * Send a stored block
  10454. */
  10455. function _tr_stored_block(s, buf, stored_len, last)
  10456. //DeflateState *s;
  10457. //charf *buf; /* input block */
  10458. //ulg stored_len; /* length of input block */
  10459. //int last; /* one if this is the last block for a file */
  10460. {
  10461. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  10462. copy_block(s, buf, stored_len, true); /* with header */
  10463. }
  10464. /* ===========================================================================
  10465. * Send one empty static block to give enough lookahead for inflate.
  10466. * This takes 10 bits, of which 7 may remain in the bit buffer.
  10467. */
  10468. function _tr_align(s) {
  10469. send_bits(s, STATIC_TREES << 1, 3);
  10470. send_code(s, END_BLOCK, static_ltree);
  10471. bi_flush(s);
  10472. }
  10473. /* ===========================================================================
  10474. * Determine the best encoding for the current block: dynamic trees, static
  10475. * trees or store, and output the encoded block to the zip file.
  10476. */
  10477. function _tr_flush_block(s, buf, stored_len, last)
  10478. //DeflateState *s;
  10479. //charf *buf; /* input block, or NULL if too old */
  10480. //ulg stored_len; /* length of input block */
  10481. //int last; /* one if this is the last block for a file */
  10482. {
  10483. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  10484. var max_blindex = 0; /* index of last bit length code of non zero freq */
  10485. /* Build the Huffman trees unless a stored block is forced */
  10486. if (s.level > 0) {
  10487. /* Check if the file is binary or text */
  10488. if (s.strm.data_type === Z_UNKNOWN) {
  10489. s.strm.data_type = detect_data_type(s);
  10490. }
  10491. /* Construct the literal and distance trees */
  10492. build_tree(s, s.l_desc);
  10493. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  10494. // s->static_len));
  10495. build_tree(s, s.d_desc);
  10496. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  10497. // s->static_len));
  10498. /* At this point, opt_len and static_len are the total bit lengths of
  10499. * the compressed block data, excluding the tree representations.
  10500. */
  10501. /* Build the bit length tree for the above two trees, and get the index
  10502. * in bl_order of the last bit length code to send.
  10503. */
  10504. max_blindex = build_bl_tree(s);
  10505. /* Determine the best encoding. Compute the block lengths in bytes. */
  10506. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  10507. static_lenb = (s.static_len + 3 + 7) >>> 3;
  10508. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  10509. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  10510. // s->last_lit));
  10511. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  10512. } else {
  10513. // Assert(buf != (char*)0, "lost buf");
  10514. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  10515. }
  10516. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  10517. /* 4: two words for the lengths */
  10518. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  10519. * Otherwise we can't have processed more than WSIZE input bytes since
  10520. * the last block flush, because compression would have been
  10521. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  10522. * transform a block into a stored block.
  10523. */
  10524. _tr_stored_block(s, buf, stored_len, last);
  10525. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  10526. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  10527. compress_block(s, static_ltree, static_dtree);
  10528. } else {
  10529. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  10530. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  10531. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  10532. }
  10533. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  10534. /* The above check is made mod 2^32, for files larger than 512 MB
  10535. * and uLong implemented on 32 bits.
  10536. */
  10537. init_block(s);
  10538. if (last) {
  10539. bi_windup(s);
  10540. }
  10541. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  10542. // s->compressed_len-7*last));
  10543. }
  10544. /* ===========================================================================
  10545. * Save the match info and tally the frequency counts. Return true if
  10546. * the current block must be flushed.
  10547. */
  10548. function _tr_tally(s, dist, lc)
  10549. // deflate_state *s;
  10550. // unsigned dist; /* distance of matched string */
  10551. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  10552. {
  10553. //var out_length, in_length, dcode;
  10554. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  10555. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  10556. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  10557. s.last_lit++;
  10558. if (dist === 0) {
  10559. /* lc is the unmatched char */
  10560. s.dyn_ltree[lc * 2]/*.Freq*/++;
  10561. } else {
  10562. s.matches++;
  10563. /* Here, lc is the match length - MIN_MATCH */
  10564. dist--; /* dist = match distance - 1 */
  10565. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  10566. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  10567. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  10568. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  10569. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  10570. }
  10571. // (!) This block is disabled in zlib defailts,
  10572. // don't enable it for binary compatibility
  10573. //#ifdef TRUNCATE_BLOCK
  10574. // /* Try to guess if it is profitable to stop the current block here */
  10575. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  10576. // /* Compute an upper bound for the compressed length */
  10577. // out_length = s.last_lit*8;
  10578. // in_length = s.strstart - s.block_start;
  10579. //
  10580. // for (dcode = 0; dcode < D_CODES; dcode++) {
  10581. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  10582. // }
  10583. // out_length >>>= 3;
  10584. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  10585. // // s->last_lit, in_length, out_length,
  10586. // // 100L - out_length*100L/in_length));
  10587. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  10588. // return true;
  10589. // }
  10590. // }
  10591. //#endif
  10592. return (s.last_lit === s.lit_bufsize - 1);
  10593. /* We avoid equality with lit_bufsize because of wraparound at 64K
  10594. * on 16 bit machines and because stored blocks are restricted to
  10595. * 64K-1 bytes.
  10596. */
  10597. }
  10598. exports._tr_init = _tr_init;
  10599. exports._tr_stored_block = _tr_stored_block;
  10600. exports._tr_flush_block = _tr_flush_block;
  10601. exports._tr_tally = _tr_tally;
  10602. exports._tr_align = _tr_align;
  10603. },{"../utils/common":32}],44:[function(_dereq_,module,exports){
  10604. 'use strict';
  10605. function ZStream() {
  10606. /* next input byte */
  10607. this.input = null; // JS specific, because we have no pointers
  10608. this.next_in = 0;
  10609. /* number of bytes available at input */
  10610. this.avail_in = 0;
  10611. /* total number of input bytes read so far */
  10612. this.total_in = 0;
  10613. /* next output byte should be put there */
  10614. this.output = null; // JS specific, because we have no pointers
  10615. this.next_out = 0;
  10616. /* remaining free space at output */
  10617. this.avail_out = 0;
  10618. /* total number of bytes output so far */
  10619. this.total_out = 0;
  10620. /* last error message, NULL if no error */
  10621. this.msg = ''/*Z_NULL*/;
  10622. /* not visible by applications */
  10623. this.state = null;
  10624. /* best guess about the data type: binary or text */
  10625. this.data_type = 2/*Z_UNKNOWN*/;
  10626. /* adler32 value of the uncompressed data */
  10627. this.adler = 0;
  10628. }
  10629. module.exports = ZStream;
  10630. },{}],45:[function(_dereq_,module,exports){
  10631. /**
  10632. * lodash 3.2.0 (Custom Build) <https://lodash.com/>
  10633. * Build: `lodash modularize exports="npm" -o ./`
  10634. * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
  10635. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  10636. * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  10637. * Available under MIT license <https://lodash.com/license>
  10638. */
  10639. var root = _dereq_('lodash._root');
  10640. /** Used as references for various `Number` constants. */
  10641. var INFINITY = 1 / 0;
  10642. /** `Object#toString` result references. */
  10643. var symbolTag = '[object Symbol]';
  10644. /** Used to match HTML entities and HTML characters. */
  10645. var reUnescapedHtml = /[&<>"'`]/g,
  10646. reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
  10647. /** Used to map characters to HTML entities. */
  10648. var htmlEscapes = {
  10649. '&': '&amp;',
  10650. '<': '&lt;',
  10651. '>': '&gt;',
  10652. '"': '&quot;',
  10653. "'": '&#39;',
  10654. '`': '&#96;'
  10655. };
  10656. /**
  10657. * Used by `_.escape` to convert characters to HTML entities.
  10658. *
  10659. * @private
  10660. * @param {string} chr The matched character to escape.
  10661. * @returns {string} Returns the escaped character.
  10662. */
  10663. function escapeHtmlChar(chr) {
  10664. return htmlEscapes[chr];
  10665. }
  10666. /** Used for built-in method references. */
  10667. var objectProto = Object.prototype;
  10668. /**
  10669. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  10670. * of values.
  10671. */
  10672. var objectToString = objectProto.toString;
  10673. /** Built-in value references. */
  10674. var Symbol = root.Symbol;
  10675. /** Used to convert symbols to primitives and strings. */
  10676. var symbolProto = Symbol ? Symbol.prototype : undefined,
  10677. symbolToString = Symbol ? symbolProto.toString : undefined;
  10678. /**
  10679. * Checks if `value` is object-like. A value is object-like if it's not `null`
  10680. * and has a `typeof` result of "object".
  10681. *
  10682. * @static
  10683. * @memberOf _
  10684. * @category Lang
  10685. * @param {*} value The value to check.
  10686. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  10687. * @example
  10688. *
  10689. * _.isObjectLike({});
  10690. * // => true
  10691. *
  10692. * _.isObjectLike([1, 2, 3]);
  10693. * // => true
  10694. *
  10695. * _.isObjectLike(_.noop);
  10696. * // => false
  10697. *
  10698. * _.isObjectLike(null);
  10699. * // => false
  10700. */
  10701. function isObjectLike(value) {
  10702. return !!value && typeof value == 'object';
  10703. }
  10704. /**
  10705. * Checks if `value` is classified as a `Symbol` primitive or object.
  10706. *
  10707. * @static
  10708. * @memberOf _
  10709. * @category Lang
  10710. * @param {*} value The value to check.
  10711. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  10712. * @example
  10713. *
  10714. * _.isSymbol(Symbol.iterator);
  10715. * // => true
  10716. *
  10717. * _.isSymbol('abc');
  10718. * // => false
  10719. */
  10720. function isSymbol(value) {
  10721. return typeof value == 'symbol' ||
  10722. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  10723. }
  10724. /**
  10725. * Converts `value` to a string if it's not one. An empty string is returned
  10726. * for `null` and `undefined` values. The sign of `-0` is preserved.
  10727. *
  10728. * @static
  10729. * @memberOf _
  10730. * @category Lang
  10731. * @param {*} value The value to process.
  10732. * @returns {string} Returns the string.
  10733. * @example
  10734. *
  10735. * _.toString(null);
  10736. * // => ''
  10737. *
  10738. * _.toString(-0);
  10739. * // => '-0'
  10740. *
  10741. * _.toString([1, 2, 3]);
  10742. * // => '1,2,3'
  10743. */
  10744. function toString(value) {
  10745. // Exit early for strings to avoid a performance hit in some environments.
  10746. if (typeof value == 'string') {
  10747. return value;
  10748. }
  10749. if (value == null) {
  10750. return '';
  10751. }
  10752. if (isSymbol(value)) {
  10753. return Symbol ? symbolToString.call(value) : '';
  10754. }
  10755. var result = (value + '');
  10756. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  10757. }
  10758. /**
  10759. * Converts the characters "&", "<", ">", '"', "'", and "\`" in `string` to
  10760. * their corresponding HTML entities.
  10761. *
  10762. * **Note:** No other characters are escaped. To escape additional
  10763. * characters use a third-party library like [_he_](https://mths.be/he).
  10764. *
  10765. * Though the ">" character is escaped for symmetry, characters like
  10766. * ">" and "/" don't need escaping in HTML and have no special meaning
  10767. * unless they're part of a tag or unquoted attribute value.
  10768. * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
  10769. * (under "semi-related fun fact") for more details.
  10770. *
  10771. * Backticks are escaped because in IE < 9, they can break out of
  10772. * attribute values or HTML comments. See [#59](https://html5sec.org/#59),
  10773. * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
  10774. * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
  10775. * for more details.
  10776. *
  10777. * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
  10778. * to reduce XSS vectors.
  10779. *
  10780. * @static
  10781. * @memberOf _
  10782. * @category String
  10783. * @param {string} [string=''] The string to escape.
  10784. * @returns {string} Returns the escaped string.
  10785. * @example
  10786. *
  10787. * _.escape('fred, barney, & pebbles');
  10788. * // => 'fred, barney, &amp; pebbles'
  10789. */
  10790. function escape(string) {
  10791. string = toString(string);
  10792. return (string && reHasUnescapedHtml.test(string))
  10793. ? string.replace(reUnescapedHtml, escapeHtmlChar)
  10794. : string;
  10795. }
  10796. module.exports = escape;
  10797. },{"lodash._root":46}],46:[function(_dereq_,module,exports){
  10798. (function (global){
  10799. /**
  10800. * lodash 3.0.1 (Custom Build) <https://lodash.com/>
  10801. * Build: `lodash modularize exports="npm" -o ./`
  10802. * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
  10803. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  10804. * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  10805. * Available under MIT license <https://lodash.com/license>
  10806. */
  10807. /** Used to determine if values are of the language type `Object`. */
  10808. var objectTypes = {
  10809. 'function': true,
  10810. 'object': true
  10811. };
  10812. /** Detect free variable `exports`. */
  10813. var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
  10814. ? exports
  10815. : undefined;
  10816. /** Detect free variable `module`. */
  10817. var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
  10818. ? module
  10819. : undefined;
  10820. /** Detect free variable `global` from Node.js. */
  10821. var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
  10822. /** Detect free variable `self`. */
  10823. var freeSelf = checkGlobal(objectTypes[typeof self] && self);
  10824. /** Detect free variable `window`. */
  10825. var freeWindow = checkGlobal(objectTypes[typeof window] && window);
  10826. /** Detect `this` as the global object. */
  10827. var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
  10828. /**
  10829. * Used as a reference to the global object.
  10830. *
  10831. * The `this` value is used if it's the global object to avoid Greasemonkey's
  10832. * restricted `window` object, otherwise the `window` object is used.
  10833. */
  10834. var root = freeGlobal ||
  10835. ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
  10836. freeSelf || thisGlobal || Function('return this')();
  10837. /**
  10838. * Checks if `value` is a global object.
  10839. *
  10840. * @private
  10841. * @param {*} value The value to check.
  10842. * @returns {null|Object} Returns `value` if it's a global object, else `null`.
  10843. */
  10844. function checkGlobal(value) {
  10845. return (value && value.Object === Object) ? value : null;
  10846. }
  10847. module.exports = root;
  10848. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  10849. },{}],47:[function(_dereq_,module,exports){
  10850. /**
  10851. * lodash 3.3.2 (Custom Build) <https://lodash.com/>
  10852. * Build: `lodash modern modularize exports="npm" -o ./`
  10853. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  10854. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  10855. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  10856. * Available under MIT license <https://lodash.com/license>
  10857. */
  10858. var arrayCopy = _dereq_('lodash._arraycopy'),
  10859. arrayEach = _dereq_('lodash._arrayeach'),
  10860. createAssigner = _dereq_('lodash._createassigner'),
  10861. isArguments = _dereq_('lodash.isarguments'),
  10862. isArray = _dereq_('lodash.isarray'),
  10863. isPlainObject = _dereq_('lodash.isplainobject'),
  10864. isTypedArray = _dereq_('lodash.istypedarray'),
  10865. keys = _dereq_('lodash.keys'),
  10866. toPlainObject = _dereq_('lodash.toplainobject');
  10867. /**
  10868. * Checks if `value` is object-like.
  10869. *
  10870. * @private
  10871. * @param {*} value The value to check.
  10872. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  10873. */
  10874. function isObjectLike(value) {
  10875. return !!value && typeof value == 'object';
  10876. }
  10877. /**
  10878. * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
  10879. * of an array-like value.
  10880. */
  10881. var MAX_SAFE_INTEGER = 9007199254740991;
  10882. /**
  10883. * The base implementation of `_.merge` without support for argument juggling,
  10884. * multiple sources, and `this` binding `customizer` functions.
  10885. *
  10886. * @private
  10887. * @param {Object} object The destination object.
  10888. * @param {Object} source The source object.
  10889. * @param {Function} [customizer] The function to customize merged values.
  10890. * @param {Array} [stackA=[]] Tracks traversed source objects.
  10891. * @param {Array} [stackB=[]] Associates values with source counterparts.
  10892. * @returns {Object} Returns `object`.
  10893. */
  10894. function baseMerge(object, source, customizer, stackA, stackB) {
  10895. if (!isObject(object)) {
  10896. return object;
  10897. }
  10898. var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
  10899. props = isSrcArr ? undefined : keys(source);
  10900. arrayEach(props || source, function(srcValue, key) {
  10901. if (props) {
  10902. key = srcValue;
  10903. srcValue = source[key];
  10904. }
  10905. if (isObjectLike(srcValue)) {
  10906. stackA || (stackA = []);
  10907. stackB || (stackB = []);
  10908. baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
  10909. }
  10910. else {
  10911. var value = object[key],
  10912. result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
  10913. isCommon = result === undefined;
  10914. if (isCommon) {
  10915. result = srcValue;
  10916. }
  10917. if ((result !== undefined || (isSrcArr && !(key in object))) &&
  10918. (isCommon || (result === result ? (result !== value) : (value === value)))) {
  10919. object[key] = result;
  10920. }
  10921. }
  10922. });
  10923. return object;
  10924. }
  10925. /**
  10926. * A specialized version of `baseMerge` for arrays and objects which performs
  10927. * deep merges and tracks traversed objects enabling objects with circular
  10928. * references to be merged.
  10929. *
  10930. * @private
  10931. * @param {Object} object The destination object.
  10932. * @param {Object} source The source object.
  10933. * @param {string} key The key of the value to merge.
  10934. * @param {Function} mergeFunc The function to merge values.
  10935. * @param {Function} [customizer] The function to customize merged values.
  10936. * @param {Array} [stackA=[]] Tracks traversed source objects.
  10937. * @param {Array} [stackB=[]] Associates values with source counterparts.
  10938. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  10939. */
  10940. function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
  10941. var length = stackA.length,
  10942. srcValue = source[key];
  10943. while (length--) {
  10944. if (stackA[length] == srcValue) {
  10945. object[key] = stackB[length];
  10946. return;
  10947. }
  10948. }
  10949. var value = object[key],
  10950. result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
  10951. isCommon = result === undefined;
  10952. if (isCommon) {
  10953. result = srcValue;
  10954. if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
  10955. result = isArray(value)
  10956. ? value
  10957. : (isArrayLike(value) ? arrayCopy(value) : []);
  10958. }
  10959. else if (isPlainObject(srcValue) || isArguments(srcValue)) {
  10960. result = isArguments(value)
  10961. ? toPlainObject(value)
  10962. : (isPlainObject(value) ? value : {});
  10963. }
  10964. else {
  10965. isCommon = false;
  10966. }
  10967. }
  10968. // Add the source value to the stack of traversed objects and associate
  10969. // it with its merged value.
  10970. stackA.push(srcValue);
  10971. stackB.push(result);
  10972. if (isCommon) {
  10973. // Recursively merge objects and arrays (susceptible to call stack limits).
  10974. object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
  10975. } else if (result === result ? (result !== value) : (value === value)) {
  10976. object[key] = result;
  10977. }
  10978. }
  10979. /**
  10980. * The base implementation of `_.property` without support for deep paths.
  10981. *
  10982. * @private
  10983. * @param {string} key The key of the property to get.
  10984. * @returns {Function} Returns the new function.
  10985. */
  10986. function baseProperty(key) {
  10987. return function(object) {
  10988. return object == null ? undefined : object[key];
  10989. };
  10990. }
  10991. /**
  10992. * Gets the "length" property value of `object`.
  10993. *
  10994. * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
  10995. * that affects Safari on at least iOS 8.1-8.3 ARM64.
  10996. *
  10997. * @private
  10998. * @param {Object} object The object to query.
  10999. * @returns {*} Returns the "length" value.
  11000. */
  11001. var getLength = baseProperty('length');
  11002. /**
  11003. * Checks if `value` is array-like.
  11004. *
  11005. * @private
  11006. * @param {*} value The value to check.
  11007. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  11008. */
  11009. function isArrayLike(value) {
  11010. return value != null && isLength(getLength(value));
  11011. }
  11012. /**
  11013. * Checks if `value` is a valid array-like length.
  11014. *
  11015. * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  11016. *
  11017. * @private
  11018. * @param {*} value The value to check.
  11019. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  11020. */
  11021. function isLength(value) {
  11022. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  11023. }
  11024. /**
  11025. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  11026. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  11027. *
  11028. * @static
  11029. * @memberOf _
  11030. * @category Lang
  11031. * @param {*} value The value to check.
  11032. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  11033. * @example
  11034. *
  11035. * _.isObject({});
  11036. * // => true
  11037. *
  11038. * _.isObject([1, 2, 3]);
  11039. * // => true
  11040. *
  11041. * _.isObject(1);
  11042. * // => false
  11043. */
  11044. function isObject(value) {
  11045. // Avoid a V8 JIT bug in Chrome 19-20.
  11046. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  11047. var type = typeof value;
  11048. return !!value && (type == 'object' || type == 'function');
  11049. }
  11050. /**
  11051. * Recursively merges own enumerable properties of the source object(s), that
  11052. * don't resolve to `undefined` into the destination object. Subsequent sources
  11053. * overwrite property assignments of previous sources. If `customizer` is
  11054. * provided it is invoked to produce the merged values of the destination and
  11055. * source properties. If `customizer` returns `undefined` merging is handled
  11056. * by the method instead. The `customizer` is bound to `thisArg` and invoked
  11057. * with five arguments: (objectValue, sourceValue, key, object, source).
  11058. *
  11059. * @static
  11060. * @memberOf _
  11061. * @category Object
  11062. * @param {Object} object The destination object.
  11063. * @param {...Object} [sources] The source objects.
  11064. * @param {Function} [customizer] The function to customize assigned values.
  11065. * @param {*} [thisArg] The `this` binding of `customizer`.
  11066. * @returns {Object} Returns `object`.
  11067. * @example
  11068. *
  11069. * var users = {
  11070. * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
  11071. * };
  11072. *
  11073. * var ages = {
  11074. * 'data': [{ 'age': 36 }, { 'age': 40 }]
  11075. * };
  11076. *
  11077. * _.merge(users, ages);
  11078. * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
  11079. *
  11080. * // using a customizer callback
  11081. * var object = {
  11082. * 'fruits': ['apple'],
  11083. * 'vegetables': ['beet']
  11084. * };
  11085. *
  11086. * var other = {
  11087. * 'fruits': ['banana'],
  11088. * 'vegetables': ['carrot']
  11089. * };
  11090. *
  11091. * _.merge(object, other, function(a, b) {
  11092. * if (_.isArray(a)) {
  11093. * return a.concat(b);
  11094. * }
  11095. * });
  11096. * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
  11097. */
  11098. var merge = createAssigner(baseMerge);
  11099. module.exports = merge;
  11100. },{"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){
  11101. /**
  11102. * lodash 3.0.0 (Custom Build) <https://lodash.com/>
  11103. * Build: `lodash modern modularize exports="npm" -o ./`
  11104. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11105. * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
  11106. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11107. * Available under MIT license <https://lodash.com/license>
  11108. */
  11109. /**
  11110. * Copies the values of `source` to `array`.
  11111. *
  11112. * @private
  11113. * @param {Array} source The array to copy values from.
  11114. * @param {Array} [array=[]] The array to copy values to.
  11115. * @returns {Array} Returns `array`.
  11116. */
  11117. function arrayCopy(source, array) {
  11118. var index = -1,
  11119. length = source.length;
  11120. array || (array = Array(length));
  11121. while (++index < length) {
  11122. array[index] = source[index];
  11123. }
  11124. return array;
  11125. }
  11126. module.exports = arrayCopy;
  11127. },{}],49:[function(_dereq_,module,exports){
  11128. /**
  11129. * lodash 3.0.0 (Custom Build) <https://lodash.com/>
  11130. * Build: `lodash modern modularize exports="npm" -o ./`
  11131. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11132. * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
  11133. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11134. * Available under MIT license <https://lodash.com/license>
  11135. */
  11136. /**
  11137. * A specialized version of `_.forEach` for arrays without support for callback
  11138. * shorthands or `this` binding.
  11139. *
  11140. * @private
  11141. * @param {Array} array The array to iterate over.
  11142. * @param {Function} iteratee The function invoked per iteration.
  11143. * @returns {Array} Returns `array`.
  11144. */
  11145. function arrayEach(array, iteratee) {
  11146. var index = -1,
  11147. length = array.length;
  11148. while (++index < length) {
  11149. if (iteratee(array[index], index, array) === false) {
  11150. break;
  11151. }
  11152. }
  11153. return array;
  11154. }
  11155. module.exports = arrayEach;
  11156. },{}],50:[function(_dereq_,module,exports){
  11157. /**
  11158. * lodash 3.1.1 (Custom Build) <https://lodash.com/>
  11159. * Build: `lodash modern modularize exports="npm" -o ./`
  11160. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11161. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11162. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11163. * Available under MIT license <https://lodash.com/license>
  11164. */
  11165. var bindCallback = _dereq_('lodash._bindcallback'),
  11166. isIterateeCall = _dereq_('lodash._isiterateecall'),
  11167. restParam = _dereq_('lodash.restparam');
  11168. /**
  11169. * Creates a function that assigns properties of source object(s) to a given
  11170. * destination object.
  11171. *
  11172. * **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`.
  11173. *
  11174. * @private
  11175. * @param {Function} assigner The function to assign values.
  11176. * @returns {Function} Returns the new assigner function.
  11177. */
  11178. function createAssigner(assigner) {
  11179. return restParam(function(object, sources) {
  11180. var index = -1,
  11181. length = object == null ? 0 : sources.length,
  11182. customizer = length > 2 ? sources[length - 2] : undefined,
  11183. guard = length > 2 ? sources[2] : undefined,
  11184. thisArg = length > 1 ? sources[length - 1] : undefined;
  11185. if (typeof customizer == 'function') {
  11186. customizer = bindCallback(customizer, thisArg, 5);
  11187. length -= 2;
  11188. } else {
  11189. customizer = typeof thisArg == 'function' ? thisArg : undefined;
  11190. length -= (customizer ? 1 : 0);
  11191. }
  11192. if (guard && isIterateeCall(sources[0], sources[1], guard)) {
  11193. customizer = length < 3 ? undefined : customizer;
  11194. length = 1;
  11195. }
  11196. while (++index < length) {
  11197. var source = sources[index];
  11198. if (source) {
  11199. assigner(object, source, customizer);
  11200. }
  11201. }
  11202. return object;
  11203. });
  11204. }
  11205. module.exports = createAssigner;
  11206. },{"lodash._bindcallback":51,"lodash._isiterateecall":52,"lodash.restparam":53}],51:[function(_dereq_,module,exports){
  11207. /**
  11208. * lodash 3.0.1 (Custom Build) <https://lodash.com/>
  11209. * Build: `lodash modern modularize exports="npm" -o ./`
  11210. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11211. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11212. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11213. * Available under MIT license <https://lodash.com/license>
  11214. */
  11215. /**
  11216. * A specialized version of `baseCallback` which only supports `this` binding
  11217. * and specifying the number of arguments to provide to `func`.
  11218. *
  11219. * @private
  11220. * @param {Function} func The function to bind.
  11221. * @param {*} thisArg The `this` binding of `func`.
  11222. * @param {number} [argCount] The number of arguments to provide to `func`.
  11223. * @returns {Function} Returns the callback.
  11224. */
  11225. function bindCallback(func, thisArg, argCount) {
  11226. if (typeof func != 'function') {
  11227. return identity;
  11228. }
  11229. if (thisArg === undefined) {
  11230. return func;
  11231. }
  11232. switch (argCount) {
  11233. case 1: return function(value) {
  11234. return func.call(thisArg, value);
  11235. };
  11236. case 3: return function(value, index, collection) {
  11237. return func.call(thisArg, value, index, collection);
  11238. };
  11239. case 4: return function(accumulator, value, index, collection) {
  11240. return func.call(thisArg, accumulator, value, index, collection);
  11241. };
  11242. case 5: return function(value, other, key, object, source) {
  11243. return func.call(thisArg, value, other, key, object, source);
  11244. };
  11245. }
  11246. return function() {
  11247. return func.apply(thisArg, arguments);
  11248. };
  11249. }
  11250. /**
  11251. * This method returns the first argument provided to it.
  11252. *
  11253. * @static
  11254. * @memberOf _
  11255. * @category Utility
  11256. * @param {*} value Any value.
  11257. * @returns {*} Returns `value`.
  11258. * @example
  11259. *
  11260. * var object = { 'user': 'fred' };
  11261. *
  11262. * _.identity(object) === object;
  11263. * // => true
  11264. */
  11265. function identity(value) {
  11266. return value;
  11267. }
  11268. module.exports = bindCallback;
  11269. },{}],52:[function(_dereq_,module,exports){
  11270. /**
  11271. * lodash 3.0.9 (Custom Build) <https://lodash.com/>
  11272. * Build: `lodash modern modularize exports="npm" -o ./`
  11273. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11274. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11275. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11276. * Available under MIT license <https://lodash.com/license>
  11277. */
  11278. /** Used to detect unsigned integer values. */
  11279. var reIsUint = /^\d+$/;
  11280. /**
  11281. * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
  11282. * of an array-like value.
  11283. */
  11284. var MAX_SAFE_INTEGER = 9007199254740991;
  11285. /**
  11286. * The base implementation of `_.property` without support for deep paths.
  11287. *
  11288. * @private
  11289. * @param {string} key The key of the property to get.
  11290. * @returns {Function} Returns the new function.
  11291. */
  11292. function baseProperty(key) {
  11293. return function(object) {
  11294. return object == null ? undefined : object[key];
  11295. };
  11296. }
  11297. /**
  11298. * Gets the "length" property value of `object`.
  11299. *
  11300. * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
  11301. * that affects Safari on at least iOS 8.1-8.3 ARM64.
  11302. *
  11303. * @private
  11304. * @param {Object} object The object to query.
  11305. * @returns {*} Returns the "length" value.
  11306. */
  11307. var getLength = baseProperty('length');
  11308. /**
  11309. * Checks if `value` is array-like.
  11310. *
  11311. * @private
  11312. * @param {*} value The value to check.
  11313. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  11314. */
  11315. function isArrayLike(value) {
  11316. return value != null && isLength(getLength(value));
  11317. }
  11318. /**
  11319. * Checks if `value` is a valid array-like index.
  11320. *
  11321. * @private
  11322. * @param {*} value The value to check.
  11323. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  11324. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  11325. */
  11326. function isIndex(value, length) {
  11327. value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
  11328. length = length == null ? MAX_SAFE_INTEGER : length;
  11329. return value > -1 && value % 1 == 0 && value < length;
  11330. }
  11331. /**
  11332. * Checks if the provided arguments are from an iteratee call.
  11333. *
  11334. * @private
  11335. * @param {*} value The potential iteratee value argument.
  11336. * @param {*} index The potential iteratee index or key argument.
  11337. * @param {*} object The potential iteratee object argument.
  11338. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
  11339. */
  11340. function isIterateeCall(value, index, object) {
  11341. if (!isObject(object)) {
  11342. return false;
  11343. }
  11344. var type = typeof index;
  11345. if (type == 'number'
  11346. ? (isArrayLike(object) && isIndex(index, object.length))
  11347. : (type == 'string' && index in object)) {
  11348. var other = object[index];
  11349. return value === value ? (value === other) : (other !== other);
  11350. }
  11351. return false;
  11352. }
  11353. /**
  11354. * Checks if `value` is a valid array-like length.
  11355. *
  11356. * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
  11357. *
  11358. * @private
  11359. * @param {*} value The value to check.
  11360. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  11361. */
  11362. function isLength(value) {
  11363. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  11364. }
  11365. /**
  11366. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  11367. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  11368. *
  11369. * @static
  11370. * @memberOf _
  11371. * @category Lang
  11372. * @param {*} value The value to check.
  11373. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  11374. * @example
  11375. *
  11376. * _.isObject({});
  11377. * // => true
  11378. *
  11379. * _.isObject([1, 2, 3]);
  11380. * // => true
  11381. *
  11382. * _.isObject(1);
  11383. * // => false
  11384. */
  11385. function isObject(value) {
  11386. // Avoid a V8 JIT bug in Chrome 19-20.
  11387. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  11388. var type = typeof value;
  11389. return !!value && (type == 'object' || type == 'function');
  11390. }
  11391. module.exports = isIterateeCall;
  11392. },{}],53:[function(_dereq_,module,exports){
  11393. /**
  11394. * lodash 3.6.1 (Custom Build) <https://lodash.com/>
  11395. * Build: `lodash modern modularize exports="npm" -o ./`
  11396. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11397. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11398. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11399. * Available under MIT license <https://lodash.com/license>
  11400. */
  11401. /** Used as the `TypeError` message for "Functions" methods. */
  11402. var FUNC_ERROR_TEXT = 'Expected a function';
  11403. /* Native method references for those with the same name as other `lodash` methods. */
  11404. var nativeMax = Math.max;
  11405. /**
  11406. * Creates a function that invokes `func` with the `this` binding of the
  11407. * created function and arguments from `start` and beyond provided as an array.
  11408. *
  11409. * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
  11410. *
  11411. * @static
  11412. * @memberOf _
  11413. * @category Function
  11414. * @param {Function} func The function to apply a rest parameter to.
  11415. * @param {number} [start=func.length-1] The start position of the rest parameter.
  11416. * @returns {Function} Returns the new function.
  11417. * @example
  11418. *
  11419. * var say = _.restParam(function(what, names) {
  11420. * return what + ' ' + _.initial(names).join(', ') +
  11421. * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
  11422. * });
  11423. *
  11424. * say('hello', 'fred', 'barney', 'pebbles');
  11425. * // => 'hello fred, barney, & pebbles'
  11426. */
  11427. function restParam(func, start) {
  11428. if (typeof func != 'function') {
  11429. throw new TypeError(FUNC_ERROR_TEXT);
  11430. }
  11431. start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
  11432. return function() {
  11433. var args = arguments,
  11434. index = -1,
  11435. length = nativeMax(args.length - start, 0),
  11436. rest = Array(length);
  11437. while (++index < length) {
  11438. rest[index] = args[start + index];
  11439. }
  11440. switch (start) {
  11441. case 0: return func.call(this, rest);
  11442. case 1: return func.call(this, args[0], rest);
  11443. case 2: return func.call(this, args[0], args[1], rest);
  11444. }
  11445. var otherArgs = Array(start + 1);
  11446. index = -1;
  11447. while (++index < start) {
  11448. otherArgs[index] = args[index];
  11449. }
  11450. otherArgs[start] = rest;
  11451. return func.apply(this, otherArgs);
  11452. };
  11453. }
  11454. module.exports = restParam;
  11455. },{}],54:[function(_dereq_,module,exports){
  11456. /**
  11457. * lodash 3.9.1 (Custom Build) <https://lodash.com/>
  11458. * Build: `lodash modern modularize exports="npm" -o ./`
  11459. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11460. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11461. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11462. * Available under MIT license <https://lodash.com/license>
  11463. */
  11464. /** `Object#toString` result references. */
  11465. var funcTag = '[object Function]';
  11466. /** Used to detect host constructors (Safari > 5). */
  11467. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  11468. /**
  11469. * Checks if `value` is object-like.
  11470. *
  11471. * @private
  11472. * @param {*} value The value to check.
  11473. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11474. */
  11475. function isObjectLike(value) {
  11476. return !!value && typeof value == 'object';
  11477. }
  11478. /** Used for native method references. */
  11479. var objectProto = Object.prototype;
  11480. /** Used to resolve the decompiled source of functions. */
  11481. var fnToString = Function.prototype.toString;
  11482. /** Used to check objects for own properties. */
  11483. var hasOwnProperty = objectProto.hasOwnProperty;
  11484. /**
  11485. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  11486. * of values.
  11487. */
  11488. var objToString = objectProto.toString;
  11489. /** Used to detect if a method is native. */
  11490. var reIsNative = RegExp('^' +
  11491. fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
  11492. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  11493. );
  11494. /**
  11495. * Gets the native function at `key` of `object`.
  11496. *
  11497. * @private
  11498. * @param {Object} object The object to query.
  11499. * @param {string} key The key of the method to get.
  11500. * @returns {*} Returns the function if it's native, else `undefined`.
  11501. */
  11502. function getNative(object, key) {
  11503. var value = object == null ? undefined : object[key];
  11504. return isNative(value) ? value : undefined;
  11505. }
  11506. /**
  11507. * Checks if `value` is classified as a `Function` object.
  11508. *
  11509. * @static
  11510. * @memberOf _
  11511. * @category Lang
  11512. * @param {*} value The value to check.
  11513. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  11514. * @example
  11515. *
  11516. * _.isFunction(_);
  11517. * // => true
  11518. *
  11519. * _.isFunction(/abc/);
  11520. * // => false
  11521. */
  11522. function isFunction(value) {
  11523. // The use of `Object#toString` avoids issues with the `typeof` operator
  11524. // in older versions of Chrome and Safari which return 'function' for regexes
  11525. // and Safari 8 equivalents which return 'object' for typed array constructors.
  11526. return isObject(value) && objToString.call(value) == funcTag;
  11527. }
  11528. /**
  11529. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  11530. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  11531. *
  11532. * @static
  11533. * @memberOf _
  11534. * @category Lang
  11535. * @param {*} value The value to check.
  11536. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  11537. * @example
  11538. *
  11539. * _.isObject({});
  11540. * // => true
  11541. *
  11542. * _.isObject([1, 2, 3]);
  11543. * // => true
  11544. *
  11545. * _.isObject(1);
  11546. * // => false
  11547. */
  11548. function isObject(value) {
  11549. // Avoid a V8 JIT bug in Chrome 19-20.
  11550. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  11551. var type = typeof value;
  11552. return !!value && (type == 'object' || type == 'function');
  11553. }
  11554. /**
  11555. * Checks if `value` is a native function.
  11556. *
  11557. * @static
  11558. * @memberOf _
  11559. * @category Lang
  11560. * @param {*} value The value to check.
  11561. * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
  11562. * @example
  11563. *
  11564. * _.isNative(Array.prototype.push);
  11565. * // => true
  11566. *
  11567. * _.isNative(_);
  11568. * // => false
  11569. */
  11570. function isNative(value) {
  11571. if (value == null) {
  11572. return false;
  11573. }
  11574. if (isFunction(value)) {
  11575. return reIsNative.test(fnToString.call(value));
  11576. }
  11577. return isObjectLike(value) && reIsHostCtor.test(value);
  11578. }
  11579. module.exports = getNative;
  11580. },{}],55:[function(_dereq_,module,exports){
  11581. /**
  11582. * lodash 3.0.8 (Custom Build) <https://lodash.com/>
  11583. * Build: `lodash modularize exports="npm" -o ./`
  11584. * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
  11585. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11586. * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11587. * Available under MIT license <https://lodash.com/license>
  11588. */
  11589. /** Used as references for various `Number` constants. */
  11590. var MAX_SAFE_INTEGER = 9007199254740991;
  11591. /** `Object#toString` result references. */
  11592. var argsTag = '[object Arguments]',
  11593. funcTag = '[object Function]',
  11594. genTag = '[object GeneratorFunction]';
  11595. /** Used for built-in method references. */
  11596. var objectProto = Object.prototype;
  11597. /** Used to check objects for own properties. */
  11598. var hasOwnProperty = objectProto.hasOwnProperty;
  11599. /**
  11600. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  11601. * of values.
  11602. */
  11603. var objectToString = objectProto.toString;
  11604. /** Built-in value references. */
  11605. var propertyIsEnumerable = objectProto.propertyIsEnumerable;
  11606. /**
  11607. * The base implementation of `_.property` without support for deep paths.
  11608. *
  11609. * @private
  11610. * @param {string} key The key of the property to get.
  11611. * @returns {Function} Returns the new function.
  11612. */
  11613. function baseProperty(key) {
  11614. return function(object) {
  11615. return object == null ? undefined : object[key];
  11616. };
  11617. }
  11618. /**
  11619. * Gets the "length" property value of `object`.
  11620. *
  11621. * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
  11622. * that affects Safari on at least iOS 8.1-8.3 ARM64.
  11623. *
  11624. * @private
  11625. * @param {Object} object The object to query.
  11626. * @returns {*} Returns the "length" value.
  11627. */
  11628. var getLength = baseProperty('length');
  11629. /**
  11630. * Checks if `value` is likely an `arguments` object.
  11631. *
  11632. * @static
  11633. * @memberOf _
  11634. * @category Lang
  11635. * @param {*} value The value to check.
  11636. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  11637. * @example
  11638. *
  11639. * _.isArguments(function() { return arguments; }());
  11640. * // => true
  11641. *
  11642. * _.isArguments([1, 2, 3]);
  11643. * // => false
  11644. */
  11645. function isArguments(value) {
  11646. // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
  11647. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
  11648. (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
  11649. }
  11650. /**
  11651. * Checks if `value` is array-like. A value is considered array-like if it's
  11652. * not a function and has a `value.length` that's an integer greater than or
  11653. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  11654. *
  11655. * @static
  11656. * @memberOf _
  11657. * @category Lang
  11658. * @param {*} value The value to check.
  11659. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  11660. * @example
  11661. *
  11662. * _.isArrayLike([1, 2, 3]);
  11663. * // => true
  11664. *
  11665. * _.isArrayLike(document.body.children);
  11666. * // => true
  11667. *
  11668. * _.isArrayLike('abc');
  11669. * // => true
  11670. *
  11671. * _.isArrayLike(_.noop);
  11672. * // => false
  11673. */
  11674. function isArrayLike(value) {
  11675. return value != null && isLength(getLength(value)) && !isFunction(value);
  11676. }
  11677. /**
  11678. * This method is like `_.isArrayLike` except that it also checks if `value`
  11679. * is an object.
  11680. *
  11681. * @static
  11682. * @memberOf _
  11683. * @category Lang
  11684. * @param {*} value The value to check.
  11685. * @returns {boolean} Returns `true` if `value` is an array-like object, else `false`.
  11686. * @example
  11687. *
  11688. * _.isArrayLikeObject([1, 2, 3]);
  11689. * // => true
  11690. *
  11691. * _.isArrayLikeObject(document.body.children);
  11692. * // => true
  11693. *
  11694. * _.isArrayLikeObject('abc');
  11695. * // => false
  11696. *
  11697. * _.isArrayLikeObject(_.noop);
  11698. * // => false
  11699. */
  11700. function isArrayLikeObject(value) {
  11701. return isObjectLike(value) && isArrayLike(value);
  11702. }
  11703. /**
  11704. * Checks if `value` is classified as a `Function` object.
  11705. *
  11706. * @static
  11707. * @memberOf _
  11708. * @category Lang
  11709. * @param {*} value The value to check.
  11710. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  11711. * @example
  11712. *
  11713. * _.isFunction(_);
  11714. * // => true
  11715. *
  11716. * _.isFunction(/abc/);
  11717. * // => false
  11718. */
  11719. function isFunction(value) {
  11720. // The use of `Object#toString` avoids issues with the `typeof` operator
  11721. // in Safari 8 which returns 'object' for typed array and weak map constructors,
  11722. // and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
  11723. var tag = isObject(value) ? objectToString.call(value) : '';
  11724. return tag == funcTag || tag == genTag;
  11725. }
  11726. /**
  11727. * Checks if `value` is a valid array-like length.
  11728. *
  11729. * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  11730. *
  11731. * @static
  11732. * @memberOf _
  11733. * @category Lang
  11734. * @param {*} value The value to check.
  11735. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  11736. * @example
  11737. *
  11738. * _.isLength(3);
  11739. * // => true
  11740. *
  11741. * _.isLength(Number.MIN_VALUE);
  11742. * // => false
  11743. *
  11744. * _.isLength(Infinity);
  11745. * // => false
  11746. *
  11747. * _.isLength('3');
  11748. * // => false
  11749. */
  11750. function isLength(value) {
  11751. return typeof value == 'number' &&
  11752. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  11753. }
  11754. /**
  11755. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  11756. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  11757. *
  11758. * @static
  11759. * @memberOf _
  11760. * @category Lang
  11761. * @param {*} value The value to check.
  11762. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  11763. * @example
  11764. *
  11765. * _.isObject({});
  11766. * // => true
  11767. *
  11768. * _.isObject([1, 2, 3]);
  11769. * // => true
  11770. *
  11771. * _.isObject(_.noop);
  11772. * // => true
  11773. *
  11774. * _.isObject(null);
  11775. * // => false
  11776. */
  11777. function isObject(value) {
  11778. var type = typeof value;
  11779. return !!value && (type == 'object' || type == 'function');
  11780. }
  11781. /**
  11782. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11783. * and has a `typeof` result of "object".
  11784. *
  11785. * @static
  11786. * @memberOf _
  11787. * @category Lang
  11788. * @param {*} value The value to check.
  11789. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11790. * @example
  11791. *
  11792. * _.isObjectLike({});
  11793. * // => true
  11794. *
  11795. * _.isObjectLike([1, 2, 3]);
  11796. * // => true
  11797. *
  11798. * _.isObjectLike(_.noop);
  11799. * // => false
  11800. *
  11801. * _.isObjectLike(null);
  11802. * // => false
  11803. */
  11804. function isObjectLike(value) {
  11805. return !!value && typeof value == 'object';
  11806. }
  11807. module.exports = isArguments;
  11808. },{}],56:[function(_dereq_,module,exports){
  11809. /**
  11810. * lodash 3.0.4 (Custom Build) <https://lodash.com/>
  11811. * Build: `lodash modern modularize exports="npm" -o ./`
  11812. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11813. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11814. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11815. * Available under MIT license <https://lodash.com/license>
  11816. */
  11817. /** `Object#toString` result references. */
  11818. var arrayTag = '[object Array]',
  11819. funcTag = '[object Function]';
  11820. /** Used to detect host constructors (Safari > 5). */
  11821. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  11822. /**
  11823. * Checks if `value` is object-like.
  11824. *
  11825. * @private
  11826. * @param {*} value The value to check.
  11827. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11828. */
  11829. function isObjectLike(value) {
  11830. return !!value && typeof value == 'object';
  11831. }
  11832. /** Used for native method references. */
  11833. var objectProto = Object.prototype;
  11834. /** Used to resolve the decompiled source of functions. */
  11835. var fnToString = Function.prototype.toString;
  11836. /** Used to check objects for own properties. */
  11837. var hasOwnProperty = objectProto.hasOwnProperty;
  11838. /**
  11839. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  11840. * of values.
  11841. */
  11842. var objToString = objectProto.toString;
  11843. /** Used to detect if a method is native. */
  11844. var reIsNative = RegExp('^' +
  11845. fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
  11846. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  11847. );
  11848. /* Native method references for those with the same name as other `lodash` methods. */
  11849. var nativeIsArray = getNative(Array, 'isArray');
  11850. /**
  11851. * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
  11852. * of an array-like value.
  11853. */
  11854. var MAX_SAFE_INTEGER = 9007199254740991;
  11855. /**
  11856. * Gets the native function at `key` of `object`.
  11857. *
  11858. * @private
  11859. * @param {Object} object The object to query.
  11860. * @param {string} key The key of the method to get.
  11861. * @returns {*} Returns the function if it's native, else `undefined`.
  11862. */
  11863. function getNative(object, key) {
  11864. var value = object == null ? undefined : object[key];
  11865. return isNative(value) ? value : undefined;
  11866. }
  11867. /**
  11868. * Checks if `value` is a valid array-like length.
  11869. *
  11870. * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  11871. *
  11872. * @private
  11873. * @param {*} value The value to check.
  11874. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  11875. */
  11876. function isLength(value) {
  11877. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  11878. }
  11879. /**
  11880. * Checks if `value` is classified as an `Array` object.
  11881. *
  11882. * @static
  11883. * @memberOf _
  11884. * @category Lang
  11885. * @param {*} value The value to check.
  11886. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  11887. * @example
  11888. *
  11889. * _.isArray([1, 2, 3]);
  11890. * // => true
  11891. *
  11892. * _.isArray(function() { return arguments; }());
  11893. * // => false
  11894. */
  11895. var isArray = nativeIsArray || function(value) {
  11896. return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
  11897. };
  11898. /**
  11899. * Checks if `value` is classified as a `Function` object.
  11900. *
  11901. * @static
  11902. * @memberOf _
  11903. * @category Lang
  11904. * @param {*} value The value to check.
  11905. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
  11906. * @example
  11907. *
  11908. * _.isFunction(_);
  11909. * // => true
  11910. *
  11911. * _.isFunction(/abc/);
  11912. * // => false
  11913. */
  11914. function isFunction(value) {
  11915. // The use of `Object#toString` avoids issues with the `typeof` operator
  11916. // in older versions of Chrome and Safari which return 'function' for regexes
  11917. // and Safari 8 equivalents which return 'object' for typed array constructors.
  11918. return isObject(value) && objToString.call(value) == funcTag;
  11919. }
  11920. /**
  11921. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  11922. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  11923. *
  11924. * @static
  11925. * @memberOf _
  11926. * @category Lang
  11927. * @param {*} value The value to check.
  11928. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  11929. * @example
  11930. *
  11931. * _.isObject({});
  11932. * // => true
  11933. *
  11934. * _.isObject([1, 2, 3]);
  11935. * // => true
  11936. *
  11937. * _.isObject(1);
  11938. * // => false
  11939. */
  11940. function isObject(value) {
  11941. // Avoid a V8 JIT bug in Chrome 19-20.
  11942. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  11943. var type = typeof value;
  11944. return !!value && (type == 'object' || type == 'function');
  11945. }
  11946. /**
  11947. * Checks if `value` is a native function.
  11948. *
  11949. * @static
  11950. * @memberOf _
  11951. * @category Lang
  11952. * @param {*} value The value to check.
  11953. * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
  11954. * @example
  11955. *
  11956. * _.isNative(Array.prototype.push);
  11957. * // => true
  11958. *
  11959. * _.isNative(_);
  11960. * // => false
  11961. */
  11962. function isNative(value) {
  11963. if (value == null) {
  11964. return false;
  11965. }
  11966. if (isFunction(value)) {
  11967. return reIsNative.test(fnToString.call(value));
  11968. }
  11969. return isObjectLike(value) && reIsHostCtor.test(value);
  11970. }
  11971. module.exports = isArray;
  11972. },{}],57:[function(_dereq_,module,exports){
  11973. /**
  11974. * lodash 3.2.0 (Custom Build) <https://lodash.com/>
  11975. * Build: `lodash modern modularize exports="npm" -o ./`
  11976. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  11977. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11978. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11979. * Available under MIT license <https://lodash.com/license>
  11980. */
  11981. var baseFor = _dereq_('lodash._basefor'),
  11982. isArguments = _dereq_('lodash.isarguments'),
  11983. keysIn = _dereq_('lodash.keysin');
  11984. /** `Object#toString` result references. */
  11985. var objectTag = '[object Object]';
  11986. /**
  11987. * Checks if `value` is object-like.
  11988. *
  11989. * @private
  11990. * @param {*} value The value to check.
  11991. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11992. */
  11993. function isObjectLike(value) {
  11994. return !!value && typeof value == 'object';
  11995. }
  11996. /** Used for native method references. */
  11997. var objectProto = Object.prototype;
  11998. /** Used to check objects for own properties. */
  11999. var hasOwnProperty = objectProto.hasOwnProperty;
  12000. /**
  12001. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  12002. * of values.
  12003. */
  12004. var objToString = objectProto.toString;
  12005. /**
  12006. * The base implementation of `_.forIn` without support for callback
  12007. * shorthands and `this` binding.
  12008. *
  12009. * @private
  12010. * @param {Object} object The object to iterate over.
  12011. * @param {Function} iteratee The function invoked per iteration.
  12012. * @returns {Object} Returns `object`.
  12013. */
  12014. function baseForIn(object, iteratee) {
  12015. return baseFor(object, iteratee, keysIn);
  12016. }
  12017. /**
  12018. * Checks if `value` is a plain object, that is, an object created by the
  12019. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  12020. *
  12021. * **Note:** This method assumes objects created by the `Object` constructor
  12022. * have no inherited enumerable properties.
  12023. *
  12024. * @static
  12025. * @memberOf _
  12026. * @category Lang
  12027. * @param {*} value The value to check.
  12028. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  12029. * @example
  12030. *
  12031. * function Foo() {
  12032. * this.a = 1;
  12033. * }
  12034. *
  12035. * _.isPlainObject(new Foo);
  12036. * // => false
  12037. *
  12038. * _.isPlainObject([1, 2, 3]);
  12039. * // => false
  12040. *
  12041. * _.isPlainObject({ 'x': 0, 'y': 0 });
  12042. * // => true
  12043. *
  12044. * _.isPlainObject(Object.create(null));
  12045. * // => true
  12046. */
  12047. function isPlainObject(value) {
  12048. var Ctor;
  12049. // Exit early for non `Object` objects.
  12050. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
  12051. (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
  12052. return false;
  12053. }
  12054. // IE < 9 iterates inherited properties before own properties. If the first
  12055. // iterated property is an object's own property then there are no inherited
  12056. // enumerable properties.
  12057. var result;
  12058. // In most environments an object's own properties are iterated before
  12059. // its inherited properties. If the last iterated property is an object's
  12060. // own property then there are no inherited enumerable properties.
  12061. baseForIn(value, function(subValue, key) {
  12062. result = key;
  12063. });
  12064. return result === undefined || hasOwnProperty.call(value, result);
  12065. }
  12066. module.exports = isPlainObject;
  12067. },{"lodash._basefor":58,"lodash.isarguments":55,"lodash.keysin":61}],58:[function(_dereq_,module,exports){
  12068. /**
  12069. * lodash 3.0.3 (Custom Build) <https://lodash.com/>
  12070. * Build: `lodash modularize exports="npm" -o ./`
  12071. * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
  12072. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12073. * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12074. * Available under MIT license <https://lodash.com/license>
  12075. */
  12076. /**
  12077. * The base implementation of `baseForIn` and `baseForOwn` which iterates
  12078. * over `object` properties returned by `keysFunc` invoking `iteratee` for
  12079. * each property. Iteratee functions may exit iteration early by explicitly
  12080. * returning `false`.
  12081. *
  12082. * @private
  12083. * @param {Object} object The object to iterate over.
  12084. * @param {Function} iteratee The function invoked per iteration.
  12085. * @param {Function} keysFunc The function to get the keys of `object`.
  12086. * @returns {Object} Returns `object`.
  12087. */
  12088. var baseFor = createBaseFor();
  12089. /**
  12090. * Creates a base function for methods like `_.forIn`.
  12091. *
  12092. * @private
  12093. * @param {boolean} [fromRight] Specify iterating from right to left.
  12094. * @returns {Function} Returns the new base function.
  12095. */
  12096. function createBaseFor(fromRight) {
  12097. return function(object, iteratee, keysFunc) {
  12098. var index = -1,
  12099. iterable = Object(object),
  12100. props = keysFunc(object),
  12101. length = props.length;
  12102. while (length--) {
  12103. var key = props[fromRight ? length : ++index];
  12104. if (iteratee(iterable[key], key, iterable) === false) {
  12105. break;
  12106. }
  12107. }
  12108. return object;
  12109. };
  12110. }
  12111. module.exports = baseFor;
  12112. },{}],59:[function(_dereq_,module,exports){
  12113. /**
  12114. * lodash 3.0.6 (Custom Build) <https://lodash.com/>
  12115. * Build: `lodash modularize exports="npm" -o ./`
  12116. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  12117. * Released under MIT license <https://lodash.com/license>
  12118. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12119. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12120. */
  12121. /** Used as references for various `Number` constants. */
  12122. var MAX_SAFE_INTEGER = 9007199254740991;
  12123. /** `Object#toString` result references. */
  12124. var argsTag = '[object Arguments]',
  12125. arrayTag = '[object Array]',
  12126. boolTag = '[object Boolean]',
  12127. dateTag = '[object Date]',
  12128. errorTag = '[object Error]',
  12129. funcTag = '[object Function]',
  12130. mapTag = '[object Map]',
  12131. numberTag = '[object Number]',
  12132. objectTag = '[object Object]',
  12133. regexpTag = '[object RegExp]',
  12134. setTag = '[object Set]',
  12135. stringTag = '[object String]',
  12136. weakMapTag = '[object WeakMap]';
  12137. var arrayBufferTag = '[object ArrayBuffer]',
  12138. dataViewTag = '[object DataView]',
  12139. float32Tag = '[object Float32Array]',
  12140. float64Tag = '[object Float64Array]',
  12141. int8Tag = '[object Int8Array]',
  12142. int16Tag = '[object Int16Array]',
  12143. int32Tag = '[object Int32Array]',
  12144. uint8Tag = '[object Uint8Array]',
  12145. uint8ClampedTag = '[object Uint8ClampedArray]',
  12146. uint16Tag = '[object Uint16Array]',
  12147. uint32Tag = '[object Uint32Array]';
  12148. /** Used to identify `toStringTag` values of typed arrays. */
  12149. var typedArrayTags = {};
  12150. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  12151. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  12152. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  12153. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  12154. typedArrayTags[uint32Tag] = true;
  12155. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  12156. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  12157. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  12158. typedArrayTags[errorTag] = typedArrayTags[funcTag] =
  12159. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  12160. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  12161. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  12162. typedArrayTags[weakMapTag] = false;
  12163. /** Used for built-in method references. */
  12164. var objectProto = Object.prototype;
  12165. /**
  12166. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  12167. * of values.
  12168. */
  12169. var objectToString = objectProto.toString;
  12170. /**
  12171. * Checks if `value` is a valid array-like length.
  12172. *
  12173. * **Note:** This function is loosely based on
  12174. * [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  12175. *
  12176. * @static
  12177. * @memberOf _
  12178. * @since 4.0.0
  12179. * @category Lang
  12180. * @param {*} value The value to check.
  12181. * @returns {boolean} Returns `true` if `value` is a valid length,
  12182. * else `false`.
  12183. * @example
  12184. *
  12185. * _.isLength(3);
  12186. * // => true
  12187. *
  12188. * _.isLength(Number.MIN_VALUE);
  12189. * // => false
  12190. *
  12191. * _.isLength(Infinity);
  12192. * // => false
  12193. *
  12194. * _.isLength('3');
  12195. * // => false
  12196. */
  12197. function isLength(value) {
  12198. return typeof value == 'number' &&
  12199. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  12200. }
  12201. /**
  12202. * Checks if `value` is object-like. A value is object-like if it's not `null`
  12203. * and has a `typeof` result of "object".
  12204. *
  12205. * @static
  12206. * @memberOf _
  12207. * @since 4.0.0
  12208. * @category Lang
  12209. * @param {*} value The value to check.
  12210. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  12211. * @example
  12212. *
  12213. * _.isObjectLike({});
  12214. * // => true
  12215. *
  12216. * _.isObjectLike([1, 2, 3]);
  12217. * // => true
  12218. *
  12219. * _.isObjectLike(_.noop);
  12220. * // => false
  12221. *
  12222. * _.isObjectLike(null);
  12223. * // => false
  12224. */
  12225. function isObjectLike(value) {
  12226. return !!value && typeof value == 'object';
  12227. }
  12228. /**
  12229. * Checks if `value` is classified as a typed array.
  12230. *
  12231. * @static
  12232. * @memberOf _
  12233. * @since 3.0.0
  12234. * @category Lang
  12235. * @param {*} value The value to check.
  12236. * @returns {boolean} Returns `true` if `value` is correctly classified,
  12237. * else `false`.
  12238. * @example
  12239. *
  12240. * _.isTypedArray(new Uint8Array);
  12241. * // => true
  12242. *
  12243. * _.isTypedArray([]);
  12244. * // => false
  12245. */
  12246. function isTypedArray(value) {
  12247. return isObjectLike(value) &&
  12248. isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
  12249. }
  12250. module.exports = isTypedArray;
  12251. },{}],60:[function(_dereq_,module,exports){
  12252. /**
  12253. * lodash 3.1.2 (Custom Build) <https://lodash.com/>
  12254. * Build: `lodash modern modularize exports="npm" -o ./`
  12255. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  12256. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12257. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12258. * Available under MIT license <https://lodash.com/license>
  12259. */
  12260. var getNative = _dereq_('lodash._getnative'),
  12261. isArguments = _dereq_('lodash.isarguments'),
  12262. isArray = _dereq_('lodash.isarray');
  12263. /** Used to detect unsigned integer values. */
  12264. var reIsUint = /^\d+$/;
  12265. /** Used for native method references. */
  12266. var objectProto = Object.prototype;
  12267. /** Used to check objects for own properties. */
  12268. var hasOwnProperty = objectProto.hasOwnProperty;
  12269. /* Native method references for those with the same name as other `lodash` methods. */
  12270. var nativeKeys = getNative(Object, 'keys');
  12271. /**
  12272. * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
  12273. * of an array-like value.
  12274. */
  12275. var MAX_SAFE_INTEGER = 9007199254740991;
  12276. /**
  12277. * The base implementation of `_.property` without support for deep paths.
  12278. *
  12279. * @private
  12280. * @param {string} key The key of the property to get.
  12281. * @returns {Function} Returns the new function.
  12282. */
  12283. function baseProperty(key) {
  12284. return function(object) {
  12285. return object == null ? undefined : object[key];
  12286. };
  12287. }
  12288. /**
  12289. * Gets the "length" property value of `object`.
  12290. *
  12291. * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
  12292. * that affects Safari on at least iOS 8.1-8.3 ARM64.
  12293. *
  12294. * @private
  12295. * @param {Object} object The object to query.
  12296. * @returns {*} Returns the "length" value.
  12297. */
  12298. var getLength = baseProperty('length');
  12299. /**
  12300. * Checks if `value` is array-like.
  12301. *
  12302. * @private
  12303. * @param {*} value The value to check.
  12304. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  12305. */
  12306. function isArrayLike(value) {
  12307. return value != null && isLength(getLength(value));
  12308. }
  12309. /**
  12310. * Checks if `value` is a valid array-like index.
  12311. *
  12312. * @private
  12313. * @param {*} value The value to check.
  12314. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  12315. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  12316. */
  12317. function isIndex(value, length) {
  12318. value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
  12319. length = length == null ? MAX_SAFE_INTEGER : length;
  12320. return value > -1 && value % 1 == 0 && value < length;
  12321. }
  12322. /**
  12323. * Checks if `value` is a valid array-like length.
  12324. *
  12325. * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
  12326. *
  12327. * @private
  12328. * @param {*} value The value to check.
  12329. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  12330. */
  12331. function isLength(value) {
  12332. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  12333. }
  12334. /**
  12335. * A fallback implementation of `Object.keys` which creates an array of the
  12336. * own enumerable property names of `object`.
  12337. *
  12338. * @private
  12339. * @param {Object} object The object to query.
  12340. * @returns {Array} Returns the array of property names.
  12341. */
  12342. function shimKeys(object) {
  12343. var props = keysIn(object),
  12344. propsLength = props.length,
  12345. length = propsLength && object.length;
  12346. var allowIndexes = !!length && isLength(length) &&
  12347. (isArray(object) || isArguments(object));
  12348. var index = -1,
  12349. result = [];
  12350. while (++index < propsLength) {
  12351. var key = props[index];
  12352. if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
  12353. result.push(key);
  12354. }
  12355. }
  12356. return result;
  12357. }
  12358. /**
  12359. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  12360. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  12361. *
  12362. * @static
  12363. * @memberOf _
  12364. * @category Lang
  12365. * @param {*} value The value to check.
  12366. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  12367. * @example
  12368. *
  12369. * _.isObject({});
  12370. * // => true
  12371. *
  12372. * _.isObject([1, 2, 3]);
  12373. * // => true
  12374. *
  12375. * _.isObject(1);
  12376. * // => false
  12377. */
  12378. function isObject(value) {
  12379. // Avoid a V8 JIT bug in Chrome 19-20.
  12380. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  12381. var type = typeof value;
  12382. return !!value && (type == 'object' || type == 'function');
  12383. }
  12384. /**
  12385. * Creates an array of the own enumerable property names of `object`.
  12386. *
  12387. * **Note:** Non-object values are coerced to objects. See the
  12388. * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
  12389. * for more details.
  12390. *
  12391. * @static
  12392. * @memberOf _
  12393. * @category Object
  12394. * @param {Object} object The object to query.
  12395. * @returns {Array} Returns the array of property names.
  12396. * @example
  12397. *
  12398. * function Foo() {
  12399. * this.a = 1;
  12400. * this.b = 2;
  12401. * }
  12402. *
  12403. * Foo.prototype.c = 3;
  12404. *
  12405. * _.keys(new Foo);
  12406. * // => ['a', 'b'] (iteration order is not guaranteed)
  12407. *
  12408. * _.keys('hi');
  12409. * // => ['0', '1']
  12410. */
  12411. var keys = !nativeKeys ? shimKeys : function(object) {
  12412. var Ctor = object == null ? undefined : object.constructor;
  12413. if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
  12414. (typeof object != 'function' && isArrayLike(object))) {
  12415. return shimKeys(object);
  12416. }
  12417. return isObject(object) ? nativeKeys(object) : [];
  12418. };
  12419. /**
  12420. * Creates an array of the own and inherited enumerable property names of `object`.
  12421. *
  12422. * **Note:** Non-object values are coerced to objects.
  12423. *
  12424. * @static
  12425. * @memberOf _
  12426. * @category Object
  12427. * @param {Object} object The object to query.
  12428. * @returns {Array} Returns the array of property names.
  12429. * @example
  12430. *
  12431. * function Foo() {
  12432. * this.a = 1;
  12433. * this.b = 2;
  12434. * }
  12435. *
  12436. * Foo.prototype.c = 3;
  12437. *
  12438. * _.keysIn(new Foo);
  12439. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  12440. */
  12441. function keysIn(object) {
  12442. if (object == null) {
  12443. return [];
  12444. }
  12445. if (!isObject(object)) {
  12446. object = Object(object);
  12447. }
  12448. var length = object.length;
  12449. length = (length && isLength(length) &&
  12450. (isArray(object) || isArguments(object)) && length) || 0;
  12451. var Ctor = object.constructor,
  12452. index = -1,
  12453. isProto = typeof Ctor == 'function' && Ctor.prototype === object,
  12454. result = Array(length),
  12455. skipIndexes = length > 0;
  12456. while (++index < length) {
  12457. result[index] = (index + '');
  12458. }
  12459. for (var key in object) {
  12460. if (!(skipIndexes && isIndex(key, length)) &&
  12461. !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
  12462. result.push(key);
  12463. }
  12464. }
  12465. return result;
  12466. }
  12467. module.exports = keys;
  12468. },{"lodash._getnative":54,"lodash.isarguments":55,"lodash.isarray":56}],61:[function(_dereq_,module,exports){
  12469. /**
  12470. * lodash 3.0.8 (Custom Build) <https://lodash.com/>
  12471. * Build: `lodash modern modularize exports="npm" -o ./`
  12472. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  12473. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12474. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12475. * Available under MIT license <https://lodash.com/license>
  12476. */
  12477. var isArguments = _dereq_('lodash.isarguments'),
  12478. isArray = _dereq_('lodash.isarray');
  12479. /** Used to detect unsigned integer values. */
  12480. var reIsUint = /^\d+$/;
  12481. /** Used for native method references. */
  12482. var objectProto = Object.prototype;
  12483. /** Used to check objects for own properties. */
  12484. var hasOwnProperty = objectProto.hasOwnProperty;
  12485. /**
  12486. * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
  12487. * of an array-like value.
  12488. */
  12489. var MAX_SAFE_INTEGER = 9007199254740991;
  12490. /**
  12491. * Checks if `value` is a valid array-like index.
  12492. *
  12493. * @private
  12494. * @param {*} value The value to check.
  12495. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  12496. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  12497. */
  12498. function isIndex(value, length) {
  12499. value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
  12500. length = length == null ? MAX_SAFE_INTEGER : length;
  12501. return value > -1 && value % 1 == 0 && value < length;
  12502. }
  12503. /**
  12504. * Checks if `value` is a valid array-like length.
  12505. *
  12506. * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
  12507. *
  12508. * @private
  12509. * @param {*} value The value to check.
  12510. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  12511. */
  12512. function isLength(value) {
  12513. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  12514. }
  12515. /**
  12516. * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
  12517. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  12518. *
  12519. * @static
  12520. * @memberOf _
  12521. * @category Lang
  12522. * @param {*} value The value to check.
  12523. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  12524. * @example
  12525. *
  12526. * _.isObject({});
  12527. * // => true
  12528. *
  12529. * _.isObject([1, 2, 3]);
  12530. * // => true
  12531. *
  12532. * _.isObject(1);
  12533. * // => false
  12534. */
  12535. function isObject(value) {
  12536. // Avoid a V8 JIT bug in Chrome 19-20.
  12537. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  12538. var type = typeof value;
  12539. return !!value && (type == 'object' || type == 'function');
  12540. }
  12541. /**
  12542. * Creates an array of the own and inherited enumerable property names of `object`.
  12543. *
  12544. * **Note:** Non-object values are coerced to objects.
  12545. *
  12546. * @static
  12547. * @memberOf _
  12548. * @category Object
  12549. * @param {Object} object The object to query.
  12550. * @returns {Array} Returns the array of property names.
  12551. * @example
  12552. *
  12553. * function Foo() {
  12554. * this.a = 1;
  12555. * this.b = 2;
  12556. * }
  12557. *
  12558. * Foo.prototype.c = 3;
  12559. *
  12560. * _.keysIn(new Foo);
  12561. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  12562. */
  12563. function keysIn(object) {
  12564. if (object == null) {
  12565. return [];
  12566. }
  12567. if (!isObject(object)) {
  12568. object = Object(object);
  12569. }
  12570. var length = object.length;
  12571. length = (length && isLength(length) &&
  12572. (isArray(object) || isArguments(object)) && length) || 0;
  12573. var Ctor = object.constructor,
  12574. index = -1,
  12575. isProto = typeof Ctor == 'function' && Ctor.prototype === object,
  12576. result = Array(length),
  12577. skipIndexes = length > 0;
  12578. while (++index < length) {
  12579. result[index] = (index + '');
  12580. }
  12581. for (var key in object) {
  12582. if (!(skipIndexes && isIndex(key, length)) &&
  12583. !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
  12584. result.push(key);
  12585. }
  12586. }
  12587. return result;
  12588. }
  12589. module.exports = keysIn;
  12590. },{"lodash.isarguments":55,"lodash.isarray":56}],62:[function(_dereq_,module,exports){
  12591. /**
  12592. * lodash 3.0.0 (Custom Build) <https://lodash.com/>
  12593. * Build: `lodash modern modularize exports="npm" -o ./`
  12594. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  12595. * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
  12596. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12597. * Available under MIT license <https://lodash.com/license>
  12598. */
  12599. var baseCopy = _dereq_('lodash._basecopy'),
  12600. keysIn = _dereq_('lodash.keysin');
  12601. /**
  12602. * Converts `value` to a plain object flattening inherited enumerable
  12603. * properties of `value` to own properties of the plain object.
  12604. *
  12605. * @static
  12606. * @memberOf _
  12607. * @category Lang
  12608. * @param {*} value The value to convert.
  12609. * @returns {Object} Returns the converted plain object.
  12610. * @example
  12611. *
  12612. * function Foo() {
  12613. * this.b = 2;
  12614. * }
  12615. *
  12616. * Foo.prototype.c = 3;
  12617. *
  12618. * _.assign({ 'a': 1 }, new Foo);
  12619. * // => { 'a': 1, 'b': 2 }
  12620. *
  12621. * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
  12622. * // => { 'a': 1, 'b': 2, 'c': 3 }
  12623. */
  12624. function toPlainObject(value) {
  12625. return baseCopy(value, keysIn(value));
  12626. }
  12627. module.exports = toPlainObject;
  12628. },{"lodash._basecopy":63,"lodash.keysin":61}],63:[function(_dereq_,module,exports){
  12629. /**
  12630. * lodash 3.0.1 (Custom Build) <https://lodash.com/>
  12631. * Build: `lodash modern modularize exports="npm" -o ./`
  12632. * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
  12633. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  12634. * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  12635. * Available under MIT license <https://lodash.com/license>
  12636. */
  12637. /**
  12638. * Copies properties of `source` to `object`.
  12639. *
  12640. * @private
  12641. * @param {Object} source The object to copy properties from.
  12642. * @param {Array} props The property names to copy.
  12643. * @param {Object} [object={}] The object to copy properties to.
  12644. * @returns {Object} Returns `object`.
  12645. */
  12646. function baseCopy(source, props, object) {
  12647. object || (object = {});
  12648. var index = -1,
  12649. length = props.length;
  12650. while (++index < length) {
  12651. var key = props[index];
  12652. object[key] = source[key];
  12653. }
  12654. return object;
  12655. }
  12656. module.exports = baseCopy;
  12657. },{}],64:[function(_dereq_,module,exports){
  12658. var JSZip, fs, internal;
  12659. JSZip = _dereq_('jszip');
  12660. internal = _dereq_('./internal');
  12661. module.exports = {
  12662. asBlob: function(html, options) {
  12663. var zip;
  12664. zip = new JSZip();
  12665. internal.addFiles(zip, html, options);
  12666. return internal.generateDocument(zip);
  12667. }
  12668. };
  12669. },{"./internal":65,"jszip":14}],65:[function(_dereq_,module,exports){
  12670. (function (global,Buffer){
  12671. var documentTemplate, fs, utils, _;
  12672. documentTemplate = _dereq_('./templates/document');
  12673. utils = _dereq_('./utils');
  12674. _ = {
  12675. merge: _dereq_('lodash.merge')
  12676. };
  12677. module.exports = {
  12678. generateDocument: function(zip) {
  12679. var buffer;
  12680. buffer = zip.generate({
  12681. type: 'arraybuffer'
  12682. });
  12683. if (global.Blob) {
  12684. return new Blob([buffer], {
  12685. type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  12686. });
  12687. } else if (global.Buffer) {
  12688. return new Buffer(new Uint8Array(buffer));
  12689. } else {
  12690. throw new Error("Neither Blob nor Buffer are accessible in this environment. " + "Consider adding Blob.js shim");
  12691. }
  12692. },
  12693. renderDocumentFile: function(documentOptions) {
  12694. var templateData;
  12695. if (documentOptions == null) {
  12696. documentOptions = {};
  12697. }
  12698. templateData = _.merge({
  12699. margins: {
  12700. top: 1440,
  12701. right: 1440,
  12702. bottom: 1440,
  12703. left: 1440,
  12704. header: 720,
  12705. footer: 720,
  12706. gutter: 0
  12707. }
  12708. }, (function() {
  12709. switch (documentOptions.orientation) {
  12710. case 'landscape':
  12711. return {
  12712. height: 12240,
  12713. width: 15840,
  12714. orient: 'landscape'
  12715. };
  12716. default:
  12717. return {
  12718. width: 12240,
  12719. height: 15840,
  12720. orient: 'portrait'
  12721. };
  12722. }
  12723. })(), {
  12724. margins: documentOptions.margins
  12725. });
  12726. return documentTemplate(templateData);
  12727. },
  12728. addFiles: function(zip, htmlSource, documentOptions) {
  12729. zip.file('[Content_Types].xml', Buffer("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/Pgo8VHlwZXMgeG1sbnM9Imh0dHA6Ly9zY2hlbWFzLm9wZW54bWxmb3JtYXRzLm9yZy9wYWNrYWdlLzIwMDYvY29udGVudC10eXBlcyI+CiAgPERlZmF1bHQgRXh0ZW5zaW9uPSJyZWxzIiBDb250ZW50VHlwZT0KICAgICJhcHBsaWNhdGlvbi92bmQub3BlbnhtbGZvcm1hdHMtcGFja2FnZS5yZWxhdGlvbnNoaXBzK3htbCIgLz4KICA8T3ZlcnJpZGUgUGFydE5hbWU9Ii93b3JkL2RvY3VtZW50LnhtbCIgQ29udGVudFR5cGU9CiAgICAiYXBwbGljYXRpb24vdm5kLm9wZW54bWxmb3JtYXRzLW9mZmljZWRvY3VtZW50LndvcmRwcm9jZXNzaW5nbWwuZG9jdW1lbnQubWFpbit4bWwiLz4KICA8T3ZlcnJpZGUgUGFydE5hbWU9Ii93b3JkL2FmY2h1bmsubWh0IiBDb250ZW50VHlwZT0ibWVzc2FnZS9yZmM4MjIiLz4KPC9UeXBlcz4K","base64"));
  12730. zip.folder('_rels').file('.rels', Buffer("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/Pgo8UmVsYXRpb25zaGlwcyB4bWxucz0iaHR0cDovL3NjaGVtYXMub3BlbnhtbGZvcm1hdHMub3JnL3BhY2thZ2UvMjAwNi9yZWxhdGlvbnNoaXBzIj4KICA8UmVsYXRpb25zaGlwCiAgICAgIFR5cGU9Imh0dHA6Ly9zY2hlbWFzLm9wZW54bWxmb3JtYXRzLm9yZy9vZmZpY2VEb2N1bWVudC8yMDA2L3JlbGF0aW9uc2hpcHMvb2ZmaWNlRG9jdW1lbnQiCiAgICAgIFRhcmdldD0iL3dvcmQvZG9jdW1lbnQueG1sIiBJZD0iUjA5YzgzZmFmYzA2NzQ4OGUiIC8+CjwvUmVsYXRpb25zaGlwcz4K","base64"));
  12731. 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"));
  12732. }
  12733. };
  12734. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer)
  12735. },{"./templates/document":66,"./utils":69,"buffer":1,"lodash.merge":47}],66:[function(_dereq_,module,exports){
  12736. var _ = {escape: _dereq_("lodash.escape")};
  12737. module.exports = function(obj){
  12738. var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
  12739. with(obj||{}){
  12740. __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="'+
  12741. ((__t=( width ))==null?'':__t)+
  12742. '" w:h="'+
  12743. ((__t=( height ))==null?'':__t)+
  12744. '" w:orient="'+
  12745. ((__t=( orient ))==null?'':__t)+
  12746. '" />\n <w:pgMar w:top="'+
  12747. ((__t=( margins.top ))==null?'':__t)+
  12748. '"\n w:right="'+
  12749. ((__t=( margins.right ))==null?'':__t)+
  12750. '"\n w:bottom="'+
  12751. ((__t=( margins.bottom ))==null?'':__t)+
  12752. '"\n w:left="'+
  12753. ((__t=( margins.left ))==null?'':__t)+
  12754. '"\n w:header="'+
  12755. ((__t=( margins.header ))==null?'':__t)+
  12756. '"\n w:footer="'+
  12757. ((__t=( margins.footer ))==null?'':__t)+
  12758. '"\n w:gutter="'+
  12759. ((__t=( margins.gutter ))==null?'':__t)+
  12760. '"/>\n </w:sectPr>\n </w:body>\n</w:document>\n';
  12761. }
  12762. return __p;
  12763. };
  12764. },{"lodash.escape":45}],67:[function(_dereq_,module,exports){
  12765. var _ = {escape: _dereq_("lodash.escape")};
  12766. module.exports = function(obj){
  12767. var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
  12768. with(obj||{}){
  12769. __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'+
  12770. ((__t=( htmlSource ))==null?'':__t)+
  12771. '\n\n'+
  12772. ((__t=( contentParts ))==null?'':__t)+
  12773. '\n\n------=mhtDocumentPart--\n';
  12774. }
  12775. return __p;
  12776. };
  12777. },{"lodash.escape":45}],68:[function(_dereq_,module,exports){
  12778. var _ = {escape: _dereq_("lodash.escape")};
  12779. module.exports = function(obj){
  12780. var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
  12781. with(obj||{}){
  12782. __p+='------=mhtDocumentPart\nContent-Type: '+
  12783. ((__t=( contentType ))==null?'':__t)+
  12784. '\nContent-Transfer-Encoding: '+
  12785. ((__t=( contentEncoding ))==null?'':__t)+
  12786. '\nContent-Location: '+
  12787. ((__t=( contentLocation ))==null?'':__t)+
  12788. '\n\n'+
  12789. ((__t=( encodedContent ))==null?'':__t)+
  12790. '\n';
  12791. }
  12792. return __p;
  12793. };
  12794. },{"lodash.escape":45}],69:[function(_dereq_,module,exports){
  12795. var mhtDocumentTemplate, mhtPartTemplate;
  12796. mhtDocumentTemplate = _dereq_('./templates/mht_document');
  12797. mhtPartTemplate = _dereq_('./templates/mht_part');
  12798. module.exports = {
  12799. getMHTdocument: function(htmlSource) {
  12800. var imageContentParts, _ref;
  12801. _ref = this._prepareImageParts(htmlSource), htmlSource = _ref.htmlSource, imageContentParts = _ref.imageContentParts;
  12802. htmlSource = htmlSource.replace(/\=/g, '=3D');
  12803. return mhtDocumentTemplate({
  12804. htmlSource: htmlSource,
  12805. contentParts: imageContentParts.join('\n')
  12806. });
  12807. },
  12808. _prepareImageParts: function(htmlSource) {
  12809. var imageContentParts, inlinedReplacer, inlinedSrcPattern;
  12810. imageContentParts = [];
  12811. inlinedSrcPattern = /"data:(\w+\/\w+);(\w+),(\S+)"/g;
  12812. inlinedReplacer = function(match, contentType, contentEncoding, encodedContent) {
  12813. var contentLocation, extension, index;
  12814. index = imageContentParts.length;
  12815. extension = contentType.split('/')[1];
  12816. contentLocation = "file:///C:/fake/image" + index + "." + extension;
  12817. imageContentParts.push(mhtPartTemplate({
  12818. contentType: contentType,
  12819. contentEncoding: contentEncoding,
  12820. contentLocation: contentLocation,
  12821. encodedContent: encodedContent
  12822. }));
  12823. return "\"" + contentLocation + "\"";
  12824. };
  12825. if (typeof htmlSource === 'string') {
  12826. if (!/<img/g.test(htmlSource)) {
  12827. return {
  12828. htmlSource: htmlSource,
  12829. imageContentParts: imageContentParts
  12830. };
  12831. }
  12832. htmlSource = htmlSource.replace(inlinedSrcPattern, inlinedReplacer);
  12833. return {
  12834. htmlSource: htmlSource,
  12835. imageContentParts: imageContentParts
  12836. };
  12837. } else {
  12838. throw new Error("Not a valid source provided!");
  12839. }
  12840. }
  12841. };
  12842. },{"./templates/mht_document":67,"./templates/mht_part":68}]},{},[64])
  12843. (64)
  12844. });
  12845. /***/ }),
  12846. /***/ "Uxkr":
  12847. /***/ (function(module, exports) {
  12848. // removed by extract-text-webpack-plugin
  12849. /***/ }),
  12850. /***/ "faOw":
  12851. /***/ (function(module, exports, __webpack_require__) {
  12852. var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
  12853. * Simditor v2.3.6
  12854. * http://simditor.tower.im/
  12855. * 2015-12-21
  12856. */
  12857. (function (root, factory) {
  12858. if (true) {
  12859. // AMD. Register as an anonymous module unless amdModuleId is set
  12860. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__("4kSj"),__webpack_require__("580I"),__webpack_require__("5IXW"),__webpack_require__("Cmgq")], __WEBPACK_AMD_DEFINE_RESULT__ = (function ($, SimpleModule, simpleHotkeys, simpleUploader) {
  12861. return (root['Simditor'] = factory($, SimpleModule, simpleHotkeys, simpleUploader));
  12862. }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
  12863. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  12864. } else if (typeof exports === 'object') {
  12865. // Node. Does not work with strict CommonJS, but
  12866. // only CommonJS-like environments that support module.exports,
  12867. // like Node.
  12868. module.exports = factory(require("jquery"),require("simple-module"),require("simple-hotkeys"),require("simple-uploader"));
  12869. } else {
  12870. root['Simditor'] = factory(jQuery,SimpleModule,simple.hotkeys,simple.uploader);
  12871. }
  12872. }(this, function ($, SimpleModule, simpleHotkeys, simpleUploader) {
  12873. var AlignmentButton, BlockquoteButton, BoldButton, Button, Clipboard, CodeButton, CodePopover, ColorButton, FontScaleButton, Formatter, HrButton, ImageButton, ImagePopover, IndentButton, Indentation, InputManager, ItalicButton, Keystroke, LinkButton, LinkPopover, ListButton, OrderListButton, OutdentButton, Popover, Selection, Simditor, StrikethroughButton, TableButton, TitleButton, Toolbar, UnderlineButton, UndoManager, UnorderListButton, Util,
  12874. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  12875. hasProp = {}.hasOwnProperty,
  12876. indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
  12877. slice = [].slice;
  12878. Selection = (function(superClass) {
  12879. extend(Selection, superClass);
  12880. function Selection() {
  12881. return Selection.__super__.constructor.apply(this, arguments);
  12882. }
  12883. Selection.pluginName = 'Selection';
  12884. Selection.prototype._range = null;
  12885. Selection.prototype._startNodes = null;
  12886. Selection.prototype._endNodes = null;
  12887. Selection.prototype._containerNode = null;
  12888. Selection.prototype._nodes = null;
  12889. Selection.prototype._blockNodes = null;
  12890. Selection.prototype._rootNodes = null;
  12891. Selection.prototype._init = function() {
  12892. this.editor = this._module;
  12893. this._selection = document.getSelection();
  12894. this.editor.on('selectionchanged', (function(_this) {
  12895. return function(e) {
  12896. _this.reset();
  12897. return _this._range = _this._selection.getRangeAt(0);
  12898. };
  12899. })(this));
  12900. return this.editor.on('blur', (function(_this) {
  12901. return function(e) {
  12902. return _this.reset();
  12903. };
  12904. })(this));
  12905. };
  12906. Selection.prototype.reset = function() {
  12907. this._range = null;
  12908. this._startNodes = null;
  12909. this._endNodes = null;
  12910. this._containerNode = null;
  12911. this._nodes = null;
  12912. this._blockNodes = null;
  12913. return this._rootNodes = null;
  12914. };
  12915. Selection.prototype.clear = function() {
  12916. var e;
  12917. try {
  12918. this._selection.removeAllRanges();
  12919. } catch (_error) {
  12920. e = _error;
  12921. }
  12922. return this.reset();
  12923. };
  12924. Selection.prototype.range = function(range) {
  12925. var ffOrIE;
  12926. if (range) {
  12927. this.clear();
  12928. this._selection.addRange(range);
  12929. this._range = range;
  12930. ffOrIE = this.editor.util.browser.firefox || this.editor.util.browser.msie;
  12931. if (!this.editor.inputManager.focused && ffOrIE) {
  12932. this.editor.body.focus();
  12933. }
  12934. } else if (!this._range && this.editor.inputManager.focused && this._selection.rangeCount) {
  12935. this._range = this._selection.getRangeAt(0);
  12936. }
  12937. return this._range;
  12938. };
  12939. Selection.prototype.startNodes = function() {
  12940. if (this._range) {
  12941. this._startNodes || (this._startNodes = (function(_this) {
  12942. return function() {
  12943. var startNodes;
  12944. startNodes = $(_this._range.startContainer).parentsUntil(_this.editor.body).get();
  12945. startNodes.unshift(_this._range.startContainer);
  12946. return $(startNodes);
  12947. };
  12948. })(this)());
  12949. }
  12950. return this._startNodes;
  12951. };
  12952. Selection.prototype.endNodes = function() {
  12953. var endNodes;
  12954. if (this._range) {
  12955. this._endNodes || (this._endNodes = this._range.collapsed ? this.startNodes() : (endNodes = $(this._range.endContainer).parentsUntil(this.editor.body).get(), endNodes.unshift(this._range.endContainer), $(endNodes)));
  12956. }
  12957. return this._endNodes;
  12958. };
  12959. Selection.prototype.containerNode = function() {
  12960. if (this._range) {
  12961. this._containerNode || (this._containerNode = $(this._range.commonAncestorContainer));
  12962. }
  12963. return this._containerNode;
  12964. };
  12965. Selection.prototype.nodes = function() {
  12966. if (this._range) {
  12967. this._nodes || (this._nodes = (function(_this) {
  12968. return function() {
  12969. var nodes;
  12970. nodes = [];
  12971. if (_this.startNodes().first().is(_this.endNodes().first())) {
  12972. nodes = _this.startNodes().get();
  12973. } else {
  12974. _this.startNodes().each(function(i, node) {
  12975. var $endNode, $node, $nodes, endIndex, index, sharedIndex, startIndex;
  12976. $node = $(node);
  12977. if (_this.endNodes().index($node) > -1) {
  12978. return nodes.push(node);
  12979. } else if ($node.parent().is(_this.editor.body) || (sharedIndex = _this.endNodes().index($node.parent())) > -1) {
  12980. if (sharedIndex && sharedIndex > -1) {
  12981. $endNode = _this.endNodes().eq(sharedIndex - 1);
  12982. } else {
  12983. $endNode = _this.endNodes().last();
  12984. }
  12985. $nodes = $node.parent().contents();
  12986. startIndex = $nodes.index($node);
  12987. endIndex = $nodes.index($endNode);
  12988. return $.merge(nodes, $nodes.slice(startIndex, endIndex).get());
  12989. } else {
  12990. $nodes = $node.parent().contents();
  12991. index = $nodes.index($node);
  12992. return $.merge(nodes, $nodes.slice(index).get());
  12993. }
  12994. });
  12995. _this.endNodes().each(function(i, node) {
  12996. var $node, $nodes, index;
  12997. $node = $(node);
  12998. if ($node.parent().is(_this.editor.body) || _this.startNodes().index($node.parent()) > -1) {
  12999. nodes.push(node);
  13000. return false;
  13001. } else {
  13002. $nodes = $node.parent().contents();
  13003. index = $nodes.index($node);
  13004. return $.merge(nodes, $nodes.slice(0, index + 1));
  13005. }
  13006. });
  13007. }
  13008. return $($.unique(nodes));
  13009. };
  13010. })(this)());
  13011. }
  13012. return this._nodes;
  13013. };
  13014. Selection.prototype.blockNodes = function() {
  13015. if (!this._range) {
  13016. return;
  13017. }
  13018. this._blockNodes || (this._blockNodes = (function(_this) {
  13019. return function() {
  13020. return _this.nodes().filter(function(i, node) {
  13021. return _this.editor.util.isBlockNode(node);
  13022. });
  13023. };
  13024. })(this)());
  13025. return this._blockNodes;
  13026. };
  13027. Selection.prototype.rootNodes = function() {
  13028. if (!this._range) {
  13029. return;
  13030. }
  13031. this._rootNodes || (this._rootNodes = (function(_this) {
  13032. return function() {
  13033. return _this.nodes().filter(function(i, node) {
  13034. var $parent;
  13035. $parent = $(node).parent();
  13036. return $parent.is(_this.editor.body) || $parent.is('blockquote');
  13037. });
  13038. };
  13039. })(this)());
  13040. return this._rootNodes;
  13041. };
  13042. Selection.prototype.rangeAtEndOf = function(node, range) {
  13043. var afterLastNode, beforeLastNode, endNode, endNodeLength, lastNodeIsBr, result;
  13044. if (range == null) {
  13045. range = this.range();
  13046. }
  13047. if (!(range && range.collapsed)) {
  13048. return;
  13049. }
  13050. node = $(node)[0];
  13051. endNode = range.endContainer;
  13052. endNodeLength = this.editor.util.getNodeLength(endNode);
  13053. beforeLastNode = range.endOffset === endNodeLength - 1;
  13054. lastNodeIsBr = $(endNode).contents().last().is('br');
  13055. afterLastNode = range.endOffset === endNodeLength;
  13056. if (!((beforeLastNode && lastNodeIsBr) || afterLastNode)) {
  13057. return false;
  13058. }
  13059. if (node === endNode) {
  13060. return true;
  13061. } else if (!$.contains(node, endNode)) {
  13062. return false;
  13063. }
  13064. result = true;
  13065. $(endNode).parentsUntil(node).addBack().each(function(i, n) {
  13066. var $lastChild, beforeLastbr, isLastNode, nodes;
  13067. nodes = $(n).parent().contents().filter(function() {
  13068. return !(this !== n && this.nodeType === 3 && !this.nodeValue);
  13069. });
  13070. $lastChild = nodes.last();
  13071. isLastNode = $lastChild.get(0) === n;
  13072. beforeLastbr = $lastChild.is('br') && $lastChild.prev().get(0) === n;
  13073. if (!(isLastNode || beforeLastbr)) {
  13074. result = false;
  13075. return false;
  13076. }
  13077. });
  13078. return result;
  13079. };
  13080. Selection.prototype.rangeAtStartOf = function(node, range) {
  13081. var result, startNode;
  13082. if (range == null) {
  13083. range = this.range();
  13084. }
  13085. if (!(range && range.collapsed)) {
  13086. return;
  13087. }
  13088. node = $(node)[0];
  13089. startNode = range.startContainer;
  13090. if (range.startOffset !== 0) {
  13091. return false;
  13092. }
  13093. if (node === startNode) {
  13094. return true;
  13095. } else if (!$.contains(node, startNode)) {
  13096. return false;
  13097. }
  13098. result = true;
  13099. $(startNode).parentsUntil(node).addBack().each(function(i, n) {
  13100. var nodes;
  13101. nodes = $(n).parent().contents().filter(function() {
  13102. return !(this !== n && this.nodeType === 3 && !this.nodeValue);
  13103. });
  13104. if (nodes.first().get(0) !== n) {
  13105. return result = false;
  13106. }
  13107. });
  13108. return result;
  13109. };
  13110. Selection.prototype.insertNode = function(node, range) {
  13111. if (range == null) {
  13112. range = this.range();
  13113. }
  13114. if (!range) {
  13115. return;
  13116. }
  13117. node = $(node)[0];
  13118. range.insertNode(node);
  13119. return this.setRangeAfter(node, range);
  13120. };
  13121. Selection.prototype.setRangeAfter = function(node, range) {
  13122. if (range == null) {
  13123. range = this.range();
  13124. }
  13125. if (range == null) {
  13126. return;
  13127. }
  13128. node = $(node)[0];
  13129. range.setEndAfter(node);
  13130. range.collapse(false);
  13131. return this.range(range);
  13132. };
  13133. Selection.prototype.setRangeBefore = function(node, range) {
  13134. if (range == null) {
  13135. range = this.range();
  13136. }
  13137. if (range == null) {
  13138. return;
  13139. }
  13140. node = $(node)[0];
  13141. range.setEndBefore(node);
  13142. range.collapse(false);
  13143. return this.range(range);
  13144. };
  13145. Selection.prototype.setRangeAtStartOf = function(node, range) {
  13146. if (range == null) {
  13147. range = this.range();
  13148. }
  13149. node = $(node).get(0);
  13150. range.setEnd(node, 0);
  13151. range.collapse(false);
  13152. return this.range(range);
  13153. };
  13154. Selection.prototype.setRangeAtEndOf = function(node, range) {
  13155. var $lastNode, $node, contents, lastChild, lastChildLength, lastText, nodeLength;
  13156. if (range == null) {
  13157. range = this.range();
  13158. }
  13159. $node = $(node);
  13160. node = $node[0];
  13161. if ($node.is('pre')) {
  13162. contents = $node.contents();
  13163. if (contents.length > 0) {
  13164. lastChild = contents.last();
  13165. lastText = lastChild.text();
  13166. lastChildLength = this.editor.util.getNodeLength(lastChild[0]);
  13167. if (lastText.charAt(lastText.length - 1) === '\n') {
  13168. range.setEnd(lastChild[0], lastChildLength - 1);
  13169. } else {
  13170. range.setEnd(lastChild[0], lastChildLength);
  13171. }
  13172. } else {
  13173. range.setEnd(node, 0);
  13174. }
  13175. } else {
  13176. nodeLength = this.editor.util.getNodeLength(node);
  13177. if (node.nodeType !== 3 && nodeLength > 0) {
  13178. $lastNode = $(node).contents().last();
  13179. if ($lastNode.is('br')) {
  13180. nodeLength -= 1;
  13181. } else if ($lastNode[0].nodeType !== 3 && this.editor.util.isEmptyNode($lastNode)) {
  13182. $lastNode.append(this.editor.util.phBr);
  13183. node = $lastNode[0];
  13184. nodeLength = 0;
  13185. }
  13186. }
  13187. range.setEnd(node, nodeLength);
  13188. }
  13189. range.collapse(false);
  13190. return this.range(range);
  13191. };
  13192. Selection.prototype.deleteRangeContents = function(range) {
  13193. var atEndOfBody, atStartOfBody, endRange, startRange;
  13194. if (range == null) {
  13195. range = this.range();
  13196. }
  13197. startRange = range.cloneRange();
  13198. endRange = range.cloneRange();
  13199. startRange.collapse(true);
  13200. endRange.collapse(false);
  13201. atStartOfBody = this.rangeAtStartOf(this.editor.body, startRange);
  13202. atEndOfBody = this.rangeAtEndOf(this.editor.body, endRange);
  13203. if (!range.collapsed && atStartOfBody && atEndOfBody) {
  13204. this.editor.body.empty();
  13205. range.setStart(this.editor.body[0], 0);
  13206. range.collapse(true);
  13207. this.range(range);
  13208. } else {
  13209. range.deleteContents();
  13210. }
  13211. return range;
  13212. };
  13213. Selection.prototype.breakBlockEl = function(el, range) {
  13214. var $el;
  13215. if (range == null) {
  13216. range = this.range();
  13217. }
  13218. $el = $(el);
  13219. if (!range.collapsed) {
  13220. return $el;
  13221. }
  13222. range.setStartBefore($el.get(0));
  13223. if (range.collapsed) {
  13224. return $el;
  13225. }
  13226. return $el.before(range.extractContents());
  13227. };
  13228. Selection.prototype.save = function(range) {
  13229. var endCaret, endRange, startCaret;
  13230. if (range == null) {
  13231. range = this.range();
  13232. }
  13233. if (this._selectionSaved) {
  13234. return;
  13235. }
  13236. endRange = range.cloneRange();
  13237. endRange.collapse(false);
  13238. startCaret = $('<span/>').addClass('simditor-caret-start');
  13239. endCaret = $('<span/>').addClass('simditor-caret-end');
  13240. endRange.insertNode(endCaret[0]);
  13241. range.insertNode(startCaret[0]);
  13242. this.clear();
  13243. return this._selectionSaved = true;
  13244. };
  13245. Selection.prototype.restore = function() {
  13246. var endCaret, endContainer, endOffset, range, startCaret, startContainer, startOffset;
  13247. if (!this._selectionSaved) {
  13248. return false;
  13249. }
  13250. startCaret = this.editor.body.find('.simditor-caret-start');
  13251. endCaret = this.editor.body.find('.simditor-caret-end');
  13252. if (startCaret.length && endCaret.length) {
  13253. startContainer = startCaret.parent();
  13254. startOffset = startContainer.contents().index(startCaret);
  13255. endContainer = endCaret.parent();
  13256. endOffset = endContainer.contents().index(endCaret);
  13257. if (startContainer[0] === endContainer[0]) {
  13258. endOffset -= 1;
  13259. }
  13260. range = document.createRange();
  13261. range.setStart(startContainer.get(0), startOffset);
  13262. range.setEnd(endContainer.get(0), endOffset);
  13263. startCaret.remove();
  13264. endCaret.remove();
  13265. this.range(range);
  13266. } else {
  13267. startCaret.remove();
  13268. endCaret.remove();
  13269. }
  13270. this._selectionSaved = false;
  13271. return range;
  13272. };
  13273. return Selection;
  13274. })(SimpleModule);
  13275. Formatter = (function(superClass) {
  13276. extend(Formatter, superClass);
  13277. function Formatter() {
  13278. return Formatter.__super__.constructor.apply(this, arguments);
  13279. }
  13280. Formatter.pluginName = 'Formatter';
  13281. Formatter.prototype.opts = {
  13282. allowedTags: [],
  13283. allowedAttributes: {},
  13284. allowedStyles: {}
  13285. };
  13286. Formatter.prototype._init = function() {
  13287. this.editor = this._module;
  13288. this._allowedTags = $.merge(['br', 'span', 'a', 'img', 'b', 'strong', 'i', 'strike', 'u', 'font', 'p', 'ul', 'ol', 'li', 'blockquote', 'pre', 'code', 'h1', 'h2', 'h3', 'h4', 'hr'], this.opts.allowedTags);
  13289. this._allowedAttributes = $.extend({
  13290. img: ['src', 'alt', 'width', 'height', 'data-non-image'],
  13291. a: ['href', 'target'],
  13292. font: ['color'],
  13293. code: ['class']
  13294. }, this.opts.allowedAttributes);
  13295. this._allowedStyles = $.extend({
  13296. span: ['color', 'font-size'],
  13297. b: ['color'],
  13298. i: ['color'],
  13299. strong: ['color'],
  13300. strike: ['color'],
  13301. u: ['color'],
  13302. p: ['margin-left', 'text-align'],
  13303. h1: ['margin-left', 'text-align'],
  13304. h2: ['margin-left', 'text-align'],
  13305. h3: ['margin-left', 'text-align'],
  13306. h4: ['margin-left', 'text-align']
  13307. }, this.opts.allowedStyles);
  13308. return this.editor.body.on('click', 'a', function(e) {
  13309. return false;
  13310. });
  13311. };
  13312. Formatter.prototype.decorate = function($el) {
  13313. if ($el == null) {
  13314. $el = this.editor.body;
  13315. }
  13316. this.editor.trigger('decorate', [$el]);
  13317. return $el;
  13318. };
  13319. Formatter.prototype.undecorate = function($el) {
  13320. if ($el == null) {
  13321. $el = this.editor.body.clone();
  13322. }
  13323. this.editor.trigger('undecorate', [$el]);
  13324. return $el;
  13325. };
  13326. Formatter.prototype.autolink = function($el) {
  13327. var $link, $node, findLinkNode, k, lastIndex, len, linkNodes, match, re, replaceEls, subStr, text, uri;
  13328. if ($el == null) {
  13329. $el = this.editor.body;
  13330. }
  13331. linkNodes = [];
  13332. findLinkNode = function($parentNode) {
  13333. return $parentNode.contents().each(function(i, node) {
  13334. var $node, text;
  13335. $node = $(node);
  13336. if ($node.is('a') || $node.closest('a, pre', $el).length) {
  13337. return;
  13338. }
  13339. if (!$node.is('iframe') && $node.contents().length) {
  13340. return findLinkNode($node);
  13341. } else if ((text = $node.text()) && /https?:\/\/|www\./ig.test(text)) {
  13342. return linkNodes.push($node);
  13343. }
  13344. });
  13345. };
  13346. findLinkNode($el);
  13347. re = /(https?:\/\/|www\.)[\w\-\.\?&=\/#%:,@\!\+]+/ig;
  13348. for (k = 0, len = linkNodes.length; k < len; k++) {
  13349. $node = linkNodes[k];
  13350. text = $node.text();
  13351. replaceEls = [];
  13352. match = null;
  13353. lastIndex = 0;
  13354. while ((match = re.exec(text)) !== null) {
  13355. subStr = text.substring(lastIndex, match.index);
  13356. replaceEls.push(document.createTextNode(subStr));
  13357. lastIndex = re.lastIndex;
  13358. uri = /^(http(s)?:\/\/|\/)/.test(match[0]) ? match[0] : 'http://' + match[0];
  13359. $link = $("<a href=\"" + uri + "\" rel=\"nofollow\"></a>").text(match[0]);
  13360. replaceEls.push($link[0]);
  13361. }
  13362. replaceEls.push(document.createTextNode(text.substring(lastIndex)));
  13363. $node.replaceWith($(replaceEls));
  13364. }
  13365. return $el;
  13366. };
  13367. Formatter.prototype.format = function($el) {
  13368. var $node, blockNode, k, l, len, len1, n, node, ref, ref1;
  13369. if ($el == null) {
  13370. $el = this.editor.body;
  13371. }
  13372. if ($el.is(':empty')) {
  13373. $el.append('<p>' + this.editor.util.phBr + '</p>');
  13374. return $el;
  13375. }
  13376. ref = $el.contents();
  13377. for (k = 0, len = ref.length; k < len; k++) {
  13378. n = ref[k];
  13379. this.cleanNode(n, true);
  13380. }
  13381. ref1 = $el.contents();
  13382. for (l = 0, len1 = ref1.length; l < len1; l++) {
  13383. node = ref1[l];
  13384. $node = $(node);
  13385. if ($node.is('br')) {
  13386. if (typeof blockNode !== "undefined" && blockNode !== null) {
  13387. blockNode = null;
  13388. }
  13389. $node.remove();
  13390. } else if (this.editor.util.isBlockNode(node)) {
  13391. if ($node.is('li')) {
  13392. if (blockNode && blockNode.is('ul, ol')) {
  13393. blockNode.append(node);
  13394. } else {
  13395. blockNode = $('<ul/>').insertBefore(node);
  13396. blockNode.append(node);
  13397. }
  13398. } else {
  13399. blockNode = null;
  13400. }
  13401. } else {
  13402. if (!blockNode || blockNode.is('ul, ol')) {
  13403. blockNode = $('<p/>').insertBefore(node);
  13404. }
  13405. blockNode.append(node);
  13406. if (this.editor.util.isEmptyNode(blockNode)) {
  13407. blockNode.append(this.editor.util.phBr);
  13408. }
  13409. }
  13410. }
  13411. return $el;
  13412. };
  13413. Formatter.prototype.cleanNode = function(node, recursive) {
  13414. var $blockEls, $childImg, $node, $p, $td, allowedAttributes, attr, contents, isDecoration, k, l, len, len1, n, ref, ref1, text, textNode;
  13415. $node = $(node);
  13416. if (!($node.length > 0)) {
  13417. return;
  13418. }
  13419. if ($node[0].nodeType === 3) {
  13420. text = $node.text().replace(/(\r\n|\n|\r)/gm, '');
  13421. if (text) {
  13422. textNode = document.createTextNode(text);
  13423. $node.replaceWith(textNode);
  13424. } else {
  13425. $node.remove();
  13426. }
  13427. return;
  13428. }
  13429. contents = $node.is('iframe') ? null : $node.contents();
  13430. isDecoration = this.editor.util.isDecoratedNode($node);
  13431. if ($node.is(this._allowedTags.join(',')) || isDecoration) {
  13432. if ($node.is('a') && ($childImg = $node.find('img')).length > 0) {
  13433. $node.replaceWith($childImg);
  13434. $node = $childImg;
  13435. contents = null;
  13436. }
  13437. if ($node.is('td') && ($blockEls = $node.find(this.editor.util.blockNodes.join(','))).length > 0) {
  13438. $blockEls.each((function(_this) {
  13439. return function(i, blockEl) {
  13440. return $(blockEl).contents().unwrap();
  13441. };
  13442. })(this));
  13443. contents = $node.contents();
  13444. }
  13445. if ($node.is('img') && $node.hasClass('uploading')) {
  13446. $node.remove();
  13447. }
  13448. if (!isDecoration) {
  13449. allowedAttributes = this._allowedAttributes[$node[0].tagName.toLowerCase()];
  13450. ref = $.makeArray($node[0].attributes);
  13451. for (k = 0, len = ref.length; k < len; k++) {
  13452. attr = ref[k];
  13453. if (attr.name === 'style') {
  13454. continue;
  13455. }
  13456. if (!((allowedAttributes != null) && (ref1 = attr.name, indexOf.call(allowedAttributes, ref1) >= 0))) {
  13457. $node.removeAttr(attr.name);
  13458. }
  13459. }
  13460. this._cleanNodeStyles($node);
  13461. if ($node.is('span') && $node[0].attributes.length === 0) {
  13462. $node.contents().first().unwrap();
  13463. }
  13464. }
  13465. } else if ($node[0].nodeType === 1 && !$node.is(':empty')) {
  13466. if ($node.is('div, article, dl, header, footer, tr')) {
  13467. $node.append('<br/>');
  13468. contents.first().unwrap();
  13469. } else if ($node.is('table')) {
  13470. $p = $('<p/>');
  13471. $node.find('tr').each(function(i, tr) {
  13472. return $p.append($(tr).text() + '<br/>');
  13473. });
  13474. $node.replaceWith($p);
  13475. contents = null;
  13476. } else if ($node.is('thead, tfoot')) {
  13477. $node.remove();
  13478. contents = null;
  13479. } else if ($node.is('th')) {
  13480. $td = $('<td/>').append($node.contents());
  13481. $node.replaceWith($td);
  13482. } else {
  13483. contents.first().unwrap();
  13484. }
  13485. } else {
  13486. $node.remove();
  13487. contents = null;
  13488. }
  13489. if (recursive && (contents != null) && !$node.is('pre')) {
  13490. for (l = 0, len1 = contents.length; l < len1; l++) {
  13491. n = contents[l];
  13492. this.cleanNode(n, true);
  13493. }
  13494. }
  13495. return null;
  13496. };
  13497. Formatter.prototype._cleanNodeStyles = function($node) {
  13498. var allowedStyles, k, len, pair, ref, ref1, style, styleStr, styles;
  13499. styleStr = $node.attr('style');
  13500. if (!styleStr) {
  13501. return;
  13502. }
  13503. $node.removeAttr('style');
  13504. allowedStyles = this._allowedStyles[$node[0].tagName.toLowerCase()];
  13505. if (!(allowedStyles && allowedStyles.length > 0)) {
  13506. return $node;
  13507. }
  13508. styles = {};
  13509. ref = styleStr.split(';');
  13510. for (k = 0, len = ref.length; k < len; k++) {
  13511. style = ref[k];
  13512. style = $.trim(style);
  13513. pair = style.split(':');
  13514. if (!(pair.length = 2)) {
  13515. continue;
  13516. }
  13517. if (ref1 = pair[0], indexOf.call(allowedStyles, ref1) >= 0) {
  13518. styles[$.trim(pair[0])] = $.trim(pair[1]);
  13519. }
  13520. }
  13521. if (Object.keys(styles).length > 0) {
  13522. $node.css(styles);
  13523. }
  13524. return $node;
  13525. };
  13526. Formatter.prototype.clearHtml = function(html, lineBreak) {
  13527. var container, contents, result;
  13528. if (lineBreak == null) {
  13529. lineBreak = true;
  13530. }
  13531. container = $('<div/>').append(html);
  13532. contents = container.contents();
  13533. result = '';
  13534. contents.each((function(_this) {
  13535. return function(i, node) {
  13536. var $node, children;
  13537. if (node.nodeType === 3) {
  13538. return result += node.nodeValue;
  13539. } else if (node.nodeType === 1) {
  13540. $node = $(node);
  13541. children = $node.is('iframe') ? null : $node.contents();
  13542. if (children && children.length > 0) {
  13543. result += _this.clearHtml(children);
  13544. }
  13545. if (lineBreak && i < contents.length - 1 && $node.is('br, p, div, li,tr, pre, address, artticle, aside, dl, figcaption, footer, h1, h2,h3, h4, header')) {
  13546. return result += '\n';
  13547. }
  13548. }
  13549. };
  13550. })(this));
  13551. return result;
  13552. };
  13553. Formatter.prototype.beautify = function($contents) {
  13554. var uselessP;
  13555. uselessP = function($el) {
  13556. return !!($el.is('p') && !$el.text() && $el.children(':not(br)').length < 1);
  13557. };
  13558. return $contents.each(function(i, el) {
  13559. var $el, invalid;
  13560. $el = $(el);
  13561. invalid = $el.is(':not(img, br, col, td, hr, [class^="simditor-"]):empty');
  13562. if (invalid || uselessP($el)) {
  13563. $el.remove();
  13564. }
  13565. return $el.find(':not(img, br, col, td, hr, [class^="simditor-"]):empty').remove();
  13566. });
  13567. };
  13568. return Formatter;
  13569. })(SimpleModule);
  13570. InputManager = (function(superClass) {
  13571. extend(InputManager, superClass);
  13572. function InputManager() {
  13573. return InputManager.__super__.constructor.apply(this, arguments);
  13574. }
  13575. InputManager.pluginName = 'InputManager';
  13576. InputManager.prototype._modifierKeys = [16, 17, 18, 91, 93, 224];
  13577. InputManager.prototype._arrowKeys = [37, 38, 39, 40];
  13578. InputManager.prototype._init = function() {
  13579. var selectAllKey, submitKey;
  13580. this.editor = this._module;
  13581. this.throttledValueChanged = this.editor.util.throttle((function(_this) {
  13582. return function(params) {
  13583. return setTimeout(function() {
  13584. return _this.editor.trigger('valuechanged', params);
  13585. }, 10);
  13586. };
  13587. })(this), 300);
  13588. this.throttledSelectionChanged = this.editor.util.throttle((function(_this) {
  13589. return function() {
  13590. return _this.editor.trigger('selectionchanged');
  13591. };
  13592. })(this), 50);
  13593. $(document).on('selectionchange.simditor' + this.editor.id, (function(_this) {
  13594. return function(e) {
  13595. var triggerEvent;
  13596. if (!(_this.focused && !_this.editor.clipboard.pasting)) {
  13597. return;
  13598. }
  13599. triggerEvent = function() {
  13600. if (_this._selectionTimer) {
  13601. clearTimeout(_this._selectionTimer);
  13602. _this._selectionTimer = null;
  13603. }
  13604. if (_this.editor.selection._selection.rangeCount > 0) {
  13605. return _this.throttledSelectionChanged();
  13606. } else {
  13607. return _this._selectionTimer = setTimeout(function() {
  13608. _this._selectionTimer = null;
  13609. if (_this.focused) {
  13610. return triggerEvent();
  13611. }
  13612. }, 10);
  13613. }
  13614. };
  13615. return triggerEvent();
  13616. };
  13617. })(this));
  13618. this.editor.on('valuechanged', (function(_this) {
  13619. return function() {
  13620. var $rootBlocks;
  13621. _this.lastCaretPosition = null;
  13622. $rootBlocks = _this.editor.body.children().filter(function(i, node) {
  13623. return _this.editor.util.isBlockNode(node);
  13624. });
  13625. if (_this.focused && $rootBlocks.length === 0) {
  13626. _this.editor.selection.save();
  13627. _this.editor.formatter.format();
  13628. _this.editor.selection.restore();
  13629. }
  13630. _this.editor.body.find('hr, pre, .simditor-table').each(function(i, el) {
  13631. var $el, formatted;
  13632. $el = $(el);
  13633. if ($el.parent().is('blockquote') || $el.parent()[0] === _this.editor.body[0]) {
  13634. formatted = false;
  13635. if ($el.next().length === 0) {
  13636. $('<p/>').append(_this.editor.util.phBr).insertAfter($el);
  13637. formatted = true;
  13638. }
  13639. if ($el.prev().length === 0) {
  13640. $('<p/>').append(_this.editor.util.phBr).insertBefore($el);
  13641. formatted = true;
  13642. }
  13643. if (formatted) {
  13644. return _this.throttledValueChanged();
  13645. }
  13646. }
  13647. });
  13648. _this.editor.body.find('pre:empty').append(_this.editor.util.phBr);
  13649. if (!_this.editor.util.support.onselectionchange && _this.focused) {
  13650. return _this.throttledSelectionChanged();
  13651. }
  13652. };
  13653. })(this));
  13654. this.editor.body.on('keydown', $.proxy(this._onKeyDown, this)).on('keypress', $.proxy(this._onKeyPress, this)).on('keyup', $.proxy(this._onKeyUp, this)).on('mouseup', $.proxy(this._onMouseUp, this)).on('focus', $.proxy(this._onFocus, this)).on('blur', $.proxy(this._onBlur, this)).on('drop', $.proxy(this._onDrop, this)).on('input', $.proxy(this._onInput, this));
  13655. if (this.editor.util.browser.firefox) {
  13656. this.editor.hotkeys.add('cmd+left', (function(_this) {
  13657. return function(e) {
  13658. e.preventDefault();
  13659. _this.editor.selection._selection.modify('move', 'backward', 'lineboundary');
  13660. return false;
  13661. };
  13662. })(this));
  13663. this.editor.hotkeys.add('cmd+right', (function(_this) {
  13664. return function(e) {
  13665. e.preventDefault();
  13666. _this.editor.selection._selection.modify('move', 'forward', 'lineboundary');
  13667. return false;
  13668. };
  13669. })(this));
  13670. selectAllKey = this.editor.util.os.mac ? 'cmd+a' : 'ctrl+a';
  13671. this.editor.hotkeys.add(selectAllKey, (function(_this) {
  13672. return function(e) {
  13673. var $children, firstBlock, lastBlock, range;
  13674. $children = _this.editor.body.children();
  13675. if (!($children.length > 0)) {
  13676. return;
  13677. }
  13678. firstBlock = $children.first().get(0);
  13679. lastBlock = $children.last().get(0);
  13680. range = document.createRange();
  13681. range.setStart(firstBlock, 0);
  13682. range.setEnd(lastBlock, _this.editor.util.getNodeLength(lastBlock));
  13683. _this.editor.selection.range(range);
  13684. return false;
  13685. };
  13686. })(this));
  13687. }
  13688. submitKey = this.editor.util.os.mac ? 'cmd+enter' : 'ctrl+enter';
  13689. return this.editor.hotkeys.add(submitKey, (function(_this) {
  13690. return function(e) {
  13691. _this.editor.el.closest('form').find('button:submit').click();
  13692. return false;
  13693. };
  13694. })(this));
  13695. };
  13696. InputManager.prototype._onFocus = function(e) {
  13697. if (this.editor.clipboard.pasting) {
  13698. return;
  13699. }
  13700. this.editor.el.addClass('focus').removeClass('error');
  13701. this.focused = true;
  13702. return setTimeout((function(_this) {
  13703. return function() {
  13704. var $blockEl, range;
  13705. range = _this.editor.selection._selection.getRangeAt(0);
  13706. if (range.startContainer === _this.editor.body[0]) {
  13707. if (_this.lastCaretPosition) {
  13708. _this.editor.undoManager.caretPosition(_this.lastCaretPosition);
  13709. } else {
  13710. $blockEl = _this.editor.body.children().first();
  13711. range = document.createRange();
  13712. _this.editor.selection.setRangeAtStartOf($blockEl, range);
  13713. }
  13714. }
  13715. _this.lastCaretPosition = null;
  13716. _this.editor.triggerHandler('focus');
  13717. if (!_this.editor.util.support.onselectionchange) {
  13718. return _this.throttledSelectionChanged();
  13719. }
  13720. };
  13721. })(this), 0);
  13722. };
  13723. InputManager.prototype._onBlur = function(e) {
  13724. var ref;
  13725. if (this.editor.clipboard.pasting) {
  13726. return;
  13727. }
  13728. this.editor.el.removeClass('focus');
  13729. this.editor.sync();
  13730. this.focused = false;
  13731. this.lastCaretPosition = (ref = this.editor.undoManager.currentState()) != null ? ref.caret : void 0;
  13732. return this.editor.triggerHandler('blur');
  13733. };
  13734. InputManager.prototype._onMouseUp = function(e) {
  13735. if (!this.editor.util.support.onselectionchange) {
  13736. return this.throttledSelectionChanged();
  13737. }
  13738. };
  13739. InputManager.prototype._onKeyDown = function(e) {
  13740. var ref, ref1;
  13741. if (this.editor.triggerHandler(e) === false) {
  13742. return false;
  13743. }
  13744. if (this.editor.hotkeys.respondTo(e)) {
  13745. return;
  13746. }
  13747. if (this.editor.keystroke.respondTo(e)) {
  13748. this.throttledValueChanged();
  13749. return false;
  13750. }
  13751. if ((ref = e.which, indexOf.call(this._modifierKeys, ref) >= 0) || (ref1 = e.which, indexOf.call(this._arrowKeys, ref1) >= 0)) {
  13752. return;
  13753. }
  13754. if (this.editor.util.metaKey(e) && e.which === 86) {
  13755. return;
  13756. }
  13757. if (!this.editor.util.support.oninput) {
  13758. this.throttledValueChanged(['typing']);
  13759. }
  13760. return null;
  13761. };
  13762. InputManager.prototype._onKeyPress = function(e) {
  13763. if (this.editor.triggerHandler(e) === false) {
  13764. return false;
  13765. }
  13766. };
  13767. InputManager.prototype._onKeyUp = function(e) {
  13768. var p, ref;
  13769. if (this.editor.triggerHandler(e) === false) {
  13770. return false;
  13771. }
  13772. if (!this.editor.util.support.onselectionchange && (ref = e.which, indexOf.call(this._arrowKeys, ref) >= 0)) {
  13773. this.throttledValueChanged();
  13774. return;
  13775. }
  13776. if ((e.which === 8 || e.which === 46) && this.editor.util.isEmptyNode(this.editor.body)) {
  13777. this.editor.body.empty();
  13778. p = $('<p/>').append(this.editor.util.phBr).appendTo(this.editor.body);
  13779. this.editor.selection.setRangeAtStartOf(p);
  13780. }
  13781. };
  13782. InputManager.prototype._onDrop = function(e) {
  13783. if (this.editor.triggerHandler(e) === false) {
  13784. return false;
  13785. }
  13786. return this.throttledValueChanged();
  13787. };
  13788. InputManager.prototype._onInput = function(e) {
  13789. return this.throttledValueChanged(['oninput']);
  13790. };
  13791. return InputManager;
  13792. })(SimpleModule);
  13793. Keystroke = (function(superClass) {
  13794. extend(Keystroke, superClass);
  13795. function Keystroke() {
  13796. return Keystroke.__super__.constructor.apply(this, arguments);
  13797. }
  13798. Keystroke.pluginName = 'Keystroke';
  13799. Keystroke.prototype._init = function() {
  13800. this.editor = this._module;
  13801. this._keystrokeHandlers = {};
  13802. return this._initKeystrokeHandlers();
  13803. };
  13804. Keystroke.prototype.add = function(key, node, handler) {
  13805. key = key.toLowerCase();
  13806. key = this.editor.hotkeys.constructor.aliases[key] || key;
  13807. if (!this._keystrokeHandlers[key]) {
  13808. this._keystrokeHandlers[key] = {};
  13809. }
  13810. return this._keystrokeHandlers[key][node] = handler;
  13811. };
  13812. Keystroke.prototype.respondTo = function(e) {
  13813. var base, key, ref, result;
  13814. key = (ref = this.editor.hotkeys.constructor.keyNameMap[e.which]) != null ? ref.toLowerCase() : void 0;
  13815. if (!key) {
  13816. return;
  13817. }
  13818. if (key in this._keystrokeHandlers) {
  13819. result = typeof (base = this._keystrokeHandlers[key])['*'] === "function" ? base['*'](e) : void 0;
  13820. if (!result) {
  13821. this.editor.selection.startNodes().each((function(_this) {
  13822. return function(i, node) {
  13823. var handler, ref1;
  13824. if (node.nodeType !== Node.ELEMENT_NODE) {
  13825. return;
  13826. }
  13827. handler = (ref1 = _this._keystrokeHandlers[key]) != null ? ref1[node.tagName.toLowerCase()] : void 0;
  13828. result = typeof handler === "function" ? handler(e, $(node)) : void 0;
  13829. if (result === true || result === false) {
  13830. return false;
  13831. }
  13832. };
  13833. })(this));
  13834. }
  13835. if (result) {
  13836. return true;
  13837. }
  13838. }
  13839. };
  13840. Keystroke.prototype._initKeystrokeHandlers = function() {
  13841. var titleEnterHandler;
  13842. if (this.editor.util.browser.safari) {
  13843. this.add('enter', '*', (function(_this) {
  13844. return function(e) {
  13845. var $blockEl, $br;
  13846. if (!e.shiftKey) {
  13847. return;
  13848. }
  13849. $blockEl = _this.editor.selection.blockNodes().last();
  13850. if ($blockEl.is('pre')) {
  13851. return;
  13852. }
  13853. $br = $('<br/>');
  13854. if (_this.editor.selection.rangeAtEndOf($blockEl)) {
  13855. _this.editor.selection.insertNode($br);
  13856. _this.editor.selection.insertNode($('<br/>'));
  13857. _this.editor.selection.setRangeBefore($br);
  13858. } else {
  13859. _this.editor.selection.insertNode($br);
  13860. }
  13861. return true;
  13862. };
  13863. })(this));
  13864. }
  13865. if (this.editor.util.browser.webkit || this.editor.util.browser.msie) {
  13866. titleEnterHandler = (function(_this) {
  13867. return function(e, $node) {
  13868. var $p;
  13869. if (!_this.editor.selection.rangeAtEndOf($node)) {
  13870. return;
  13871. }
  13872. $p = $('<p/>').append(_this.editor.util.phBr).insertAfter($node);
  13873. _this.editor.selection.setRangeAtStartOf($p);
  13874. return true;
  13875. };
  13876. })(this);
  13877. this.add('enter', 'h1', titleEnterHandler);
  13878. this.add('enter', 'h2', titleEnterHandler);
  13879. this.add('enter', 'h3', titleEnterHandler);
  13880. this.add('enter', 'h4', titleEnterHandler);
  13881. this.add('enter', 'h5', titleEnterHandler);
  13882. this.add('enter', 'h6', titleEnterHandler);
  13883. }
  13884. this.add('backspace', '*', (function(_this) {
  13885. return function(e) {
  13886. var $blockEl, $prevBlockEl, $rootBlock, isWebkit;
  13887. $rootBlock = _this.editor.selection.rootNodes().first();
  13888. $prevBlockEl = $rootBlock.prev();
  13889. if ($prevBlockEl.is('hr') && _this.editor.selection.rangeAtStartOf($rootBlock)) {
  13890. _this.editor.selection.save();
  13891. $prevBlockEl.remove();
  13892. _this.editor.selection.restore();
  13893. return true;
  13894. }
  13895. $blockEl = _this.editor.selection.blockNodes().last();
  13896. isWebkit = _this.editor.util.browser.webkit;
  13897. if (isWebkit && _this.editor.selection.rangeAtStartOf($blockEl)) {
  13898. _this.editor.selection.save();
  13899. _this.editor.formatter.cleanNode($blockEl, true);
  13900. _this.editor.selection.restore();
  13901. return null;
  13902. }
  13903. };
  13904. })(this));
  13905. this.add('enter', 'li', (function(_this) {
  13906. return function(e, $node) {
  13907. var $cloneNode, listEl, newBlockEl, newListEl;
  13908. $cloneNode = $node.clone();
  13909. $cloneNode.find('ul, ol').remove();
  13910. if (!(_this.editor.util.isEmptyNode($cloneNode) && $node.is(_this.editor.selection.blockNodes().last()))) {
  13911. return;
  13912. }
  13913. listEl = $node.parent();
  13914. if ($node.next('li').length > 0) {
  13915. if (!_this.editor.util.isEmptyNode($node)) {
  13916. return;
  13917. }
  13918. if (listEl.parent('li').length > 0) {
  13919. newBlockEl = $('<li/>').append(_this.editor.util.phBr).insertAfter(listEl.parent('li'));
  13920. newListEl = $('<' + listEl[0].tagName + '/>').append($node.nextAll('li'));
  13921. newBlockEl.append(newListEl);
  13922. } else {
  13923. newBlockEl = $('<p/>').append(_this.editor.util.phBr).insertAfter(listEl);
  13924. newListEl = $('<' + listEl[0].tagName + '/>').append($node.nextAll('li'));
  13925. newBlockEl.after(newListEl);
  13926. }
  13927. } else {
  13928. if (listEl.parent('li').length > 0) {
  13929. newBlockEl = $('<li/>').insertAfter(listEl.parent('li'));
  13930. if ($node.contents().length > 0) {
  13931. newBlockEl.append($node.contents());
  13932. } else {
  13933. newBlockEl.append(_this.editor.util.phBr);
  13934. }
  13935. } else {
  13936. newBlockEl = $('<p/>').append(_this.editor.util.phBr).insertAfter(listEl);
  13937. if ($node.children('ul, ol').length > 0) {
  13938. newBlockEl.after($node.children('ul, ol'));
  13939. }
  13940. }
  13941. }
  13942. if ($node.prev('li').length) {
  13943. $node.remove();
  13944. } else {
  13945. listEl.remove();
  13946. }
  13947. _this.editor.selection.setRangeAtStartOf(newBlockEl);
  13948. return true;
  13949. };
  13950. })(this));
  13951. this.add('enter', 'pre', (function(_this) {
  13952. return function(e, $node) {
  13953. var $p, breakNode, range;
  13954. e.preventDefault();
  13955. if (e.shiftKey) {
  13956. $p = $('<p/>').append(_this.editor.util.phBr).insertAfter($node);
  13957. _this.editor.selection.setRangeAtStartOf($p);
  13958. return true;
  13959. }
  13960. range = _this.editor.selection.range();
  13961. breakNode = null;
  13962. range.deleteContents();
  13963. if (!_this.editor.util.browser.msie && _this.editor.selection.rangeAtEndOf($node)) {
  13964. breakNode = document.createTextNode('\n\n');
  13965. range.insertNode(breakNode);
  13966. range.setEnd(breakNode, 1);
  13967. } else {
  13968. breakNode = document.createTextNode('\n');
  13969. range.insertNode(breakNode);
  13970. range.setStartAfter(breakNode);
  13971. }
  13972. range.collapse(false);
  13973. _this.editor.selection.range(range);
  13974. return true;
  13975. };
  13976. })(this));
  13977. this.add('enter', 'blockquote', (function(_this) {
  13978. return function(e, $node) {
  13979. var $closestBlock, range;
  13980. $closestBlock = _this.editor.selection.blockNodes().last();
  13981. if (!($closestBlock.is('p') && !$closestBlock.next().length && _this.editor.util.isEmptyNode($closestBlock))) {
  13982. return;
  13983. }
  13984. $node.after($closestBlock);
  13985. range = document.createRange();
  13986. _this.editor.selection.setRangeAtStartOf($closestBlock, range);
  13987. return true;
  13988. };
  13989. })(this));
  13990. this.add('backspace', 'li', (function(_this) {
  13991. return function(e, $node) {
  13992. var $br, $childList, $newLi, $prevChildList, $prevNode, $textNode, isFF, range, text;
  13993. $childList = $node.children('ul, ol');
  13994. $prevNode = $node.prev('li');
  13995. if (!($childList.length > 0 && $prevNode.length > 0)) {
  13996. return false;
  13997. }
  13998. text = '';
  13999. $textNode = null;
  14000. $node.contents().each(function(i, n) {
  14001. if (n.nodeType === 1 && /UL|OL/.test(n.nodeName)) {
  14002. return false;
  14003. }
  14004. if (n.nodeType === 1 && /BR/.test(n.nodeName)) {
  14005. return;
  14006. }
  14007. if (n.nodeType === 3 && n.nodeValue) {
  14008. text += n.nodeValue;
  14009. } else if (n.nodeType === 1) {
  14010. text += $(n).text();
  14011. }
  14012. return $textNode = $(n);
  14013. });
  14014. isFF = _this.editor.util.browser.firefox && !$textNode.next('br').length;
  14015. if ($textNode && text.length === 1 && isFF) {
  14016. $br = $(_this.editor.util.phBr).insertAfter($textNode);
  14017. $textNode.remove();
  14018. _this.editor.selection.setRangeBefore($br);
  14019. return true;
  14020. } else if (text.length > 0) {
  14021. return false;
  14022. }
  14023. range = document.createRange();
  14024. $prevChildList = $prevNode.children('ul, ol');
  14025. if ($prevChildList.length > 0) {
  14026. $newLi = $('<li/>').append(_this.editor.util.phBr).appendTo($prevChildList);
  14027. $prevChildList.append($childList.children('li'));
  14028. $node.remove();
  14029. _this.editor.selection.setRangeAtEndOf($newLi, range);
  14030. } else {
  14031. _this.editor.selection.setRangeAtEndOf($prevNode, range);
  14032. $prevNode.append($childList);
  14033. $node.remove();
  14034. _this.editor.selection.range(range);
  14035. }
  14036. return true;
  14037. };
  14038. })(this));
  14039. this.add('backspace', 'pre', (function(_this) {
  14040. return function(e, $node) {
  14041. var $newNode, codeStr, range;
  14042. if (!_this.editor.selection.rangeAtStartOf($node)) {
  14043. return;
  14044. }
  14045. codeStr = $node.html().replace('\n', '<br/>') || _this.editor.util.phBr;
  14046. $newNode = $('<p/>').append(codeStr).insertAfter($node);
  14047. $node.remove();
  14048. range = document.createRange();
  14049. _this.editor.selection.setRangeAtStartOf($newNode, range);
  14050. return true;
  14051. };
  14052. })(this));
  14053. return this.add('backspace', 'blockquote', (function(_this) {
  14054. return function(e, $node) {
  14055. var $firstChild, range;
  14056. if (!_this.editor.selection.rangeAtStartOf($node)) {
  14057. return;
  14058. }
  14059. $firstChild = $node.children().first().unwrap();
  14060. range = document.createRange();
  14061. _this.editor.selection.setRangeAtStartOf($firstChild, range);
  14062. return true;
  14063. };
  14064. })(this));
  14065. };
  14066. return Keystroke;
  14067. })(SimpleModule);
  14068. UndoManager = (function(superClass) {
  14069. extend(UndoManager, superClass);
  14070. function UndoManager() {
  14071. return UndoManager.__super__.constructor.apply(this, arguments);
  14072. }
  14073. UndoManager.pluginName = 'UndoManager';
  14074. UndoManager.prototype._index = -1;
  14075. UndoManager.prototype._capacity = 20;
  14076. UndoManager.prototype._startPosition = null;
  14077. UndoManager.prototype._endPosition = null;
  14078. UndoManager.prototype._init = function() {
  14079. var redoShortcut, undoShortcut;
  14080. this.editor = this._module;
  14081. this._stack = [];
  14082. if (this.editor.util.os.mac) {
  14083. undoShortcut = 'cmd+z';
  14084. redoShortcut = 'shift+cmd+z';
  14085. } else if (this.editor.util.os.win) {
  14086. undoShortcut = 'ctrl+z';
  14087. redoShortcut = 'ctrl+y';
  14088. } else {
  14089. undoShortcut = 'ctrl+z';
  14090. redoShortcut = 'shift+ctrl+z';
  14091. }
  14092. this.editor.hotkeys.add(undoShortcut, (function(_this) {
  14093. return function(e) {
  14094. e.preventDefault();
  14095. _this.undo();
  14096. return false;
  14097. };
  14098. })(this));
  14099. this.editor.hotkeys.add(redoShortcut, (function(_this) {
  14100. return function(e) {
  14101. e.preventDefault();
  14102. _this.redo();
  14103. return false;
  14104. };
  14105. })(this));
  14106. this.throttledPushState = this.editor.util.throttle((function(_this) {
  14107. return function() {
  14108. return _this._pushUndoState();
  14109. };
  14110. })(this), 2000);
  14111. this.editor.on('valuechanged', (function(_this) {
  14112. return function(e, src) {
  14113. if (src === 'undo' || src === 'redo') {
  14114. return;
  14115. }
  14116. return _this.throttledPushState();
  14117. };
  14118. })(this));
  14119. this.editor.on('selectionchanged', (function(_this) {
  14120. return function(e) {
  14121. _this.resetCaretPosition();
  14122. return _this.update();
  14123. };
  14124. })(this));
  14125. this.editor.on('focus', (function(_this) {
  14126. return function(e) {
  14127. if (_this._stack.length === 0) {
  14128. return _this._pushUndoState();
  14129. }
  14130. };
  14131. })(this));
  14132. return this.editor.on('blur', (function(_this) {
  14133. return function(e) {
  14134. return _this.resetCaretPosition();
  14135. };
  14136. })(this));
  14137. };
  14138. UndoManager.prototype.resetCaretPosition = function() {
  14139. this._startPosition = null;
  14140. return this._endPosition = null;
  14141. };
  14142. UndoManager.prototype.startPosition = function() {
  14143. if (this.editor.selection._range) {
  14144. this._startPosition || (this._startPosition = this._getPosition('start'));
  14145. }
  14146. return this._startPosition;
  14147. };
  14148. UndoManager.prototype.endPosition = function() {
  14149. if (this.editor.selection._range) {
  14150. this._endPosition || (this._endPosition = (function(_this) {
  14151. return function() {
  14152. var range;
  14153. range = _this.editor.selection.range();
  14154. if (range.collapsed) {
  14155. return _this._startPosition;
  14156. }
  14157. return _this._getPosition('end');
  14158. };
  14159. })(this)());
  14160. }
  14161. return this._endPosition;
  14162. };
  14163. UndoManager.prototype._pushUndoState = function() {
  14164. var caret;
  14165. if (this.editor.triggerHandler('pushundostate') === false) {
  14166. return;
  14167. }
  14168. caret = this.caretPosition();
  14169. if (!caret.start) {
  14170. return;
  14171. }
  14172. this._index += 1;
  14173. this._stack.length = this._index;
  14174. this._stack.push({
  14175. html: this.editor.body.html(),
  14176. caret: this.caretPosition()
  14177. });
  14178. if (this._stack.length > this._capacity) {
  14179. this._stack.shift();
  14180. return this._index -= 1;
  14181. }
  14182. };
  14183. UndoManager.prototype.currentState = function() {
  14184. if (this._stack.length && this._index > -1) {
  14185. return this._stack[this._index];
  14186. } else {
  14187. return null;
  14188. }
  14189. };
  14190. UndoManager.prototype.undo = function() {
  14191. var state;
  14192. if (this._index < 1 || this._stack.length < 2) {
  14193. return;
  14194. }
  14195. this.editor.hidePopover();
  14196. this._index -= 1;
  14197. state = this._stack[this._index];
  14198. this.editor.body.get(0).innerHTML = state.html;
  14199. this.caretPosition(state.caret);
  14200. this.editor.body.find('.selected').removeClass('selected');
  14201. this.editor.sync();
  14202. return this.editor.trigger('valuechanged', ['undo']);
  14203. };
  14204. UndoManager.prototype.redo = function() {
  14205. var state;
  14206. if (this._index < 0 || this._stack.length < this._index + 2) {
  14207. return;
  14208. }
  14209. this.editor.hidePopover();
  14210. this._index += 1;
  14211. state = this._stack[this._index];
  14212. this.editor.body.get(0).innerHTML = state.html;
  14213. this.caretPosition(state.caret);
  14214. this.editor.body.find('.selected').removeClass('selected');
  14215. this.editor.sync();
  14216. return this.editor.trigger('valuechanged', ['redo']);
  14217. };
  14218. UndoManager.prototype.update = function() {
  14219. var currentState;
  14220. currentState = this.currentState();
  14221. if (!currentState) {
  14222. return;
  14223. }
  14224. currentState.html = this.editor.body.html();
  14225. return currentState.caret = this.caretPosition();
  14226. };
  14227. UndoManager.prototype._getNodeOffset = function(node, index) {
  14228. var $parent, merging, offset;
  14229. if ($.isNumeric(index)) {
  14230. $parent = $(node);
  14231. } else {
  14232. $parent = $(node).parent();
  14233. }
  14234. offset = 0;
  14235. merging = false;
  14236. $parent.contents().each(function(i, child) {
  14237. if (node === child || (index === i && i === 0)) {
  14238. return false;
  14239. }
  14240. if (child.nodeType === Node.TEXT_NODE) {
  14241. if (!merging && child.nodeValue.length > 0) {
  14242. offset += 1;
  14243. merging = true;
  14244. }
  14245. } else {
  14246. offset += 1;
  14247. merging = false;
  14248. }
  14249. if (index - 1 === i) {
  14250. return false;
  14251. }
  14252. return null;
  14253. });
  14254. return offset;
  14255. };
  14256. UndoManager.prototype._getPosition = function(type) {
  14257. var $nodes, node, nodes, offset, position, prevNode, range;
  14258. if (type == null) {
  14259. type = 'start';
  14260. }
  14261. range = this.editor.selection.range();
  14262. offset = range[type + "Offset"];
  14263. $nodes = this.editor.selection[type + "Nodes"]();
  14264. node = $nodes.first()[0];
  14265. if (node.nodeType === Node.TEXT_NODE) {
  14266. prevNode = node.previousSibling;
  14267. while (prevNode && prevNode.nodeType === Node.TEXT_NODE) {
  14268. node = prevNode;
  14269. offset += this.editor.util.getNodeLength(prevNode);
  14270. prevNode = prevNode.previousSibling;
  14271. }
  14272. nodes = $nodes.get();
  14273. nodes[0] = node;
  14274. $nodes = $(nodes);
  14275. } else {
  14276. offset = this._getNodeOffset(node, offset);
  14277. }
  14278. position = [offset];
  14279. $nodes.each((function(_this) {
  14280. return function(i, node) {
  14281. return position.unshift(_this._getNodeOffset(node));
  14282. };
  14283. })(this));
  14284. return position;
  14285. };
  14286. UndoManager.prototype._getNodeByPosition = function(position) {
  14287. var child, childNodes, i, k, len, node, offset, ref;
  14288. node = this.editor.body[0];
  14289. ref = position.slice(0, position.length - 1);
  14290. for (i = k = 0, len = ref.length; k < len; i = ++k) {
  14291. offset = ref[i];
  14292. childNodes = node.childNodes;
  14293. if (offset > childNodes.length - 1) {
  14294. if (i === position.length - 2 && $(node).is('pre:empty')) {
  14295. child = document.createTextNode('');
  14296. node.appendChild(child);
  14297. childNodes = node.childNodes;
  14298. } else {
  14299. node = null;
  14300. break;
  14301. }
  14302. }
  14303. node = childNodes[offset];
  14304. }
  14305. return node;
  14306. };
  14307. UndoManager.prototype.caretPosition = function(caret) {
  14308. var endContainer, endOffset, range, startContainer, startOffset;
  14309. if (!caret) {
  14310. range = this.editor.selection.range();
  14311. caret = this.editor.inputManager.focused && (range != null) ? {
  14312. start: this.startPosition(),
  14313. end: this.endPosition(),
  14314. collapsed: range.collapsed
  14315. } : {};
  14316. return caret;
  14317. } else {
  14318. if (!caret.start) {
  14319. return;
  14320. }
  14321. startContainer = this._getNodeByPosition(caret.start);
  14322. startOffset = caret.start[caret.start.length - 1];
  14323. if (caret.collapsed) {
  14324. endContainer = startContainer;
  14325. endOffset = startOffset;
  14326. } else {
  14327. endContainer = this._getNodeByPosition(caret.end);
  14328. endOffset = caret.start[caret.start.length - 1];
  14329. }
  14330. if (!startContainer || !endContainer) {
  14331. if (typeof console !== "undefined" && console !== null) {
  14332. if (typeof console.warn === "function") {
  14333. console.warn('simditor: invalid caret state');
  14334. }
  14335. }
  14336. return;
  14337. }
  14338. range = document.createRange();
  14339. range.setStart(startContainer, startOffset);
  14340. range.setEnd(endContainer, endOffset);
  14341. return this.editor.selection.range(range);
  14342. }
  14343. };
  14344. return UndoManager;
  14345. })(SimpleModule);
  14346. Util = (function(superClass) {
  14347. extend(Util, superClass);
  14348. function Util() {
  14349. return Util.__super__.constructor.apply(this, arguments);
  14350. }
  14351. Util.pluginName = 'Util';
  14352. Util.prototype._init = function() {
  14353. this.editor = this._module;
  14354. if (this.browser.msie && this.browser.version < 11) {
  14355. return this.phBr = '';
  14356. }
  14357. };
  14358. Util.prototype.phBr = '<br/>';
  14359. Util.prototype.os = (function() {
  14360. var os;
  14361. os = {};
  14362. if (/Mac/.test(navigator.appVersion)) {
  14363. os.mac = true;
  14364. } else if (/Linux/.test(navigator.appVersion)) {
  14365. os.linux = true;
  14366. } else if (/Win/.test(navigator.appVersion)) {
  14367. os.win = true;
  14368. } else if (/X11/.test(navigator.appVersion)) {
  14369. os.unix = true;
  14370. }
  14371. if (/Mobi/.test(navigator.appVersion)) {
  14372. os.mobile = true;
  14373. }
  14374. return os;
  14375. })();
  14376. Util.prototype.browser = (function() {
  14377. var chrome, edge, firefox, ie, ref, ref1, ref2, ref3, ref4, safari, ua;
  14378. ua = navigator.userAgent;
  14379. ie = /(msie|trident)/i.test(ua);
  14380. chrome = /chrome|crios/i.test(ua);
  14381. safari = /safari/i.test(ua) && !chrome;
  14382. firefox = /firefox/i.test(ua);
  14383. edge = /edge/i.test(ua);
  14384. if (ie) {
  14385. return {
  14386. msie: true,
  14387. version: ((ref = ua.match(/(msie |rv:)(\d+(\.\d+)?)/i)) != null ? ref[2] : void 0) * 1
  14388. };
  14389. } else if (edge) {
  14390. return {
  14391. edge: true,
  14392. webkit: true,
  14393. version: ((ref1 = ua.match(/edge\/(\d+(\.\d+)?)/i)) != null ? ref1[1] : void 0) * 1
  14394. };
  14395. } else if (chrome) {
  14396. return {
  14397. webkit: true,
  14398. chrome: true,
  14399. version: ((ref2 = ua.match(/(?:chrome|crios)\/(\d+(\.\d+)?)/i)) != null ? ref2[1] : void 0) * 1
  14400. };
  14401. } else if (safari) {
  14402. return {
  14403. webkit: true,
  14404. safari: true,
  14405. version: ((ref3 = ua.match(/version\/(\d+(\.\d+)?)/i)) != null ? ref3[1] : void 0) * 1
  14406. };
  14407. } else if (firefox) {
  14408. return {
  14409. mozilla: true,
  14410. firefox: true,
  14411. version: ((ref4 = ua.match(/firefox\/(\d+(\.\d+)?)/i)) != null ? ref4[1] : void 0) * 1
  14412. };
  14413. } else {
  14414. return {};
  14415. }
  14416. })();
  14417. Util.prototype.support = (function() {
  14418. return {
  14419. onselectionchange: (function() {
  14420. var e, onselectionchange;
  14421. onselectionchange = document.onselectionchange;
  14422. if (onselectionchange !== void 0) {
  14423. try {
  14424. document.onselectionchange = 0;
  14425. return document.onselectionchange === null;
  14426. } catch (_error) {
  14427. e = _error;
  14428. } finally {
  14429. document.onselectionchange = onselectionchange;
  14430. }
  14431. }
  14432. return false;
  14433. })(),
  14434. oninput: (function() {
  14435. return !/(msie|trident)/i.test(navigator.userAgent);
  14436. })()
  14437. };
  14438. })();
  14439. Util.prototype.reflow = function(el) {
  14440. if (el == null) {
  14441. el = document;
  14442. }
  14443. return $(el)[0].offsetHeight;
  14444. };
  14445. Util.prototype.metaKey = function(e) {
  14446. var isMac;
  14447. isMac = /Mac/.test(navigator.userAgent);
  14448. if (isMac) {
  14449. return e.metaKey;
  14450. } else {
  14451. return e.ctrlKey;
  14452. }
  14453. };
  14454. Util.prototype.isEmptyNode = function(node) {
  14455. var $node;
  14456. $node = $(node);
  14457. return $node.is(':empty') || (!$node.text() && !$node.find(':not(br, span, div)').length);
  14458. };
  14459. Util.prototype.isDecoratedNode = function(node) {
  14460. return $(node).is('[class^="simditor-"]');
  14461. };
  14462. Util.prototype.blockNodes = ["div", "p", "ul", "ol", "li", "blockquote", "hr", "pre", "h1", "h2", "h3", "h4", "h5", "table"];
  14463. Util.prototype.isBlockNode = function(node) {
  14464. node = $(node)[0];
  14465. if (!node || node.nodeType === 3) {
  14466. return false;
  14467. }
  14468. return new RegExp("^(" + (this.blockNodes.join('|')) + ")$").test(node.nodeName.toLowerCase());
  14469. };
  14470. Util.prototype.getNodeLength = function(node) {
  14471. node = $(node)[0];
  14472. switch (node.nodeType) {
  14473. case 7:
  14474. case 10:
  14475. return 0;
  14476. case 3:
  14477. case 8:
  14478. return node.length;
  14479. default:
  14480. return node.childNodes.length;
  14481. }
  14482. };
  14483. Util.prototype.dataURLtoBlob = function(dataURL) {
  14484. var BlobBuilder, arrayBuffer, bb, blobArray, byteString, hasArrayBufferViewSupport, hasBlobConstructor, i, intArray, k, mimeString, ref, supportBlob;
  14485. hasBlobConstructor = window.Blob && (function() {
  14486. var e;
  14487. try {
  14488. return Boolean(new Blob());
  14489. } catch (_error) {
  14490. e = _error;
  14491. return false;
  14492. }
  14493. })();
  14494. hasArrayBufferViewSupport = hasBlobConstructor && window.Uint8Array && (function() {
  14495. var e;
  14496. try {
  14497. return new Blob([new Uint8Array(100)]).size === 100;
  14498. } catch (_error) {
  14499. e = _error;
  14500. return false;
  14501. }
  14502. })();
  14503. BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  14504. supportBlob = hasBlobConstructor || BlobBuilder;
  14505. if (!(supportBlob && window.atob && window.ArrayBuffer && window.Uint8Array)) {
  14506. return false;
  14507. }
  14508. if (dataURL.split(',')[0].indexOf('base64') >= 0) {
  14509. byteString = atob(dataURL.split(',')[1]);
  14510. } else {
  14511. byteString = decodeURIComponent(dataURL.split(',')[1]);
  14512. }
  14513. arrayBuffer = new ArrayBuffer(byteString.length);
  14514. intArray = new Uint8Array(arrayBuffer);
  14515. for (i = k = 0, ref = byteString.length; 0 <= ref ? k <= ref : k >= ref; i = 0 <= ref ? ++k : --k) {
  14516. intArray[i] = byteString.charCodeAt(i);
  14517. }
  14518. mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
  14519. if (hasBlobConstructor) {
  14520. blobArray = hasArrayBufferViewSupport ? intArray : arrayBuffer;
  14521. return new Blob([blobArray], {
  14522. type: mimeString
  14523. });
  14524. }
  14525. bb = new BlobBuilder();
  14526. bb.append(arrayBuffer);
  14527. return bb.getBlob(mimeString);
  14528. };
  14529. Util.prototype.throttle = function(func, wait) {
  14530. var args, call, ctx, last, rtn, throttled, timeoutID;
  14531. last = 0;
  14532. timeoutID = 0;
  14533. ctx = args = rtn = null;
  14534. call = function() {
  14535. timeoutID = 0;
  14536. last = +new Date();
  14537. rtn = func.apply(ctx, args);
  14538. ctx = null;
  14539. return args = null;
  14540. };
  14541. throttled = function() {
  14542. var delta;
  14543. ctx = this;
  14544. args = arguments;
  14545. delta = new Date() - last;
  14546. if (!timeoutID) {
  14547. if (delta >= wait) {
  14548. call();
  14549. } else {
  14550. timeoutID = setTimeout(call, wait - delta);
  14551. }
  14552. }
  14553. return rtn;
  14554. };
  14555. throttled.clear = function() {
  14556. if (!timeoutID) {
  14557. return;
  14558. }
  14559. clearTimeout(timeoutID);
  14560. return call();
  14561. };
  14562. return throttled;
  14563. };
  14564. Util.prototype.formatHTML = function(html) {
  14565. var cursor, indentString, lastMatch, level, match, re, repeatString, result, str;
  14566. re = /<(\/?)(.+?)(\/?)>/g;
  14567. result = '';
  14568. level = 0;
  14569. lastMatch = null;
  14570. indentString = ' ';
  14571. repeatString = function(str, n) {
  14572. return new Array(n + 1).join(str);
  14573. };
  14574. while ((match = re.exec(html)) !== null) {
  14575. match.isBlockNode = $.inArray(match[2], this.blockNodes) > -1;
  14576. match.isStartTag = match[1] !== '/' && match[3] !== '/';
  14577. match.isEndTag = match[1] === '/' || match[3] === '/';
  14578. cursor = lastMatch ? lastMatch.index + lastMatch[0].length : 0;
  14579. if ((str = html.substring(cursor, match.index)).length > 0 && $.trim(str)) {
  14580. result += str;
  14581. }
  14582. if (match.isBlockNode && match.isEndTag && !match.isStartTag) {
  14583. level -= 1;
  14584. }
  14585. if (match.isBlockNode && match.isStartTag) {
  14586. if (!(lastMatch && lastMatch.isBlockNode && lastMatch.isEndTag)) {
  14587. result += '\n';
  14588. }
  14589. result += repeatString(indentString, level);
  14590. }
  14591. result += match[0];
  14592. if (match.isBlockNode && match.isEndTag) {
  14593. result += '\n';
  14594. }
  14595. if (match.isBlockNode && match.isStartTag) {
  14596. level += 1;
  14597. }
  14598. lastMatch = match;
  14599. }
  14600. return $.trim(result);
  14601. };
  14602. return Util;
  14603. })(SimpleModule);
  14604. Toolbar = (function(superClass) {
  14605. extend(Toolbar, superClass);
  14606. function Toolbar() {
  14607. return Toolbar.__super__.constructor.apply(this, arguments);
  14608. }
  14609. Toolbar.pluginName = 'Toolbar';
  14610. Toolbar.prototype.opts = {
  14611. toolbar: true,
  14612. toolbarFloat: true,
  14613. toolbarHidden: false,
  14614. toolbarFloatOffset: 0
  14615. };
  14616. Toolbar.prototype._tpl = {
  14617. wrapper: '<div class="simditor-toolbar"><ul></ul></div>',
  14618. separator: '<li><span class="separator"></span></li>'
  14619. };
  14620. Toolbar.prototype._init = function() {
  14621. var floatInitialized, initToolbarFloat, toolbarHeight;
  14622. this.editor = this._module;
  14623. if (!this.opts.toolbar) {
  14624. return;
  14625. }
  14626. if (!$.isArray(this.opts.toolbar)) {
  14627. this.opts.toolbar = ['bold', 'italic', 'underline', 'strikethrough', '|', 'ol', 'ul', 'blockquote', 'code', '|', 'link', 'image', '|', 'indent', 'outdent'];
  14628. }
  14629. this._render();
  14630. this.list.on('click', function(e) {
  14631. return false;
  14632. });
  14633. this.wrapper.on('mousedown', (function(_this) {
  14634. return function(e) {
  14635. return _this.list.find('.menu-on').removeClass('.menu-on');
  14636. };
  14637. })(this));
  14638. $(document).on('mousedown.simditor' + this.editor.id, (function(_this) {
  14639. return function(e) {
  14640. return _this.list.find('.menu-on').removeClass('.menu-on');
  14641. };
  14642. })(this));
  14643. if (!this.opts.toolbarHidden && this.opts.toolbarFloat) {
  14644. this.wrapper.css('top', this.opts.toolbarFloatOffset);
  14645. toolbarHeight = 0;
  14646. initToolbarFloat = (function(_this) {
  14647. return function() {
  14648. _this.wrapper.css('position', 'static');
  14649. _this.wrapper.width('auto');
  14650. _this.editor.util.reflow(_this.wrapper);
  14651. _this.wrapper.width(_this.wrapper.outerWidth());
  14652. _this.wrapper.css('left', _this.editor.util.os.mobile ? _this.wrapper.position().left : _this.wrapper.offset().left);
  14653. _this.wrapper.css('position', '');
  14654. toolbarHeight = _this.wrapper.outerHeight();
  14655. _this.editor.placeholderEl.css('top', toolbarHeight);
  14656. return true;
  14657. };
  14658. })(this);
  14659. floatInitialized = null;
  14660. $(window).on('resize.simditor-' + this.editor.id, function(e) {
  14661. return floatInitialized = initToolbarFloat();
  14662. });
  14663. $(window).on('scroll.simditor-' + this.editor.id, (function(_this) {
  14664. return function(e) {
  14665. var bottomEdge, scrollTop, topEdge;
  14666. if (!_this.wrapper.is(':visible')) {
  14667. return;
  14668. }
  14669. topEdge = _this.editor.wrapper.offset().top;
  14670. bottomEdge = topEdge + _this.editor.wrapper.outerHeight() - 80;
  14671. scrollTop = $(document).scrollTop() + _this.opts.toolbarFloatOffset;
  14672. if (scrollTop <= topEdge || scrollTop >= bottomEdge) {
  14673. _this.editor.wrapper.removeClass('toolbar-floating').css('padding-top', '');
  14674. if (_this.editor.util.os.mobile) {
  14675. return _this.wrapper.css('top', _this.opts.toolbarFloatOffset);
  14676. }
  14677. } else {
  14678. floatInitialized || (floatInitialized = initToolbarFloat());
  14679. _this.editor.wrapper.addClass('toolbar-floating').css('padding-top', toolbarHeight);
  14680. if (_this.editor.util.os.mobile) {
  14681. return _this.wrapper.css('top', scrollTop - topEdge + _this.opts.toolbarFloatOffset);
  14682. }
  14683. }
  14684. };
  14685. })(this));
  14686. }
  14687. this.editor.on('destroy', (function(_this) {
  14688. return function() {
  14689. return _this.buttons.length = 0;
  14690. };
  14691. })(this));
  14692. return $(document).on("mousedown.simditor-" + this.editor.id, (function(_this) {
  14693. return function(e) {
  14694. return _this.list.find('li.menu-on').removeClass('menu-on');
  14695. };
  14696. })(this));
  14697. };
  14698. Toolbar.prototype._render = function() {
  14699. var k, len, name, ref;
  14700. this.buttons = [];
  14701. this.wrapper = $(this._tpl.wrapper).prependTo(this.editor.wrapper);
  14702. this.list = this.wrapper.find('ul');
  14703. ref = this.opts.toolbar;
  14704. for (k = 0, len = ref.length; k < len; k++) {
  14705. name = ref[k];
  14706. if (name === '|') {
  14707. $(this._tpl.separator).appendTo(this.list);
  14708. continue;
  14709. }
  14710. if (!this.constructor.buttons[name]) {
  14711. throw new Error("simditor: invalid toolbar button " + name);
  14712. continue;
  14713. }
  14714. this.buttons.push(new this.constructor.buttons[name]({
  14715. editor: this.editor
  14716. }));
  14717. }
  14718. if (this.opts.toolbarHidden) {
  14719. return this.wrapper.hide();
  14720. }
  14721. };
  14722. Toolbar.prototype.findButton = function(name) {
  14723. var button;
  14724. button = this.list.find('.toolbar-item-' + name).data('button');
  14725. return button != null ? button : null;
  14726. };
  14727. Toolbar.addButton = function(btn) {
  14728. return this.buttons[btn.prototype.name] = btn;
  14729. };
  14730. Toolbar.buttons = {};
  14731. return Toolbar;
  14732. })(SimpleModule);
  14733. Indentation = (function(superClass) {
  14734. extend(Indentation, superClass);
  14735. function Indentation() {
  14736. return Indentation.__super__.constructor.apply(this, arguments);
  14737. }
  14738. Indentation.pluginName = 'Indentation';
  14739. Indentation.prototype.opts = {
  14740. tabIndent: true
  14741. };
  14742. Indentation.prototype._init = function() {
  14743. this.editor = this._module;
  14744. return this.editor.keystroke.add('tab', '*', (function(_this) {
  14745. return function(e) {
  14746. var codeButton;
  14747. codeButton = _this.editor.toolbar.findButton('code');
  14748. if (!(_this.opts.tabIndent || (codeButton && codeButton.active))) {
  14749. return;
  14750. }
  14751. return _this.indent(e.shiftKey);
  14752. };
  14753. })(this));
  14754. };
  14755. Indentation.prototype.indent = function(isBackward) {
  14756. var $blockNodes, $endNodes, $startNodes, nodes, result;
  14757. $startNodes = this.editor.selection.startNodes();
  14758. $endNodes = this.editor.selection.endNodes();
  14759. $blockNodes = this.editor.selection.blockNodes();
  14760. nodes = [];
  14761. $blockNodes = $blockNodes.each(function(i, node) {
  14762. var include, j, k, len, n;
  14763. include = true;
  14764. for (j = k = 0, len = nodes.length; k < len; j = ++k) {
  14765. n = nodes[j];
  14766. if ($.contains(node, n)) {
  14767. include = false;
  14768. break;
  14769. } else if ($.contains(n, node)) {
  14770. nodes.splice(j, 1, node);
  14771. include = false;
  14772. break;
  14773. }
  14774. }
  14775. if (include) {
  14776. return nodes.push(node);
  14777. }
  14778. });
  14779. $blockNodes = $(nodes);
  14780. result = false;
  14781. $blockNodes.each((function(_this) {
  14782. return function(i, blockEl) {
  14783. var r;
  14784. r = isBackward ? _this.outdentBlock(blockEl) : _this.indentBlock(blockEl);
  14785. if (r) {
  14786. return result = r;
  14787. }
  14788. };
  14789. })(this));
  14790. return result;
  14791. };
  14792. Indentation.prototype.indentBlock = function(blockEl) {
  14793. var $blockEl, $childList, $nextTd, $nextTr, $parentLi, $pre, $td, $tr, marginLeft, tagName;
  14794. $blockEl = $(blockEl);
  14795. if (!$blockEl.length) {
  14796. return;
  14797. }
  14798. if ($blockEl.is('pre')) {
  14799. $pre = this.editor.selection.containerNode();
  14800. if (!($pre.is($blockEl) || $pre.closest('pre').is($blockEl))) {
  14801. return;
  14802. }
  14803. this.indentText(this.editor.selection.range());
  14804. } else if ($blockEl.is('li')) {
  14805. $parentLi = $blockEl.prev('li');
  14806. if ($parentLi.length < 1) {
  14807. return;
  14808. }
  14809. this.editor.selection.save();
  14810. tagName = $blockEl.parent()[0].tagName;
  14811. $childList = $parentLi.children('ul, ol');
  14812. if ($childList.length > 0) {
  14813. $childList.append($blockEl);
  14814. } else {
  14815. $('<' + tagName + '/>').append($blockEl).appendTo($parentLi);
  14816. }
  14817. this.editor.selection.restore();
  14818. } else if ($blockEl.is('p, h1, h2, h3, h4')) {
  14819. marginLeft = parseInt($blockEl.css('margin-left')) || 0;
  14820. marginLeft = (Math.round(marginLeft / this.opts.indentWidth) + 1) * this.opts.indentWidth;
  14821. $blockEl.css('margin-left', marginLeft);
  14822. } else if ($blockEl.is('table') || $blockEl.is('.simditor-table')) {
  14823. $td = this.editor.selection.containerNode().closest('td, th');
  14824. $nextTd = $td.next('td, th');
  14825. if (!($nextTd.length > 0)) {
  14826. $tr = $td.parent('tr');
  14827. $nextTr = $tr.next('tr');
  14828. if ($nextTr.length < 1 && $tr.parent().is('thead')) {
  14829. $nextTr = $tr.parent('thead').next('tbody').find('tr:first');
  14830. }
  14831. $nextTd = $nextTr.find('td:first, th:first');
  14832. }
  14833. if (!($td.length > 0 && $nextTd.length > 0)) {
  14834. return;
  14835. }
  14836. this.editor.selection.setRangeAtEndOf($nextTd);
  14837. } else {
  14838. return false;
  14839. }
  14840. return true;
  14841. };
  14842. Indentation.prototype.indentText = function(range) {
  14843. var text, textNode;
  14844. text = range.toString().replace(/^(?=.+)/mg, '\u00A0\u00A0');
  14845. textNode = document.createTextNode(text || '\u00A0\u00A0');
  14846. range.deleteContents();
  14847. range.insertNode(textNode);
  14848. if (text) {
  14849. range.selectNode(textNode);
  14850. return this.editor.selection.range(range);
  14851. } else {
  14852. return this.editor.selection.setRangeAfter(textNode);
  14853. }
  14854. };
  14855. Indentation.prototype.outdentBlock = function(blockEl) {
  14856. var $blockEl, $parent, $parentLi, $pre, $prevTd, $prevTr, $td, $tr, marginLeft, range;
  14857. $blockEl = $(blockEl);
  14858. if (!($blockEl && $blockEl.length > 0)) {
  14859. return;
  14860. }
  14861. if ($blockEl.is('pre')) {
  14862. $pre = this.editor.selection.containerNode();
  14863. if (!($pre.is($blockEl) || $pre.closest('pre').is($blockEl))) {
  14864. return;
  14865. }
  14866. this.outdentText(range);
  14867. } else if ($blockEl.is('li')) {
  14868. $parent = $blockEl.parent();
  14869. $parentLi = $parent.parent('li');
  14870. this.editor.selection.save();
  14871. if ($parentLi.length < 1) {
  14872. range = document.createRange();
  14873. range.setStartBefore($parent[0]);
  14874. range.setEndBefore($blockEl[0]);
  14875. $parent.before(range.extractContents());
  14876. $('<p/>').insertBefore($parent).after($blockEl.children('ul, ol')).append($blockEl.contents());
  14877. $blockEl.remove();
  14878. } else {
  14879. if ($blockEl.next('li').length > 0) {
  14880. $('<' + $parent[0].tagName + '/>').append($blockEl.nextAll('li')).appendTo($blockEl);
  14881. }
  14882. $blockEl.insertAfter($parentLi);
  14883. if ($parent.children('li').length < 1) {
  14884. $parent.remove();
  14885. }
  14886. }
  14887. this.editor.selection.restore();
  14888. } else if ($blockEl.is('p, h1, h2, h3, h4')) {
  14889. marginLeft = parseInt($blockEl.css('margin-left')) || 0;
  14890. marginLeft = Math.max(Math.round(marginLeft / this.opts.indentWidth) - 1, 0) * this.opts.indentWidth;
  14891. $blockEl.css('margin-left', marginLeft === 0 ? '' : marginLeft);
  14892. } else if ($blockEl.is('table') || $blockEl.is('.simditor-table')) {
  14893. $td = this.editor.selection.containerNode().closest('td, th');
  14894. $prevTd = $td.prev('td, th');
  14895. if (!($prevTd.length > 0)) {
  14896. $tr = $td.parent('tr');
  14897. $prevTr = $tr.prev('tr');
  14898. if ($prevTr.length < 1 && $tr.parent().is('tbody')) {
  14899. $prevTr = $tr.parent('tbody').prev('thead').find('tr:first');
  14900. }
  14901. $prevTd = $prevTr.find('td:last, th:last');
  14902. }
  14903. if (!($td.length > 0 && $prevTd.length > 0)) {
  14904. return;
  14905. }
  14906. this.editor.selection.setRangeAtEndOf($prevTd);
  14907. } else {
  14908. return false;
  14909. }
  14910. return true;
  14911. };
  14912. Indentation.prototype.outdentText = function(range) {};
  14913. return Indentation;
  14914. })(SimpleModule);
  14915. Clipboard = (function(superClass) {
  14916. extend(Clipboard, superClass);
  14917. function Clipboard() {
  14918. return Clipboard.__super__.constructor.apply(this, arguments);
  14919. }
  14920. Clipboard.pluginName = 'Clipboard';
  14921. Clipboard.prototype.opts = {
  14922. pasteImage: false,
  14923. cleanPaste: false
  14924. };
  14925. Clipboard.prototype._init = function() {
  14926. this.editor = this._module;
  14927. if (this.opts.pasteImage && typeof this.opts.pasteImage !== 'string') {
  14928. this.opts.pasteImage = 'inline';
  14929. }
  14930. return this.editor.body.on('paste', (function(_this) {
  14931. return function(e) {
  14932. var range;
  14933. if (_this.pasting || _this._pasteBin) {
  14934. return;
  14935. }
  14936. if (_this.editor.triggerHandler(e) === false) {
  14937. return false;
  14938. }
  14939. range = _this.editor.selection.deleteRangeContents();
  14940. if (_this.editor.body.html()) {
  14941. if (!range.collapsed) {
  14942. range.collapse(true);
  14943. }
  14944. } else {
  14945. _this.editor.formatter.format();
  14946. _this.editor.selection.setRangeAtStartOf(_this.editor.body.find('p:first'));
  14947. }
  14948. if (_this._processPasteByClipboardApi(e)) {
  14949. return false;
  14950. }
  14951. _this.editor.inputManager.throttledValueChanged.clear();
  14952. _this.editor.inputManager.throttledSelectionChanged.clear();
  14953. _this.editor.undoManager.throttledPushState.clear();
  14954. _this.editor.selection.reset();
  14955. _this.editor.undoManager.resetCaretPosition();
  14956. _this.pasting = true;
  14957. return _this._getPasteContent(function(pasteContent) {
  14958. _this._processPasteContent(pasteContent);
  14959. _this._pasteInBlockEl = null;
  14960. _this._pastePlainText = null;
  14961. return _this.pasting = false;
  14962. });
  14963. };
  14964. })(this));
  14965. };
  14966. Clipboard.prototype._processPasteByClipboardApi = function(e) {
  14967. var imageFile, pasteItem, ref, uploadOpt;
  14968. if (this.editor.util.browser.edge) {
  14969. return;
  14970. }
  14971. if (e.originalEvent.clipboardData && e.originalEvent.clipboardData.items && e.originalEvent.clipboardData.items.length > 0) {
  14972. pasteItem = e.originalEvent.clipboardData.items[0];
  14973. if (/^image\//.test(pasteItem.type)) {
  14974. imageFile = pasteItem.getAsFile();
  14975. if (!((imageFile != null) && this.opts.pasteImage)) {
  14976. return;
  14977. }
  14978. if (!imageFile.name) {
  14979. imageFile.name = "Clipboard Image.png";
  14980. }
  14981. if (this.editor.triggerHandler('pasting', [imageFile]) === false) {
  14982. return;
  14983. }
  14984. uploadOpt = {};
  14985. uploadOpt[this.opts.pasteImage] = true;
  14986. if ((ref = this.editor.uploader) != null) {
  14987. ref.upload(imageFile, uploadOpt);
  14988. }
  14989. return true;
  14990. }
  14991. }
  14992. };
  14993. Clipboard.prototype._getPasteContent = function(callback) {
  14994. var state;
  14995. this._pasteBin = $('<div contenteditable="true" />').addClass('simditor-paste-bin').attr('tabIndex', '-1').appendTo(this.editor.el);
  14996. state = {
  14997. html: this.editor.body.html(),
  14998. caret: this.editor.undoManager.caretPosition()
  14999. };
  15000. this._pasteBin.focus();
  15001. return setTimeout((function(_this) {
  15002. return function() {
  15003. var pasteContent;
  15004. _this.editor.hidePopover();
  15005. _this.editor.body.get(0).innerHTML = state.html;
  15006. _this.editor.undoManager.caretPosition(state.caret);
  15007. _this.editor.body.focus();
  15008. _this.editor.selection.reset();
  15009. _this.editor.selection.range();
  15010. _this._pasteInBlockEl = _this.editor.selection.blockNodes().last();
  15011. _this._pastePlainText = _this.opts.cleanPaste || _this._pasteInBlockEl.is('pre, table');
  15012. if (_this._pastePlainText) {
  15013. pasteContent = _this.editor.formatter.clearHtml(_this._pasteBin.html(), true);
  15014. } else {
  15015. pasteContent = $('<div/>').append(_this._pasteBin.contents());
  15016. pasteContent.find('table colgroup').remove();
  15017. _this.editor.formatter.format(pasteContent);
  15018. _this.editor.formatter.decorate(pasteContent);
  15019. _this.editor.formatter.beautify(pasteContent.children());
  15020. pasteContent = pasteContent.contents();
  15021. }
  15022. _this._pasteBin.remove();
  15023. _this._pasteBin = null;
  15024. return callback(pasteContent);
  15025. };
  15026. })(this), 0);
  15027. };
  15028. Clipboard.prototype._processPasteContent = function(pasteContent) {
  15029. var $blockEl, $img, blob, children, insertPosition, k, l, lastLine, len, len1, len2, len3, len4, line, lines, m, node, o, q, ref, ref1, ref2, uploadOpt;
  15030. if (this.editor.triggerHandler('pasting', [pasteContent]) === false) {
  15031. return;
  15032. }
  15033. $blockEl = this._pasteInBlockEl;
  15034. if (!pasteContent) {
  15035. return;
  15036. } else if (this._pastePlainText) {
  15037. if ($blockEl.is('table')) {
  15038. lines = pasteContent.split('\n');
  15039. lastLine = lines.pop();
  15040. for (k = 0, len = lines.length; k < len; k++) {
  15041. line = lines[k];
  15042. this.editor.selection.insertNode(document.createTextNode(line));
  15043. this.editor.selection.insertNode($('<br/>'));
  15044. }
  15045. this.editor.selection.insertNode(document.createTextNode(lastLine));
  15046. } else {
  15047. pasteContent = $('<div/>').text(pasteContent);
  15048. ref = pasteContent.contents();
  15049. for (l = 0, len1 = ref.length; l < len1; l++) {
  15050. node = ref[l];
  15051. this.editor.selection.insertNode($(node)[0]);
  15052. }
  15053. }
  15054. } else if ($blockEl.is(this.editor.body)) {
  15055. for (m = 0, len2 = pasteContent.length; m < len2; m++) {
  15056. node = pasteContent[m];
  15057. this.editor.selection.insertNode(node);
  15058. }
  15059. } else if (pasteContent.length < 1) {
  15060. return;
  15061. } else if (pasteContent.length === 1) {
  15062. if (pasteContent.is('p')) {
  15063. children = pasteContent.contents();
  15064. if (children.length === 1 && children.is('img')) {
  15065. $img = children;
  15066. if (/^data:image/.test($img.attr('src'))) {
  15067. if (!this.opts.pasteImage) {
  15068. return;
  15069. }
  15070. blob = this.editor.util.dataURLtoBlob($img.attr("src"));
  15071. blob.name = "Clipboard Image.png";
  15072. uploadOpt = {};
  15073. uploadOpt[this.opts.pasteImage] = true;
  15074. if ((ref1 = this.editor.uploader) != null) {
  15075. ref1.upload(blob, uploadOpt);
  15076. }
  15077. return;
  15078. } else if ($img.is('img[src^="webkit-fake-url://"]')) {
  15079. return;
  15080. }
  15081. }
  15082. for (o = 0, len3 = children.length; o < len3; o++) {
  15083. node = children[o];
  15084. this.editor.selection.insertNode(node);
  15085. }
  15086. } else if ($blockEl.is('p') && this.editor.util.isEmptyNode($blockEl)) {
  15087. $blockEl.replaceWith(pasteContent);
  15088. this.editor.selection.setRangeAtEndOf(pasteContent);
  15089. } else if (pasteContent.is('ul, ol')) {
  15090. if (pasteContent.find('li').length === 1) {
  15091. pasteContent = $('<div/>').text(pasteContent.text());
  15092. ref2 = pasteContent.contents();
  15093. for (q = 0, len4 = ref2.length; q < len4; q++) {
  15094. node = ref2[q];
  15095. this.editor.selection.insertNode($(node)[0]);
  15096. }
  15097. } else if ($blockEl.is('li')) {
  15098. $blockEl.parent().after(pasteContent);
  15099. this.editor.selection.setRangeAtEndOf(pasteContent);
  15100. } else {
  15101. $blockEl.after(pasteContent);
  15102. this.editor.selection.setRangeAtEndOf(pasteContent);
  15103. }
  15104. } else {
  15105. $blockEl.after(pasteContent);
  15106. this.editor.selection.setRangeAtEndOf(pasteContent);
  15107. }
  15108. } else {
  15109. if ($blockEl.is('li')) {
  15110. $blockEl = $blockEl.parent();
  15111. }
  15112. if (this.editor.selection.rangeAtStartOf($blockEl)) {
  15113. insertPosition = 'before';
  15114. } else if (this.editor.selection.rangeAtEndOf($blockEl)) {
  15115. insertPosition = 'after';
  15116. } else {
  15117. this.editor.selection.breakBlockEl($blockEl);
  15118. insertPosition = 'before';
  15119. }
  15120. $blockEl[insertPosition](pasteContent);
  15121. this.editor.selection.setRangeAtEndOf(pasteContent.last());
  15122. }
  15123. return this.editor.inputManager.throttledValueChanged();
  15124. };
  15125. return Clipboard;
  15126. })(SimpleModule);
  15127. Simditor = (function(superClass) {
  15128. extend(Simditor, superClass);
  15129. function Simditor() {
  15130. return Simditor.__super__.constructor.apply(this, arguments);
  15131. }
  15132. Simditor.connect(Util);
  15133. Simditor.connect(InputManager);
  15134. Simditor.connect(Selection);
  15135. Simditor.connect(UndoManager);
  15136. Simditor.connect(Keystroke);
  15137. Simditor.connect(Formatter);
  15138. Simditor.connect(Toolbar);
  15139. Simditor.connect(Indentation);
  15140. Simditor.connect(Clipboard);
  15141. Simditor.count = 0;
  15142. Simditor.prototype.opts = {
  15143. textarea: null,
  15144. placeholder: '',
  15145. defaultImage: 'images/image.png',
  15146. params: {},
  15147. upload: false,
  15148. indentWidth: 40
  15149. };
  15150. Simditor.prototype._init = function() {
  15151. var e, editor, form, uploadOpts;
  15152. this.textarea = $(this.opts.textarea);
  15153. this.opts.placeholder = this.opts.placeholder || this.textarea.attr('placeholder');
  15154. if (!this.textarea.length) {
  15155. throw new Error('simditor: param textarea is required.');
  15156. return;
  15157. }
  15158. editor = this.textarea.data('simditor');
  15159. if (editor != null) {
  15160. editor.destroy();
  15161. }
  15162. this.id = ++Simditor.count;
  15163. this._render();
  15164. if (simpleHotkeys) {
  15165. this.hotkeys = simpleHotkeys({
  15166. el: this.body
  15167. });
  15168. } else {
  15169. throw new Error('simditor: simple-hotkeys is required.');
  15170. return;
  15171. }
  15172. if (this.opts.upload && simpleUploader) {
  15173. uploadOpts = typeof this.opts.upload === 'object' ? this.opts.upload : {};
  15174. this.uploader = simpleUploader(uploadOpts);
  15175. }
  15176. form = this.textarea.closest('form');
  15177. if (form.length) {
  15178. form.on('submit.simditor-' + this.id, (function(_this) {
  15179. return function() {
  15180. return _this.sync();
  15181. };
  15182. })(this));
  15183. form.on('reset.simditor-' + this.id, (function(_this) {
  15184. return function() {
  15185. return _this.setValue('');
  15186. };
  15187. })(this));
  15188. }
  15189. this.on('initialized', (function(_this) {
  15190. return function() {
  15191. if (_this.opts.placeholder) {
  15192. _this.on('valuechanged', function() {
  15193. return _this._placeholder();
  15194. });
  15195. }
  15196. _this.setValue(_this.textarea.val().trim() || '');
  15197. if (_this.textarea.attr('autofocus')) {
  15198. return _this.focus();
  15199. }
  15200. };
  15201. })(this));
  15202. if (this.util.browser.mozilla) {
  15203. this.util.reflow();
  15204. try {
  15205. document.execCommand('enableObjectResizing', false, false);
  15206. return document.execCommand('enableInlineTableEditing', false, false);
  15207. } catch (_error) {
  15208. e = _error;
  15209. }
  15210. }
  15211. };
  15212. Simditor.prototype._tpl = "<div class=\"simditor\">\n <div class=\"simditor-wrapper\">\n <div class=\"simditor-placeholder\"></div>\n <div class=\"simditor-body\" contenteditable=\"true\">\n </div>\n </div>\n</div>";
  15213. Simditor.prototype._render = function() {
  15214. var key, ref, results, val;
  15215. this.el = $(this._tpl).insertBefore(this.textarea);
  15216. this.wrapper = this.el.find('.simditor-wrapper');
  15217. this.body = this.wrapper.find('.simditor-body');
  15218. this.placeholderEl = this.wrapper.find('.simditor-placeholder').append(this.opts.placeholder);
  15219. this.el.data('simditor', this);
  15220. this.wrapper.append(this.textarea);
  15221. this.textarea.data('simditor', this).blur();
  15222. this.body.attr('tabindex', this.textarea.attr('tabindex'));
  15223. if (this.util.os.mac) {
  15224. this.el.addClass('simditor-mac');
  15225. } else if (this.util.os.linux) {
  15226. this.el.addClass('simditor-linux');
  15227. }
  15228. if (this.util.os.mobile) {
  15229. this.el.addClass('simditor-mobile');
  15230. }
  15231. if (this.opts.params) {
  15232. ref = this.opts.params;
  15233. results = [];
  15234. for (key in ref) {
  15235. val = ref[key];
  15236. results.push($('<input/>', {
  15237. type: 'hidden',
  15238. name: key,
  15239. value: val
  15240. }).insertAfter(this.textarea));
  15241. }
  15242. return results;
  15243. }
  15244. };
  15245. Simditor.prototype._placeholder = function() {
  15246. var children;
  15247. children = this.body.children();
  15248. if (children.length === 0 || (children.length === 1 && this.util.isEmptyNode(children) && parseInt(children.css('margin-left') || 0) < this.opts.indentWidth)) {
  15249. return this.placeholderEl.show();
  15250. } else {
  15251. return this.placeholderEl.hide();
  15252. }
  15253. };
  15254. Simditor.prototype.setValue = function(val) {
  15255. this.hidePopover();
  15256. this.textarea.val(val);
  15257. this.body.get(0).innerHTML = val;
  15258. this.formatter.format();
  15259. this.formatter.decorate();
  15260. this.util.reflow(this.body);
  15261. this.inputManager.lastCaretPosition = null;
  15262. return this.trigger('valuechanged');
  15263. };
  15264. Simditor.prototype.getValue = function() {
  15265. return this.sync();
  15266. };
  15267. Simditor.prototype.sync = function() {
  15268. var children, cloneBody, emptyP, firstP, lastP, val;
  15269. cloneBody = this.body.clone();
  15270. this.formatter.undecorate(cloneBody);
  15271. this.formatter.format(cloneBody);
  15272. this.formatter.autolink(cloneBody);
  15273. children = cloneBody.children();
  15274. lastP = children.last('p');
  15275. firstP = children.first('p');
  15276. while (lastP.is('p') && this.util.isEmptyNode(lastP)) {
  15277. emptyP = lastP;
  15278. lastP = lastP.prev('p');
  15279. emptyP.remove();
  15280. }
  15281. while (firstP.is('p') && this.util.isEmptyNode(firstP)) {
  15282. emptyP = firstP;
  15283. firstP = lastP.next('p');
  15284. emptyP.remove();
  15285. }
  15286. cloneBody.find('img.uploading').remove();
  15287. val = $.trim(cloneBody.html());
  15288. this.textarea.val(val);
  15289. return val;
  15290. };
  15291. Simditor.prototype.focus = function() {
  15292. var $blockEl, range;
  15293. if (!(this.body.is(':visible') && this.body.is('[contenteditable]'))) {
  15294. this.el.find('textarea:visible').focus();
  15295. return;
  15296. }
  15297. if (this.inputManager.lastCaretPosition) {
  15298. this.undoManager.caretPosition(this.inputManager.lastCaretPosition);
  15299. return this.inputManager.lastCaretPosition = null;
  15300. } else {
  15301. $blockEl = this.body.children().last();
  15302. if (!$blockEl.is('p')) {
  15303. $blockEl = $('<p/>').append(this.util.phBr).appendTo(this.body);
  15304. }
  15305. range = document.createRange();
  15306. return this.selection.setRangeAtEndOf($blockEl, range);
  15307. }
  15308. };
  15309. Simditor.prototype.blur = function() {
  15310. if (this.body.is(':visible') && this.body.is('[contenteditable]')) {
  15311. return this.body.blur();
  15312. } else {
  15313. return this.body.find('textarea:visible').blur();
  15314. }
  15315. };
  15316. Simditor.prototype.hidePopover = function() {
  15317. return this.el.find('.simditor-popover').each(function(i, popover) {
  15318. popover = $(popover).data('popover');
  15319. if (popover.active) {
  15320. return popover.hide();
  15321. }
  15322. });
  15323. };
  15324. Simditor.prototype.destroy = function() {
  15325. this.triggerHandler('destroy');
  15326. this.textarea.closest('form').off('.simditor .simditor-' + this.id);
  15327. this.selection.clear();
  15328. this.inputManager.focused = false;
  15329. this.textarea.insertBefore(this.el).hide().val('').removeData('simditor');
  15330. this.el.remove();
  15331. $(document).off('.simditor-' + this.id);
  15332. $(window).off('.simditor-' + this.id);
  15333. return this.off();
  15334. };
  15335. return Simditor;
  15336. })(SimpleModule);
  15337. Simditor.i18n = {
  15338. 'zh-CN': {
  15339. 'blockquote': '引用',
  15340. 'bold': '加粗文字',
  15341. 'code': '插入代码',
  15342. 'color': '文字颜色',
  15343. 'coloredText': '彩色文字',
  15344. 'hr': '分隔线',
  15345. 'image': '插入图片',
  15346. 'externalImage': '外链图片',
  15347. 'uploadImage': '上传图片',
  15348. 'uploadFailed': '上传失败了',
  15349. 'uploadError': '上传出错了',
  15350. 'imageUrl': '图片地址',
  15351. 'imageSize': '图片尺寸',
  15352. 'imageAlt': '图片描述',
  15353. 'restoreImageSize': '还原图片尺寸',
  15354. 'uploading': '正在上传',
  15355. 'indent': '向右缩进',
  15356. 'outdent': '向左缩进',
  15357. 'italic': '斜体文字',
  15358. 'link': '插入链接',
  15359. 'linkText': '链接文字',
  15360. 'linkUrl': '链接地址',
  15361. 'linkTarget': '打开方式',
  15362. 'openLinkInCurrentWindow': '在新窗口中打开',
  15363. 'openLinkInNewWindow': '在当前窗口中打开',
  15364. 'removeLink': '移除链接',
  15365. 'ol': '有序列表',
  15366. 'ul': '无序列表',
  15367. 'strikethrough': '删除线文字',
  15368. 'table': '表格',
  15369. 'deleteRow': '删除行',
  15370. 'insertRowAbove': '在上面插入行',
  15371. 'insertRowBelow': '在下面插入行',
  15372. 'deleteColumn': '删除列',
  15373. 'insertColumnLeft': '在左边插入列',
  15374. 'insertColumnRight': '在右边插入列',
  15375. 'deleteTable': '删除表格',
  15376. 'title': '标题',
  15377. 'normalText': '普通文本',
  15378. 'underline': '下划线文字',
  15379. 'alignment': '水平对齐',
  15380. 'alignCenter': '居中',
  15381. 'alignLeft': '居左',
  15382. 'alignRight': '居右',
  15383. 'selectLanguage': '选择程序语言',
  15384. 'fontScale': '字体大小',
  15385. 'fontScaleXLarge': '超大字体',
  15386. 'fontScaleLarge': '大号字体',
  15387. 'fontScaleNormal': '正常大小',
  15388. 'fontScaleSmall': '小号字体',
  15389. 'fontScaleXSmall': '超小字体'
  15390. },
  15391. 'en-US': {
  15392. 'blockquote': 'Block Quote',
  15393. 'bold': 'Bold',
  15394. 'code': 'Code',
  15395. 'color': 'Text Color',
  15396. 'coloredText': 'Colored Text',
  15397. 'hr': 'Horizontal Line',
  15398. 'image': 'Insert Image',
  15399. 'externalImage': 'External Image',
  15400. 'uploadImage': 'Upload Image',
  15401. 'uploadFailed': 'Upload failed',
  15402. 'uploadError': 'Error occurs during upload',
  15403. 'imageUrl': 'Url',
  15404. 'imageSize': 'Size',
  15405. 'imageAlt': 'Alt',
  15406. 'restoreImageSize': 'Restore Origin Size',
  15407. 'uploading': 'Uploading',
  15408. 'indent': 'Indent',
  15409. 'outdent': 'Outdent',
  15410. 'italic': 'Italic',
  15411. 'link': 'Insert Link',
  15412. 'linkText': 'Text',
  15413. 'linkUrl': 'Url',
  15414. 'linkTarget': 'Target',
  15415. 'openLinkInCurrentWindow': 'Open link in current window',
  15416. 'openLinkInNewWindow': 'Open link in new window',
  15417. 'removeLink': 'Remove Link',
  15418. 'ol': 'Ordered List',
  15419. 'ul': 'Unordered List',
  15420. 'strikethrough': 'Strikethrough',
  15421. 'table': 'Table',
  15422. 'deleteRow': 'Delete Row',
  15423. 'insertRowAbove': 'Insert Row Above',
  15424. 'insertRowBelow': 'Insert Row Below',
  15425. 'deleteColumn': 'Delete Column',
  15426. 'insertColumnLeft': 'Insert Column Left',
  15427. 'insertColumnRight': 'Insert Column Right',
  15428. 'deleteTable': 'Delete Table',
  15429. 'title': 'Title',
  15430. 'normalText': 'Text',
  15431. 'underline': 'Underline',
  15432. 'alignment': 'Alignment',
  15433. 'alignCenter': 'Align Center',
  15434. 'alignLeft': 'Align Left',
  15435. 'alignRight': 'Align Right',
  15436. 'selectLanguage': 'Select Language',
  15437. 'fontScale': 'Font Size',
  15438. 'fontScaleXLarge': 'X Large Size',
  15439. 'fontScaleLarge': 'Large Size',
  15440. 'fontScaleNormal': 'Normal Size',
  15441. 'fontScaleSmall': 'Small Size',
  15442. 'fontScaleXSmall': 'X Small Size'
  15443. }
  15444. };
  15445. Button = (function(superClass) {
  15446. extend(Button, superClass);
  15447. Button.prototype._tpl = {
  15448. item: '<li><a tabindex="-1" unselectable="on" class="toolbar-item" href="javascript:;"><span></span></a></li>',
  15449. menuWrapper: '<div class="toolbar-menu"></div>',
  15450. menuItem: '<li><a tabindex="-1" unselectable="on" class="menu-item" href="javascript:;"><span></span></a></li>',
  15451. separator: '<li><span class="separator"></span></li>'
  15452. };
  15453. Button.prototype.name = '';
  15454. Button.prototype.icon = '';
  15455. Button.prototype.title = '';
  15456. Button.prototype.text = '';
  15457. Button.prototype.htmlTag = '';
  15458. Button.prototype.disableTag = '';
  15459. Button.prototype.menu = false;
  15460. Button.prototype.active = false;
  15461. Button.prototype.disabled = false;
  15462. Button.prototype.needFocus = true;
  15463. Button.prototype.shortcut = null;
  15464. function Button(opts) {
  15465. this.editor = opts.editor;
  15466. this.title = this._t(this.name);
  15467. Button.__super__.constructor.call(this, opts);
  15468. }
  15469. Button.prototype._init = function() {
  15470. var k, len, ref, tag;
  15471. this.render();
  15472. this.el.on('mousedown', (function(_this) {
  15473. return function(e) {
  15474. var exceed, noFocus, param;
  15475. e.preventDefault();
  15476. noFocus = _this.needFocus && !_this.editor.inputManager.focused;
  15477. if (_this.el.hasClass('disabled') || noFocus) {
  15478. return false;
  15479. }
  15480. if (_this.menu) {
  15481. _this.wrapper.toggleClass('menu-on').siblings('li').removeClass('menu-on');
  15482. if (_this.wrapper.is('.menu-on')) {
  15483. exceed = _this.menuWrapper.offset().left + _this.menuWrapper.outerWidth() + 5 - _this.editor.wrapper.offset().left - _this.editor.wrapper.outerWidth();
  15484. if (exceed > 0) {
  15485. _this.menuWrapper.css({
  15486. 'left': 'auto',
  15487. 'right': 0
  15488. });
  15489. }
  15490. _this.trigger('menuexpand');
  15491. }
  15492. return false;
  15493. }
  15494. param = _this.el.data('param');
  15495. _this.command(param);
  15496. return false;
  15497. };
  15498. })(this));
  15499. this.wrapper.on('click', 'a.menu-item', (function(_this) {
  15500. return function(e) {
  15501. var btn, noFocus, param;
  15502. e.preventDefault();
  15503. btn = $(e.currentTarget);
  15504. _this.wrapper.removeClass('menu-on');
  15505. noFocus = _this.needFocus && !_this.editor.inputManager.focused;
  15506. if (btn.hasClass('disabled') || noFocus) {
  15507. return false;
  15508. }
  15509. _this.editor.toolbar.wrapper.removeClass('menu-on');
  15510. param = btn.data('param');
  15511. _this.command(param);
  15512. return false;
  15513. };
  15514. })(this));
  15515. this.wrapper.on('mousedown', 'a.menu-item', function(e) {
  15516. return false;
  15517. });
  15518. this.editor.on('blur', (function(_this) {
  15519. return function() {
  15520. var editorActive;
  15521. editorActive = _this.editor.body.is(':visible') && _this.editor.body.is('[contenteditable]');
  15522. if (!(editorActive && !_this.editor.clipboard.pasting)) {
  15523. return;
  15524. }
  15525. _this.setActive(false);
  15526. return _this.setDisabled(false);
  15527. };
  15528. })(this));
  15529. if (this.shortcut != null) {
  15530. this.editor.hotkeys.add(this.shortcut, (function(_this) {
  15531. return function(e) {
  15532. _this.el.mousedown();
  15533. return false;
  15534. };
  15535. })(this));
  15536. }
  15537. ref = this.htmlTag.split(',');
  15538. for (k = 0, len = ref.length; k < len; k++) {
  15539. tag = ref[k];
  15540. tag = $.trim(tag);
  15541. if (tag && $.inArray(tag, this.editor.formatter._allowedTags) < 0) {
  15542. this.editor.formatter._allowedTags.push(tag);
  15543. }
  15544. }
  15545. return this.editor.on('selectionchanged', (function(_this) {
  15546. return function(e) {
  15547. if (_this.editor.inputManager.focused) {
  15548. return _this._status();
  15549. }
  15550. };
  15551. })(this));
  15552. };
  15553. Button.prototype.iconClassOf = function(icon) {
  15554. if (icon) {
  15555. return "simditor-icon simditor-icon-" + icon;
  15556. } else {
  15557. return '';
  15558. }
  15559. };
  15560. Button.prototype.setIcon = function(icon) {
  15561. return this.el.find('span').removeClass().addClass(this.iconClassOf(icon)).text(this.text);
  15562. };
  15563. Button.prototype.render = function() {
  15564. this.wrapper = $(this._tpl.item).appendTo(this.editor.toolbar.list);
  15565. this.el = this.wrapper.find('a.toolbar-item');
  15566. this.el.attr('title', this.title).addClass("toolbar-item-" + this.name).data('button', this);
  15567. this.setIcon(this.icon);
  15568. if (!this.menu) {
  15569. return;
  15570. }
  15571. this.menuWrapper = $(this._tpl.menuWrapper).appendTo(this.wrapper);
  15572. this.menuWrapper.addClass("toolbar-menu-" + this.name);
  15573. return this.renderMenu();
  15574. };
  15575. Button.prototype.renderMenu = function() {
  15576. var $menuBtnEl, $menuItemEl, k, len, menuItem, ref, ref1, results;
  15577. if (!$.isArray(this.menu)) {
  15578. return;
  15579. }
  15580. this.menuEl = $('<ul/>').appendTo(this.menuWrapper);
  15581. ref = this.menu;
  15582. results = [];
  15583. for (k = 0, len = ref.length; k < len; k++) {
  15584. menuItem = ref[k];
  15585. if (menuItem === '|') {
  15586. $(this._tpl.separator).appendTo(this.menuEl);
  15587. continue;
  15588. }
  15589. $menuItemEl = $(this._tpl.menuItem).appendTo(this.menuEl);
  15590. $menuBtnEl = $menuItemEl.find('a.menu-item').attr({
  15591. 'title': (ref1 = menuItem.title) != null ? ref1 : menuItem.text,
  15592. 'data-param': menuItem.param
  15593. }).addClass('menu-item-' + menuItem.name);
  15594. if (menuItem.icon) {
  15595. results.push($menuBtnEl.find('span').addClass(this.iconClassOf(menuItem.icon)));
  15596. } else {
  15597. results.push($menuBtnEl.find('span').text(menuItem.text));
  15598. }
  15599. }
  15600. return results;
  15601. };
  15602. Button.prototype.setActive = function(active) {
  15603. if (active === this.active) {
  15604. return;
  15605. }
  15606. this.active = active;
  15607. return this.el.toggleClass('active', this.active);
  15608. };
  15609. Button.prototype.setDisabled = function(disabled) {
  15610. if (disabled === this.disabled) {
  15611. return;
  15612. }
  15613. this.disabled = disabled;
  15614. return this.el.toggleClass('disabled', this.disabled);
  15615. };
  15616. Button.prototype._disableStatus = function() {
  15617. var disabled, endNodes, startNodes;
  15618. startNodes = this.editor.selection.startNodes();
  15619. endNodes = this.editor.selection.endNodes();
  15620. disabled = startNodes.filter(this.disableTag).length > 0 || endNodes.filter(this.disableTag).length > 0;
  15621. this.setDisabled(disabled);
  15622. if (this.disabled) {
  15623. this.setActive(false);
  15624. }
  15625. return this.disabled;
  15626. };
  15627. Button.prototype._activeStatus = function() {
  15628. var active, endNode, endNodes, startNode, startNodes;
  15629. startNodes = this.editor.selection.startNodes();
  15630. endNodes = this.editor.selection.endNodes();
  15631. startNode = startNodes.filter(this.htmlTag);
  15632. endNode = endNodes.filter(this.htmlTag);
  15633. active = startNode.length > 0 && endNode.length > 0 && startNode.is(endNode);
  15634. this.node = active ? startNode : null;
  15635. this.setActive(active);
  15636. return this.active;
  15637. };
  15638. Button.prototype._status = function() {
  15639. this._disableStatus();
  15640. if (this.disabled) {
  15641. return;
  15642. }
  15643. return this._activeStatus();
  15644. };
  15645. Button.prototype.command = function(param) {};
  15646. Button.prototype._t = function() {
  15647. var args, ref, result;
  15648. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  15649. result = Button.__super__._t.apply(this, args);
  15650. if (!result) {
  15651. result = (ref = this.editor)._t.apply(ref, args);
  15652. }
  15653. return result;
  15654. };
  15655. return Button;
  15656. })(SimpleModule);
  15657. Simditor.Button = Button;
  15658. Popover = (function(superClass) {
  15659. extend(Popover, superClass);
  15660. Popover.prototype.offset = {
  15661. top: 4,
  15662. left: 0
  15663. };
  15664. Popover.prototype.target = null;
  15665. Popover.prototype.active = false;
  15666. function Popover(opts) {
  15667. this.button = opts.button;
  15668. this.editor = opts.button.editor;
  15669. Popover.__super__.constructor.call(this, opts);
  15670. }
  15671. Popover.prototype._init = function() {
  15672. this.el = $('<div class="simditor-popover"></div>').appendTo(this.editor.el).data('popover', this);
  15673. this.render();
  15674. this.el.on('mouseenter', (function(_this) {
  15675. return function(e) {
  15676. return _this.el.addClass('hover');
  15677. };
  15678. })(this));
  15679. return this.el.on('mouseleave', (function(_this) {
  15680. return function(e) {
  15681. return _this.el.removeClass('hover');
  15682. };
  15683. })(this));
  15684. };
  15685. Popover.prototype.render = function() {};
  15686. Popover.prototype._initLabelWidth = function() {
  15687. var $fields;
  15688. $fields = this.el.find('.settings-field');
  15689. if (!($fields.length > 0)) {
  15690. return;
  15691. }
  15692. this._labelWidth = 0;
  15693. $fields.each((function(_this) {
  15694. return function(i, field) {
  15695. var $field, $label;
  15696. $field = $(field);
  15697. $label = $field.find('label');
  15698. if (!($label.length > 0)) {
  15699. return;
  15700. }
  15701. return _this._labelWidth = Math.max(_this._labelWidth, $label.width());
  15702. };
  15703. })(this));
  15704. return $fields.find('label').width(this._labelWidth);
  15705. };
  15706. Popover.prototype.show = function($target, position) {
  15707. if (position == null) {
  15708. position = 'bottom';
  15709. }
  15710. if ($target == null) {
  15711. return;
  15712. }
  15713. this.el.siblings('.simditor-popover').each(function(i, popover) {
  15714. popover = $(popover).data('popover');
  15715. if (popover.active) {
  15716. return popover.hide();
  15717. }
  15718. });
  15719. if (this.active && this.target) {
  15720. this.target.removeClass('selected');
  15721. }
  15722. this.target = $target.addClass('selected');
  15723. if (this.active) {
  15724. this.refresh(position);
  15725. return this.trigger('popovershow');
  15726. } else {
  15727. this.active = true;
  15728. this.el.css({
  15729. left: -9999
  15730. }).show();
  15731. if (!this._labelWidth) {
  15732. this._initLabelWidth();
  15733. }
  15734. this.editor.util.reflow();
  15735. this.refresh(position);
  15736. return this.trigger('popovershow');
  15737. }
  15738. };
  15739. Popover.prototype.hide = function() {
  15740. if (!this.active) {
  15741. return;
  15742. }
  15743. if (this.target) {
  15744. this.target.removeClass('selected');
  15745. }
  15746. this.target = null;
  15747. this.active = false;
  15748. this.el.hide();
  15749. return this.trigger('popoverhide');
  15750. };
  15751. Popover.prototype.refresh = function(position) {
  15752. var editorOffset, left, maxLeft, targetH, targetOffset, top;
  15753. if (position == null) {
  15754. position = 'bottom';
  15755. }
  15756. if (!this.active) {
  15757. return;
  15758. }
  15759. editorOffset = this.editor.el.offset();
  15760. targetOffset = this.target.offset();
  15761. targetH = this.target.outerHeight();
  15762. if (position === 'bottom') {
  15763. top = targetOffset.top - editorOffset.top + targetH;
  15764. } else if (position === 'top') {
  15765. top = targetOffset.top - editorOffset.top - this.el.height();
  15766. }
  15767. maxLeft = this.editor.wrapper.width() - this.el.outerWidth() - 10;
  15768. left = Math.min(targetOffset.left - editorOffset.left, maxLeft);
  15769. return this.el.css({
  15770. top: top + this.offset.top,
  15771. left: left + this.offset.left
  15772. });
  15773. };
  15774. Popover.prototype.destroy = function() {
  15775. this.target = null;
  15776. this.active = false;
  15777. this.editor.off('.linkpopover');
  15778. return this.el.remove();
  15779. };
  15780. Popover.prototype._t = function() {
  15781. var args, ref, result;
  15782. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  15783. result = Popover.__super__._t.apply(this, args);
  15784. if (!result) {
  15785. result = (ref = this.button)._t.apply(ref, args);
  15786. }
  15787. return result;
  15788. };
  15789. return Popover;
  15790. })(SimpleModule);
  15791. Simditor.Popover = Popover;
  15792. TitleButton = (function(superClass) {
  15793. extend(TitleButton, superClass);
  15794. function TitleButton() {
  15795. return TitleButton.__super__.constructor.apply(this, arguments);
  15796. }
  15797. TitleButton.prototype.name = 'title';
  15798. TitleButton.prototype.htmlTag = 'h1, h2, h3, h4, h5';
  15799. TitleButton.prototype.disableTag = 'pre, table';
  15800. TitleButton.prototype._init = function() {
  15801. this.menu = [
  15802. {
  15803. name: 'normal',
  15804. text: this._t('normalText'),
  15805. param: 'p'
  15806. }, '|', {
  15807. name: 'h1',
  15808. text: this._t('title') + ' 1',
  15809. param: 'h1'
  15810. }, {
  15811. name: 'h2',
  15812. text: this._t('title') + ' 2',
  15813. param: 'h2'
  15814. }, {
  15815. name: 'h3',
  15816. text: this._t('title') + ' 3',
  15817. param: 'h3'
  15818. }, {
  15819. name: 'h4',
  15820. text: this._t('title') + ' 4',
  15821. param: 'h4'
  15822. }, {
  15823. name: 'h5',
  15824. text: this._t('title') + ' 5',
  15825. param: 'h5'
  15826. }
  15827. ];
  15828. return TitleButton.__super__._init.call(this);
  15829. };
  15830. TitleButton.prototype.setActive = function(active, param) {
  15831. TitleButton.__super__.setActive.call(this, active);
  15832. if (active) {
  15833. param || (param = this.node[0].tagName.toLowerCase());
  15834. }
  15835. this.el.removeClass('active-p active-h1 active-h2 active-h3 active-h4 active-h5');
  15836. if (active) {
  15837. return this.el.addClass('active active-' + param);
  15838. }
  15839. };
  15840. TitleButton.prototype.command = function(param) {
  15841. var $rootNodes;
  15842. $rootNodes = this.editor.selection.rootNodes();
  15843. this.editor.selection.save();
  15844. $rootNodes.each((function(_this) {
  15845. return function(i, node) {
  15846. var $node;
  15847. $node = $(node);
  15848. if ($node.is('blockquote') || $node.is(param) || $node.is(_this.disableTag) || _this.editor.util.isDecoratedNode($node)) {
  15849. return;
  15850. }
  15851. return $('<' + param + '/>').append($node.contents()).replaceAll($node);
  15852. };
  15853. })(this));
  15854. this.editor.selection.restore();
  15855. return this.editor.trigger('valuechanged');
  15856. };
  15857. return TitleButton;
  15858. })(Button);
  15859. Simditor.Toolbar.addButton(TitleButton);
  15860. FontScaleButton = (function(superClass) {
  15861. extend(FontScaleButton, superClass);
  15862. function FontScaleButton() {
  15863. return FontScaleButton.__super__.constructor.apply(this, arguments);
  15864. }
  15865. FontScaleButton.prototype.name = 'fontScale';
  15866. FontScaleButton.prototype.icon = 'font';
  15867. FontScaleButton.prototype.disableTag = 'pre';
  15868. FontScaleButton.prototype.htmlTag = 'span';
  15869. FontScaleButton.prototype.sizeMap = {
  15870. 'x-large': '1.5em',
  15871. 'large': '1.25em',
  15872. 'small': '.75em',
  15873. 'x-small': '.5em'
  15874. };
  15875. FontScaleButton.prototype._init = function() {
  15876. this.menu = [
  15877. {
  15878. name: '150%',
  15879. text: this._t('fontScaleXLarge'),
  15880. param: '5'
  15881. }, {
  15882. name: '125%',
  15883. text: this._t('fontScaleLarge'),
  15884. param: '4'
  15885. }, {
  15886. name: '100%',
  15887. text: this._t('fontScaleNormal'),
  15888. param: '3'
  15889. }, {
  15890. name: '75%',
  15891. text: this._t('fontScaleSmall'),
  15892. param: '2'
  15893. }, {
  15894. name: '50%',
  15895. text: this._t('fontScaleXSmall'),
  15896. param: '1'
  15897. }
  15898. ];
  15899. return FontScaleButton.__super__._init.call(this);
  15900. };
  15901. FontScaleButton.prototype._activeStatus = function() {
  15902. var active, endNode, endNodes, range, startNode, startNodes;
  15903. range = this.editor.selection.range();
  15904. startNodes = this.editor.selection.startNodes();
  15905. endNodes = this.editor.selection.endNodes();
  15906. startNode = startNodes.filter('span[style*="font-size"]');
  15907. endNode = endNodes.filter('span[style*="font-size"]');
  15908. active = startNodes.length > 0 && endNodes.length > 0 && startNode.is(endNode);
  15909. this.setActive(active);
  15910. return this.active;
  15911. };
  15912. FontScaleButton.prototype.command = function(param) {
  15913. var $scales, containerNode, range;
  15914. range = this.editor.selection.range();
  15915. if (range.collapsed) {
  15916. return;
  15917. }
  15918. document.execCommand('styleWithCSS', false, true);
  15919. document.execCommand('fontSize', false, param);
  15920. document.execCommand('styleWithCSS', false, false);
  15921. this.editor.selection.reset();
  15922. this.editor.selection.range();
  15923. containerNode = this.editor.selection.containerNode();
  15924. if (containerNode[0].nodeType === Node.TEXT_NODE) {
  15925. $scales = containerNode.closest('span[style*="font-size"]');
  15926. } else {
  15927. $scales = containerNode.find('span[style*="font-size"]');
  15928. }
  15929. $scales.each((function(_this) {
  15930. return function(i, n) {
  15931. var $span, size;
  15932. $span = $(n);
  15933. size = n.style.fontSize;
  15934. if (/large|x-large|small|x-small/.test(size)) {
  15935. return $span.css('fontSize', _this.sizeMap[size]);
  15936. } else if (size === 'medium') {
  15937. return $span.replaceWith($span.contents());
  15938. }
  15939. };
  15940. })(this));
  15941. return this.editor.trigger('valuechanged');
  15942. };
  15943. return FontScaleButton;
  15944. })(Button);
  15945. Simditor.Toolbar.addButton(FontScaleButton);
  15946. BoldButton = (function(superClass) {
  15947. extend(BoldButton, superClass);
  15948. function BoldButton() {
  15949. return BoldButton.__super__.constructor.apply(this, arguments);
  15950. }
  15951. BoldButton.prototype.name = 'bold';
  15952. BoldButton.prototype.icon = 'bold';
  15953. BoldButton.prototype.htmlTag = 'b, strong';
  15954. BoldButton.prototype.disableTag = 'pre';
  15955. BoldButton.prototype.shortcut = 'cmd+b';
  15956. BoldButton.prototype._init = function() {
  15957. if (this.editor.util.os.mac) {
  15958. this.title = this.title + ' ( Cmd + b )';
  15959. } else {
  15960. this.title = this.title + ' ( Ctrl + b )';
  15961. this.shortcut = 'ctrl+b';
  15962. }
  15963. return BoldButton.__super__._init.call(this);
  15964. };
  15965. BoldButton.prototype._activeStatus = function() {
  15966. var active;
  15967. active = document.queryCommandState('bold') === true;
  15968. this.setActive(active);
  15969. return this.active;
  15970. };
  15971. BoldButton.prototype.command = function() {
  15972. document.execCommand('bold');
  15973. if (!this.editor.util.support.oninput) {
  15974. this.editor.trigger('valuechanged');
  15975. }
  15976. return $(document).trigger('selectionchange');
  15977. };
  15978. return BoldButton;
  15979. })(Button);
  15980. Simditor.Toolbar.addButton(BoldButton);
  15981. ItalicButton = (function(superClass) {
  15982. extend(ItalicButton, superClass);
  15983. function ItalicButton() {
  15984. return ItalicButton.__super__.constructor.apply(this, arguments);
  15985. }
  15986. ItalicButton.prototype.name = 'italic';
  15987. ItalicButton.prototype.icon = 'italic';
  15988. ItalicButton.prototype.htmlTag = 'i';
  15989. ItalicButton.prototype.disableTag = 'pre';
  15990. ItalicButton.prototype.shortcut = 'cmd+i';
  15991. ItalicButton.prototype._init = function() {
  15992. if (this.editor.util.os.mac) {
  15993. this.title = this.title + " ( Cmd + i )";
  15994. } else {
  15995. this.title = this.title + " ( Ctrl + i )";
  15996. this.shortcut = 'ctrl+i';
  15997. }
  15998. return ItalicButton.__super__._init.call(this);
  15999. };
  16000. ItalicButton.prototype._activeStatus = function() {
  16001. var active;
  16002. active = document.queryCommandState('italic') === true;
  16003. this.setActive(active);
  16004. return this.active;
  16005. };
  16006. ItalicButton.prototype.command = function() {
  16007. document.execCommand('italic');
  16008. if (!this.editor.util.support.oninput) {
  16009. this.editor.trigger('valuechanged');
  16010. }
  16011. return $(document).trigger('selectionchange');
  16012. };
  16013. return ItalicButton;
  16014. })(Button);
  16015. Simditor.Toolbar.addButton(ItalicButton);
  16016. UnderlineButton = (function(superClass) {
  16017. extend(UnderlineButton, superClass);
  16018. function UnderlineButton() {
  16019. return UnderlineButton.__super__.constructor.apply(this, arguments);
  16020. }
  16021. UnderlineButton.prototype.name = 'underline';
  16022. UnderlineButton.prototype.icon = 'underline';
  16023. UnderlineButton.prototype.htmlTag = 'u';
  16024. UnderlineButton.prototype.disableTag = 'pre';
  16025. UnderlineButton.prototype.shortcut = 'cmd+u';
  16026. UnderlineButton.prototype.render = function() {
  16027. if (this.editor.util.os.mac) {
  16028. this.title = this.title + ' ( Cmd + u )';
  16029. } else {
  16030. this.title = this.title + ' ( Ctrl + u )';
  16031. this.shortcut = 'ctrl+u';
  16032. }
  16033. return UnderlineButton.__super__.render.call(this);
  16034. };
  16035. UnderlineButton.prototype._activeStatus = function() {
  16036. var active;
  16037. active = document.queryCommandState('underline') === true;
  16038. this.setActive(active);
  16039. return this.active;
  16040. };
  16041. UnderlineButton.prototype.command = function() {
  16042. document.execCommand('underline');
  16043. if (!this.editor.util.support.oninput) {
  16044. this.editor.trigger('valuechanged');
  16045. }
  16046. return $(document).trigger('selectionchange');
  16047. };
  16048. return UnderlineButton;
  16049. })(Button);
  16050. Simditor.Toolbar.addButton(UnderlineButton);
  16051. ColorButton = (function(superClass) {
  16052. extend(ColorButton, superClass);
  16053. function ColorButton() {
  16054. return ColorButton.__super__.constructor.apply(this, arguments);
  16055. }
  16056. ColorButton.prototype.name = 'color';
  16057. ColorButton.prototype.icon = 'tint';
  16058. ColorButton.prototype.disableTag = 'pre';
  16059. ColorButton.prototype.menu = true;
  16060. ColorButton.prototype.render = function() {
  16061. var args;
  16062. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  16063. return ColorButton.__super__.render.apply(this, args);
  16064. };
  16065. ColorButton.prototype.renderMenu = function() {
  16066. $('<ul class="color-list">\n <li><a href="javascript:;" class="font-color font-color-1"></a></li>\n <li><a href="javascript:;" class="font-color font-color-2"></a></li>\n <li><a href="javascript:;" class="font-color font-color-3"></a></li>\n <li><a href="javascript:;" class="font-color font-color-4"></a></li>\n <li><a href="javascript:;" class="font-color font-color-5"></a></li>\n <li><a href="javascript:;" class="font-color font-color-6"></a></li>\n <li><a href="javascript:;" class="font-color font-color-7"></a></li>\n <li><a href="javascript:;" class="font-color font-color-default"></a></li>\n</ul>').appendTo(this.menuWrapper);
  16067. this.menuWrapper.on('mousedown', '.color-list', function(e) {
  16068. return false;
  16069. });
  16070. return this.menuWrapper.on('click', '.font-color', (function(_this) {
  16071. return function(e) {
  16072. var $link, $p, hex, range, rgb, textNode;
  16073. _this.wrapper.removeClass('menu-on');
  16074. $link = $(e.currentTarget);
  16075. if ($link.hasClass('font-color-default')) {
  16076. $p = _this.editor.body.find('p, li');
  16077. if (!($p.length > 0)) {
  16078. return;
  16079. }
  16080. rgb = window.getComputedStyle($p[0], null).getPropertyValue('color');
  16081. hex = _this._convertRgbToHex(rgb);
  16082. } else {
  16083. rgb = window.getComputedStyle($link[0], null).getPropertyValue('background-color');
  16084. hex = _this._convertRgbToHex(rgb);
  16085. }
  16086. if (!hex) {
  16087. return;
  16088. }
  16089. range = _this.editor.selection.range();
  16090. if (!$link.hasClass('font-color-default') && range.collapsed) {
  16091. textNode = document.createTextNode(_this._t('coloredText'));
  16092. range.insertNode(textNode);
  16093. range.selectNodeContents(textNode);
  16094. _this.editor.selection.range(range);
  16095. }
  16096. document.execCommand('styleWithCSS', false, true);
  16097. document.execCommand('foreColor', false, hex);
  16098. document.execCommand('styleWithCSS', false, false);
  16099. if (!_this.editor.util.support.oninput) {
  16100. return _this.editor.trigger('valuechanged');
  16101. }
  16102. };
  16103. })(this));
  16104. };
  16105. ColorButton.prototype._convertRgbToHex = function(rgb) {
  16106. var match, re, rgbToHex;
  16107. re = /rgb\((\d+),\s?(\d+),\s?(\d+)\)/g;
  16108. match = re.exec(rgb);
  16109. if (!match) {
  16110. return '';
  16111. }
  16112. rgbToHex = function(r, g, b) {
  16113. var componentToHex;
  16114. componentToHex = function(c) {
  16115. var hex;
  16116. hex = c.toString(16);
  16117. if (hex.length === 1) {
  16118. return '0' + hex;
  16119. } else {
  16120. return hex;
  16121. }
  16122. };
  16123. return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
  16124. };
  16125. return rgbToHex(match[1] * 1, match[2] * 1, match[3] * 1);
  16126. };
  16127. return ColorButton;
  16128. })(Button);
  16129. Simditor.Toolbar.addButton(ColorButton);
  16130. ListButton = (function(superClass) {
  16131. extend(ListButton, superClass);
  16132. function ListButton() {
  16133. return ListButton.__super__.constructor.apply(this, arguments);
  16134. }
  16135. ListButton.prototype.type = '';
  16136. ListButton.prototype.disableTag = 'pre, table';
  16137. ListButton.prototype.command = function(param) {
  16138. var $list, $rootNodes, anotherType;
  16139. $rootNodes = this.editor.selection.blockNodes();
  16140. anotherType = this.type === 'ul' ? 'ol' : 'ul';
  16141. this.editor.selection.save();
  16142. $list = null;
  16143. $rootNodes.each((function(_this) {
  16144. return function(i, node) {
  16145. var $node;
  16146. $node = $(node);
  16147. if ($node.is('blockquote, li') || $node.is(_this.disableTag) || _this.editor.util.isDecoratedNode($node) || !$.contains(document, node)) {
  16148. return;
  16149. }
  16150. if ($node.is(_this.type)) {
  16151. $node.children('li').each(function(i, li) {
  16152. var $childList, $li;
  16153. $li = $(li);
  16154. $childList = $li.children('ul, ol').insertAfter($node);
  16155. return $('<p/>').append($(li).html() || _this.editor.util.phBr).insertBefore($node);
  16156. });
  16157. return $node.remove();
  16158. } else if ($node.is(anotherType)) {
  16159. return $('<' + _this.type + '/>').append($node.contents()).replaceAll($node);
  16160. } else if ($list && $node.prev().is($list)) {
  16161. $('<li/>').append($node.html() || _this.editor.util.phBr).appendTo($list);
  16162. return $node.remove();
  16163. } else {
  16164. $list = $("<" + _this.type + "><li></li></" + _this.type + ">");
  16165. $list.find('li').append($node.html() || _this.editor.util.phBr);
  16166. return $list.replaceAll($node);
  16167. }
  16168. };
  16169. })(this));
  16170. this.editor.selection.restore();
  16171. return this.editor.trigger('valuechanged');
  16172. };
  16173. return ListButton;
  16174. })(Button);
  16175. OrderListButton = (function(superClass) {
  16176. extend(OrderListButton, superClass);
  16177. function OrderListButton() {
  16178. return OrderListButton.__super__.constructor.apply(this, arguments);
  16179. }
  16180. OrderListButton.prototype.type = 'ol';
  16181. OrderListButton.prototype.name = 'ol';
  16182. OrderListButton.prototype.icon = 'list-ol';
  16183. OrderListButton.prototype.htmlTag = 'ol';
  16184. OrderListButton.prototype.shortcut = 'cmd+/';
  16185. OrderListButton.prototype._init = function() {
  16186. if (this.editor.util.os.mac) {
  16187. this.title = this.title + ' ( Cmd + / )';
  16188. } else {
  16189. this.title = this.title + ' ( ctrl + / )';
  16190. this.shortcut = 'ctrl+/';
  16191. }
  16192. return OrderListButton.__super__._init.call(this);
  16193. };
  16194. return OrderListButton;
  16195. })(ListButton);
  16196. UnorderListButton = (function(superClass) {
  16197. extend(UnorderListButton, superClass);
  16198. function UnorderListButton() {
  16199. return UnorderListButton.__super__.constructor.apply(this, arguments);
  16200. }
  16201. UnorderListButton.prototype.type = 'ul';
  16202. UnorderListButton.prototype.name = 'ul';
  16203. UnorderListButton.prototype.icon = 'list-ul';
  16204. UnorderListButton.prototype.htmlTag = 'ul';
  16205. UnorderListButton.prototype.shortcut = 'cmd+.';
  16206. UnorderListButton.prototype._init = function() {
  16207. if (this.editor.util.os.mac) {
  16208. this.title = this.title + ' ( Cmd + . )';
  16209. } else {
  16210. this.title = this.title + ' ( Ctrl + . )';
  16211. this.shortcut = 'ctrl+.';
  16212. }
  16213. return UnorderListButton.__super__._init.call(this);
  16214. };
  16215. return UnorderListButton;
  16216. })(ListButton);
  16217. Simditor.Toolbar.addButton(OrderListButton);
  16218. Simditor.Toolbar.addButton(UnorderListButton);
  16219. BlockquoteButton = (function(superClass) {
  16220. extend(BlockquoteButton, superClass);
  16221. function BlockquoteButton() {
  16222. return BlockquoteButton.__super__.constructor.apply(this, arguments);
  16223. }
  16224. BlockquoteButton.prototype.name = 'blockquote';
  16225. BlockquoteButton.prototype.icon = 'quote-left';
  16226. BlockquoteButton.prototype.htmlTag = 'blockquote';
  16227. BlockquoteButton.prototype.disableTag = 'pre, table';
  16228. BlockquoteButton.prototype.command = function() {
  16229. var $rootNodes, clearCache, nodeCache;
  16230. $rootNodes = this.editor.selection.rootNodes();
  16231. $rootNodes = $rootNodes.filter(function(i, node) {
  16232. return !$(node).parent().is('blockquote');
  16233. });
  16234. this.editor.selection.save();
  16235. nodeCache = [];
  16236. clearCache = (function(_this) {
  16237. return function() {
  16238. if (nodeCache.length > 0) {
  16239. $("<" + _this.htmlTag + "/>").insertBefore(nodeCache[0]).append(nodeCache);
  16240. return nodeCache.length = 0;
  16241. }
  16242. };
  16243. })(this);
  16244. $rootNodes.each((function(_this) {
  16245. return function(i, node) {
  16246. var $node;
  16247. $node = $(node);
  16248. if (!$node.parent().is(_this.editor.body)) {
  16249. return;
  16250. }
  16251. if ($node.is(_this.htmlTag)) {
  16252. clearCache();
  16253. return $node.children().unwrap();
  16254. } else if ($node.is(_this.disableTag) || _this.editor.util.isDecoratedNode($node)) {
  16255. return clearCache();
  16256. } else {
  16257. return nodeCache.push(node);
  16258. }
  16259. };
  16260. })(this));
  16261. clearCache();
  16262. this.editor.selection.restore();
  16263. return this.editor.trigger('valuechanged');
  16264. };
  16265. return BlockquoteButton;
  16266. })(Button);
  16267. Simditor.Toolbar.addButton(BlockquoteButton);
  16268. CodeButton = (function(superClass) {
  16269. extend(CodeButton, superClass);
  16270. function CodeButton() {
  16271. return CodeButton.__super__.constructor.apply(this, arguments);
  16272. }
  16273. CodeButton.prototype.name = 'code';
  16274. CodeButton.prototype.icon = 'code';
  16275. CodeButton.prototype.htmlTag = 'pre';
  16276. CodeButton.prototype.disableTag = 'ul, ol, table';
  16277. CodeButton.prototype._init = function() {
  16278. CodeButton.__super__._init.call(this);
  16279. this.editor.on('decorate', (function(_this) {
  16280. return function(e, $el) {
  16281. return $el.find('pre').each(function(i, pre) {
  16282. return _this.decorate($(pre));
  16283. });
  16284. };
  16285. })(this));
  16286. return this.editor.on('undecorate', (function(_this) {
  16287. return function(e, $el) {
  16288. return $el.find('pre').each(function(i, pre) {
  16289. return _this.undecorate($(pre));
  16290. });
  16291. };
  16292. })(this));
  16293. };
  16294. CodeButton.prototype.render = function() {
  16295. var args;
  16296. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  16297. CodeButton.__super__.render.apply(this, args);
  16298. return this.popover = new CodePopover({
  16299. button: this
  16300. });
  16301. };
  16302. CodeButton.prototype._checkMode = function() {
  16303. var $blockNodes, range;
  16304. range = this.editor.selection.range();
  16305. if (($blockNodes = $(range.cloneContents()).find(this.editor.util.blockNodes.join(','))) > 0 || (range.collapsed && this.editor.selection.startNodes().filter('code').length === 0)) {
  16306. this.inlineMode = false;
  16307. return this.htmlTag = 'pre';
  16308. } else {
  16309. this.inlineMode = true;
  16310. return this.htmlTag = 'code';
  16311. }
  16312. };
  16313. CodeButton.prototype._status = function() {
  16314. this._checkMode();
  16315. CodeButton.__super__._status.call(this);
  16316. if (this.inlineMode) {
  16317. return;
  16318. }
  16319. if (this.active) {
  16320. return this.popover.show(this.node);
  16321. } else {
  16322. return this.popover.hide();
  16323. }
  16324. };
  16325. CodeButton.prototype.decorate = function($pre) {
  16326. var $code, lang, ref, ref1;
  16327. $code = $pre.find('> code');
  16328. if ($code.length > 0) {
  16329. lang = (ref = $code.attr('class')) != null ? (ref1 = ref.match(/lang-(\S+)/)) != null ? ref1[1] : void 0 : void 0;
  16330. $code.contents().unwrap();
  16331. if (lang) {
  16332. return $pre.attr('data-lang', lang);
  16333. }
  16334. }
  16335. };
  16336. CodeButton.prototype.undecorate = function($pre) {
  16337. var $code, lang;
  16338. lang = $pre.attr('data-lang');
  16339. $code = $('<code/>');
  16340. if (lang && lang !== -1) {
  16341. $code.addClass('lang-' + lang);
  16342. }
  16343. return $pre.wrapInner($code).removeAttr('data-lang');
  16344. };
  16345. CodeButton.prototype.command = function() {
  16346. if (this.inlineMode) {
  16347. return this._inlineCommand();
  16348. } else {
  16349. return this._blockCommand();
  16350. }
  16351. };
  16352. CodeButton.prototype._blockCommand = function() {
  16353. var $rootNodes, clearCache, nodeCache, resultNodes;
  16354. $rootNodes = this.editor.selection.rootNodes();
  16355. nodeCache = [];
  16356. resultNodes = [];
  16357. clearCache = (function(_this) {
  16358. return function() {
  16359. var $pre;
  16360. if (!(nodeCache.length > 0)) {
  16361. return;
  16362. }
  16363. $pre = $("<" + _this.htmlTag + "/>").insertBefore(nodeCache[0]).text(_this.editor.formatter.clearHtml(nodeCache));
  16364. resultNodes.push($pre[0]);
  16365. return nodeCache.length = 0;
  16366. };
  16367. })(this);
  16368. $rootNodes.each((function(_this) {
  16369. return function(i, node) {
  16370. var $node, $p;
  16371. $node = $(node);
  16372. if ($node.is(_this.htmlTag)) {
  16373. clearCache();
  16374. $p = $('<p/>').append($node.html().replace('\n', '<br/>')).replaceAll($node);
  16375. return resultNodes.push($p[0]);
  16376. } else if ($node.is(_this.disableTag) || _this.editor.util.isDecoratedNode($node) || $node.is('blockquote')) {
  16377. return clearCache();
  16378. } else {
  16379. return nodeCache.push(node);
  16380. }
  16381. };
  16382. })(this));
  16383. clearCache();
  16384. this.editor.selection.setRangeAtEndOf($(resultNodes).last());
  16385. return this.editor.trigger('valuechanged');
  16386. };
  16387. CodeButton.prototype._inlineCommand = function() {
  16388. var $code, $contents, range;
  16389. range = this.editor.selection.range();
  16390. if (this.active) {
  16391. range.selectNodeContents(this.node[0]);
  16392. this.editor.selection.save(range);
  16393. this.node.contents().unwrap();
  16394. this.editor.selection.restore();
  16395. } else {
  16396. $contents = $(range.extractContents());
  16397. $code = $("<" + this.htmlTag + "/>").append($contents.contents());
  16398. range.insertNode($code[0]);
  16399. range.selectNodeContents($code[0]);
  16400. this.editor.selection.range(range);
  16401. }
  16402. return this.editor.trigger('valuechanged');
  16403. };
  16404. return CodeButton;
  16405. })(Button);
  16406. CodePopover = (function(superClass) {
  16407. extend(CodePopover, superClass);
  16408. function CodePopover() {
  16409. return CodePopover.__super__.constructor.apply(this, arguments);
  16410. }
  16411. CodePopover.prototype.render = function() {
  16412. var $option, k, lang, len, ref;
  16413. this._tpl = "<div class=\"code-settings\">\n <div class=\"settings-field\">\n <select class=\"select-lang\">\n <option value=\"-1\">" + (this._t('selectLanguage')) + "</option>\n </select>\n </div>\n</div>";
  16414. this.langs = this.editor.opts.codeLanguages || [
  16415. {
  16416. name: 'Bash',
  16417. value: 'bash'
  16418. }, {
  16419. name: 'C++',
  16420. value: 'c++'
  16421. }, {
  16422. name: 'C#',
  16423. value: 'cs'
  16424. }, {
  16425. name: 'CSS',
  16426. value: 'css'
  16427. }, {
  16428. name: 'Erlang',
  16429. value: 'erlang'
  16430. }, {
  16431. name: 'Less',
  16432. value: 'less'
  16433. }, {
  16434. name: 'Sass',
  16435. value: 'sass'
  16436. }, {
  16437. name: 'Diff',
  16438. value: 'diff'
  16439. }, {
  16440. name: 'CoffeeScript',
  16441. value: 'coffeescript'
  16442. }, {
  16443. name: 'HTML,XML',
  16444. value: 'html'
  16445. }, {
  16446. name: 'JSON',
  16447. value: 'json'
  16448. }, {
  16449. name: 'Java',
  16450. value: 'java'
  16451. }, {
  16452. name: 'JavaScript',
  16453. value: 'js'
  16454. }, {
  16455. name: 'Markdown',
  16456. value: 'markdown'
  16457. }, {
  16458. name: 'Objective C',
  16459. value: 'oc'
  16460. }, {
  16461. name: 'PHP',
  16462. value: 'php'
  16463. }, {
  16464. name: 'Perl',
  16465. value: 'parl'
  16466. }, {
  16467. name: 'Python',
  16468. value: 'python'
  16469. }, {
  16470. name: 'Ruby',
  16471. value: 'ruby'
  16472. }, {
  16473. name: 'SQL',
  16474. value: 'sql'
  16475. }
  16476. ];
  16477. this.el.addClass('code-popover').append(this._tpl);
  16478. this.selectEl = this.el.find('.select-lang');
  16479. ref = this.langs;
  16480. for (k = 0, len = ref.length; k < len; k++) {
  16481. lang = ref[k];
  16482. $option = $('<option/>', {
  16483. text: lang.name,
  16484. value: lang.value
  16485. }).appendTo(this.selectEl);
  16486. }
  16487. this.selectEl.on('change', (function(_this) {
  16488. return function(e) {
  16489. var selected;
  16490. _this.lang = _this.selectEl.val();
  16491. selected = _this.target.hasClass('selected');
  16492. _this.target.removeClass().removeAttr('data-lang');
  16493. if (_this.lang !== -1) {
  16494. _this.target.attr('data-lang', _this.lang);
  16495. }
  16496. if (selected) {
  16497. _this.target.addClass('selected');
  16498. }
  16499. return _this.editor.trigger('valuechanged');
  16500. };
  16501. })(this));
  16502. return this.editor.on('valuechanged', (function(_this) {
  16503. return function(e) {
  16504. if (_this.active) {
  16505. return _this.refresh();
  16506. }
  16507. };
  16508. })(this));
  16509. };
  16510. CodePopover.prototype.show = function() {
  16511. var args;
  16512. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  16513. CodePopover.__super__.show.apply(this, args);
  16514. this.lang = this.target.attr('data-lang');
  16515. if (this.lang != null) {
  16516. return this.selectEl.val(this.lang);
  16517. } else {
  16518. return this.selectEl.val(-1);
  16519. }
  16520. };
  16521. return CodePopover;
  16522. })(Popover);
  16523. Simditor.Toolbar.addButton(CodeButton);
  16524. LinkButton = (function(superClass) {
  16525. extend(LinkButton, superClass);
  16526. function LinkButton() {
  16527. return LinkButton.__super__.constructor.apply(this, arguments);
  16528. }
  16529. LinkButton.prototype.name = 'link';
  16530. LinkButton.prototype.icon = 'link';
  16531. LinkButton.prototype.htmlTag = 'a';
  16532. LinkButton.prototype.disableTag = 'pre';
  16533. LinkButton.prototype.render = function() {
  16534. var args;
  16535. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  16536. LinkButton.__super__.render.apply(this, args);
  16537. return this.popover = new LinkPopover({
  16538. button: this
  16539. });
  16540. };
  16541. LinkButton.prototype._status = function() {
  16542. LinkButton.__super__._status.call(this);
  16543. if (this.active && !this.editor.selection.rangeAtEndOf(this.node)) {
  16544. return this.popover.show(this.node);
  16545. } else {
  16546. return this.popover.hide();
  16547. }
  16548. };
  16549. LinkButton.prototype.command = function() {
  16550. var $contents, $link, $newBlock, linkText, range, txtNode;
  16551. range = this.editor.selection.range();
  16552. if (this.active) {
  16553. txtNode = document.createTextNode(this.node.text());
  16554. this.node.replaceWith(txtNode);
  16555. range.selectNode(txtNode);
  16556. } else {
  16557. $contents = $(range.extractContents());
  16558. linkText = this.editor.formatter.clearHtml($contents.contents(), false);
  16559. $link = $('<a/>', {
  16560. href: 'http://www.example.com',
  16561. target: '_blank',
  16562. text: linkText || this._t('linkText')
  16563. });
  16564. if (this.editor.selection.blockNodes().length > 0) {
  16565. range.insertNode($link[0]);
  16566. } else {
  16567. $newBlock = $('<p/>').append($link);
  16568. range.insertNode($newBlock[0]);
  16569. }
  16570. range.selectNodeContents($link[0]);
  16571. this.popover.one('popovershow', (function(_this) {
  16572. return function() {
  16573. if (linkText) {
  16574. _this.popover.urlEl.focus();
  16575. return _this.popover.urlEl[0].select();
  16576. } else {
  16577. _this.popover.textEl.focus();
  16578. return _this.popover.textEl[0].select();
  16579. }
  16580. };
  16581. })(this));
  16582. }
  16583. this.editor.selection.range(range);
  16584. return this.editor.trigger('valuechanged');
  16585. };
  16586. return LinkButton;
  16587. })(Button);
  16588. LinkPopover = (function(superClass) {
  16589. extend(LinkPopover, superClass);
  16590. function LinkPopover() {
  16591. return LinkPopover.__super__.constructor.apply(this, arguments);
  16592. }
  16593. LinkPopover.prototype.render = function() {
  16594. var tpl;
  16595. tpl = "<div class=\"link-settings\">\n <div class=\"settings-field\">\n <label>" + (this._t('linkText')) + "</label>\n <input class=\"link-text\" type=\"text\"/>\n <a class=\"btn-unlink\" href=\"javascript:;\" title=\"" + (this._t('removeLink')) + "\"\n tabindex=\"-1\">\n <span class=\"simditor-icon simditor-icon-unlink\"></span>\n </a>\n </div>\n <div class=\"settings-field\">\n <label>" + (this._t('linkUrl')) + "</label>\n <input class=\"link-url\" type=\"text\"/>\n </div>\n <div class=\"settings-field\">\n <label>" + (this._t('linkTarget')) + "</label>\n <select class=\"link-target\">\n <option value=\"_blank\">" + (this._t('openLinkInNewWindow')) + " (_blank)</option>\n <option value=\"_self\">" + (this._t('openLinkInCurrentWindow')) + " (_self)</option>\n </select>\n </div>\n</div>";
  16596. this.el.addClass('link-popover').append(tpl);
  16597. this.textEl = this.el.find('.link-text');
  16598. this.urlEl = this.el.find('.link-url');
  16599. this.unlinkEl = this.el.find('.btn-unlink');
  16600. this.selectTarget = this.el.find('.link-target');
  16601. this.textEl.on('keyup', (function(_this) {
  16602. return function(e) {
  16603. if (e.which === 13) {
  16604. return;
  16605. }
  16606. _this.target.text(_this.textEl.val());
  16607. return _this.editor.inputManager.throttledValueChanged();
  16608. };
  16609. })(this));
  16610. this.urlEl.on('keyup', (function(_this) {
  16611. return function(e) {
  16612. var val;
  16613. if (e.which === 13) {
  16614. return;
  16615. }
  16616. val = _this.urlEl.val();
  16617. if (!(/https?:\/\/|^\//ig.test(val) || !val)) {
  16618. val = 'http://' + val;
  16619. }
  16620. _this.target.attr('href', val);
  16621. return _this.editor.inputManager.throttledValueChanged();
  16622. };
  16623. })(this));
  16624. $([this.urlEl[0], this.textEl[0]]).on('keydown', (function(_this) {
  16625. return function(e) {
  16626. var range;
  16627. if (e.which === 13 || e.which === 27 || (!e.shiftKey && e.which === 9 && $(e.target).hasClass('link-url'))) {
  16628. e.preventDefault();
  16629. range = document.createRange();
  16630. _this.editor.selection.setRangeAfter(_this.target, range);
  16631. _this.hide();
  16632. return _this.editor.inputManager.throttledValueChanged();
  16633. }
  16634. };
  16635. })(this));
  16636. this.unlinkEl.on('click', (function(_this) {
  16637. return function(e) {
  16638. var range, txtNode;
  16639. txtNode = document.createTextNode(_this.target.text());
  16640. _this.target.replaceWith(txtNode);
  16641. _this.hide();
  16642. range = document.createRange();
  16643. _this.editor.selection.setRangeAfter(txtNode, range);
  16644. return _this.editor.inputManager.throttledValueChanged();
  16645. };
  16646. })(this));
  16647. return this.selectTarget.on('change', (function(_this) {
  16648. return function(e) {
  16649. _this.target.attr('target', _this.selectTarget.val());
  16650. return _this.editor.inputManager.throttledValueChanged();
  16651. };
  16652. })(this));
  16653. };
  16654. LinkPopover.prototype.show = function() {
  16655. var args;
  16656. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  16657. LinkPopover.__super__.show.apply(this, args);
  16658. this.textEl.val(this.target.text());
  16659. return this.urlEl.val(this.target.attr('href'));
  16660. };
  16661. return LinkPopover;
  16662. })(Popover);
  16663. Simditor.Toolbar.addButton(LinkButton);
  16664. ImageButton = (function(superClass) {
  16665. extend(ImageButton, superClass);
  16666. function ImageButton() {
  16667. return ImageButton.__super__.constructor.apply(this, arguments);
  16668. }
  16669. ImageButton.prototype.name = 'image';
  16670. ImageButton.prototype.icon = 'picture-o';
  16671. ImageButton.prototype.htmlTag = 'img';
  16672. ImageButton.prototype.disableTag = 'pre, table';
  16673. ImageButton.prototype.defaultImage = '';
  16674. ImageButton.prototype.needFocus = false;
  16675. ImageButton.prototype._init = function() {
  16676. var item, k, len, ref;
  16677. if (this.editor.opts.imageButton) {
  16678. if (Array.isArray(this.editor.opts.imageButton)) {
  16679. this.menu = [];
  16680. ref = this.editor.opts.imageButton;
  16681. for (k = 0, len = ref.length; k < len; k++) {
  16682. item = ref[k];
  16683. this.menu.push({
  16684. name: item + '-image',
  16685. text: this._t(item + 'Image')
  16686. });
  16687. }
  16688. } else {
  16689. this.menu = false;
  16690. }
  16691. } else {
  16692. if (this.editor.uploader != null) {
  16693. this.menu = [
  16694. {
  16695. name: 'upload-image',
  16696. text: this._t('uploadImage')
  16697. }, {
  16698. name: 'external-image',
  16699. text: this._t('externalImage')
  16700. }
  16701. ];
  16702. } else {
  16703. this.menu = false;
  16704. }
  16705. }
  16706. this.defaultImage = this.editor.opts.defaultImage;
  16707. this.editor.body.on('click', 'img:not([data-non-image])', (function(_this) {
  16708. return function(e) {
  16709. var $img, range;
  16710. $img = $(e.currentTarget);
  16711. range = document.createRange();
  16712. range.selectNode($img[0]);
  16713. _this.editor.selection.range(range);
  16714. if (!_this.editor.util.support.onselectionchange) {
  16715. _this.editor.trigger('selectionchanged');
  16716. }
  16717. return false;
  16718. };
  16719. })(this));
  16720. this.editor.body.on('mouseup', 'img:not([data-non-image])', function(e) {
  16721. return false;
  16722. });
  16723. this.editor.on('selectionchanged.image', (function(_this) {
  16724. return function() {
  16725. var $contents, $img, range;
  16726. range = _this.editor.selection.range();
  16727. if (range == null) {
  16728. return;
  16729. }
  16730. $contents = $(range.cloneContents()).contents();
  16731. if ($contents.length === 1 && $contents.is('img:not([data-non-image])')) {
  16732. $img = $(range.startContainer).contents().eq(range.startOffset);
  16733. return _this.popover.show($img);
  16734. } else {
  16735. return _this.popover.hide();
  16736. }
  16737. };
  16738. })(this));
  16739. this.editor.on('valuechanged.image', (function(_this) {
  16740. return function() {
  16741. var $masks;
  16742. $masks = _this.editor.wrapper.find('.simditor-image-loading');
  16743. if (!($masks.length > 0)) {
  16744. return;
  16745. }
  16746. return $masks.each(function(i, mask) {
  16747. var $img, $mask, file;
  16748. $mask = $(mask);
  16749. $img = $mask.data('img');
  16750. if (!($img && $img.parent().length > 0)) {
  16751. $mask.remove();
  16752. if ($img) {
  16753. file = $img.data('file');
  16754. if (file) {
  16755. _this.editor.uploader.cancel(file);
  16756. if (_this.editor.body.find('img.uploading').length < 1) {
  16757. return _this.editor.uploader.trigger('uploadready', [file]);
  16758. }
  16759. }
  16760. }
  16761. }
  16762. });
  16763. };
  16764. })(this));
  16765. return ImageButton.__super__._init.call(this);
  16766. };
  16767. ImageButton.prototype.render = function() {
  16768. var args;
  16769. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  16770. ImageButton.__super__.render.apply(this, args);
  16771. this.popover = new ImagePopover({
  16772. button: this
  16773. });
  16774. if (this.editor.opts.imageButton === 'upload') {
  16775. return this._initUploader(this.el);
  16776. }
  16777. };
  16778. ImageButton.prototype.renderMenu = function() {
  16779. ImageButton.__super__.renderMenu.call(this);
  16780. return this._initUploader();
  16781. };
  16782. ImageButton.prototype._initUploader = function($uploadItem) {
  16783. var $input, createInput, uploadProgress;
  16784. if ($uploadItem == null) {
  16785. $uploadItem = this.menuEl.find('.menu-item-upload-image');
  16786. }
  16787. if (this.editor.uploader == null) {
  16788. this.el.find('.btn-upload').remove();
  16789. return;
  16790. }
  16791. $input = null;
  16792. createInput = (function(_this) {
  16793. return function() {
  16794. if ($input) {
  16795. $input.remove();
  16796. }
  16797. return $input = $('<input/>', {
  16798. type: 'file',
  16799. title: _this._t('uploadImage'),
  16800. multiple: true,
  16801. accept: 'image/*'
  16802. }).appendTo($uploadItem);
  16803. };
  16804. })(this);
  16805. createInput();
  16806. $uploadItem.on('click mousedown', 'input[type=file]', function(e) {
  16807. return e.stopPropagation();
  16808. });
  16809. $uploadItem.on('change', 'input[type=file]', (function(_this) {
  16810. return function(e) {
  16811. if (_this.editor.inputManager.focused) {
  16812. _this.editor.uploader.upload($input, {
  16813. inline: true
  16814. });
  16815. createInput();
  16816. } else {
  16817. _this.editor.one('focus', function(e) {
  16818. _this.editor.uploader.upload($input, {
  16819. inline: true
  16820. });
  16821. return createInput();
  16822. });
  16823. _this.editor.focus();
  16824. }
  16825. return _this.wrapper.removeClass('menu-on');
  16826. };
  16827. })(this));
  16828. this.editor.uploader.on('beforeupload', (function(_this) {
  16829. return function(e, file) {
  16830. var $img;
  16831. if (!file.inline) {
  16832. return;
  16833. }
  16834. if (file.img) {
  16835. $img = $(file.img);
  16836. } else {
  16837. $img = _this.createImage(file.name);
  16838. file.img = $img;
  16839. }
  16840. $img.addClass('uploading');
  16841. $img.data('file', file);
  16842. return _this.editor.uploader.readImageFile(file.obj, function(img) {
  16843. var src;
  16844. if (!$img.hasClass('uploading')) {
  16845. return;
  16846. }
  16847. src = img ? img.src : _this.defaultImage;
  16848. return _this.loadImage($img, src, function() {
  16849. if (_this.popover.active) {
  16850. _this.popover.refresh();
  16851. return _this.popover.srcEl.val(_this._t('uploading')).prop('disabled', true);
  16852. }
  16853. });
  16854. });
  16855. };
  16856. })(this));
  16857. uploadProgress = $.proxy(this.editor.util.throttle(function(e, file, loaded, total) {
  16858. var $img, $mask, percent;
  16859. if (!file.inline) {
  16860. return;
  16861. }
  16862. $mask = file.img.data('mask');
  16863. if (!$mask) {
  16864. return;
  16865. }
  16866. $img = $mask.data('img');
  16867. if (!($img.hasClass('uploading') && $img.parent().length > 0)) {
  16868. $mask.remove();
  16869. return;
  16870. }
  16871. percent = loaded / total;
  16872. percent = (percent * 100).toFixed(0);
  16873. if (percent > 99) {
  16874. percent = 99;
  16875. }
  16876. return $mask.find('.progress').height((100 - percent) + "%");
  16877. }, 500), this);
  16878. this.editor.uploader.on('uploadprogress', uploadProgress);
  16879. this.editor.uploader.on('uploadsuccess', (function(_this) {
  16880. return function(e, file, result) {
  16881. var $img, img_path, msg;
  16882. if (!file.inline) {
  16883. return;
  16884. }
  16885. $img = file.img;
  16886. if (!($img.hasClass('uploading') && $img.parent().length > 0)) {
  16887. return;
  16888. }
  16889. if (typeof result !== 'object') {
  16890. try {
  16891. result = $.parseJSON(result);
  16892. } catch (_error) {
  16893. e = _error;
  16894. result = {
  16895. success: false
  16896. };
  16897. }
  16898. }
  16899. if (result.success === false) {
  16900. msg = result.msg || _this._t('uploadFailed');
  16901. alert(msg);
  16902. img_path = _this.defaultImage;
  16903. } else {
  16904. img_path = result.file_path;
  16905. }
  16906. _this.loadImage($img, img_path, function() {
  16907. var $mask;
  16908. $img.removeData('file');
  16909. $img.removeClass('uploading').removeClass('loading');
  16910. $mask = $img.data('mask');
  16911. if ($mask) {
  16912. $mask.remove();
  16913. }
  16914. $img.removeData('mask');
  16915. _this.editor.trigger('valuechanged');
  16916. if (_this.editor.body.find('img.uploading').length < 1) {
  16917. return _this.editor.uploader.trigger('uploadready', [file, result]);
  16918. }
  16919. });
  16920. if (_this.popover.active) {
  16921. _this.popover.srcEl.prop('disabled', false);
  16922. return _this.popover.srcEl.val(result.file_path);
  16923. }
  16924. };
  16925. })(this));
  16926. return this.editor.uploader.on('uploaderror', (function(_this) {
  16927. return function(e, file, xhr) {
  16928. var $img, msg, result;
  16929. if (!file.inline) {
  16930. return;
  16931. }
  16932. if (xhr.statusText === 'abort') {
  16933. return;
  16934. }
  16935. if (xhr.responseText) {
  16936. try {
  16937. result = $.parseJSON(xhr.responseText);
  16938. msg = result.msg;
  16939. } catch (_error) {
  16940. e = _error;
  16941. msg = _this._t('uploadError');
  16942. }
  16943. alert(msg);
  16944. }
  16945. $img = file.img;
  16946. if (!($img.hasClass('uploading') && $img.parent().length > 0)) {
  16947. return;
  16948. }
  16949. _this.loadImage($img, _this.defaultImage, function() {
  16950. var $mask;
  16951. $img.removeData('file');
  16952. $img.removeClass('uploading').removeClass('loading');
  16953. $mask = $img.data('mask');
  16954. if ($mask) {
  16955. $mask.remove();
  16956. }
  16957. return $img.removeData('mask');
  16958. });
  16959. if (_this.popover.active) {
  16960. _this.popover.srcEl.prop('disabled', false);
  16961. _this.popover.srcEl.val(_this.defaultImage);
  16962. }
  16963. _this.editor.trigger('valuechanged');
  16964. if (_this.editor.body.find('img.uploading').length < 1) {
  16965. return _this.editor.uploader.trigger('uploadready', [file, result]);
  16966. }
  16967. };
  16968. })(this));
  16969. };
  16970. ImageButton.prototype._status = function() {
  16971. return this._disableStatus();
  16972. };
  16973. ImageButton.prototype.loadImage = function($img, src, callback) {
  16974. var $mask, img, positionMask;
  16975. positionMask = (function(_this) {
  16976. return function() {
  16977. var imgOffset, wrapperOffset;
  16978. imgOffset = $img.offset();
  16979. wrapperOffset = _this.editor.wrapper.offset();
  16980. return $mask.css({
  16981. top: imgOffset.top - wrapperOffset.top,
  16982. left: imgOffset.left - wrapperOffset.left,
  16983. width: $img.width(),
  16984. height: $img.height()
  16985. }).show();
  16986. };
  16987. })(this);
  16988. $img.addClass('loading');
  16989. $mask = $img.data('mask');
  16990. if (!$mask) {
  16991. $mask = $('<div class="simditor-image-loading">\n <div class="progress"></div>\n</div>').hide().appendTo(this.editor.wrapper);
  16992. positionMask();
  16993. $img.data('mask', $mask);
  16994. $mask.data('img', $img);
  16995. }
  16996. img = new Image();
  16997. img.onload = (function(_this) {
  16998. return function() {
  16999. var height, width;
  17000. if (!$img.hasClass('loading') && !$img.hasClass('uploading')) {
  17001. return;
  17002. }
  17003. width = img.width;
  17004. height = img.height;
  17005. $img.attr({
  17006. src: src,
  17007. width: width,
  17008. height: height,
  17009. 'data-image-size': width + ',' + height
  17010. }).removeClass('loading');
  17011. if ($img.hasClass('uploading')) {
  17012. _this.editor.util.reflow(_this.editor.body);
  17013. positionMask();
  17014. } else {
  17015. $mask.remove();
  17016. $img.removeData('mask');
  17017. }
  17018. if ($.isFunction(callback)) {
  17019. return callback(img);
  17020. }
  17021. };
  17022. })(this);
  17023. img.onerror = function() {
  17024. if ($.isFunction(callback)) {
  17025. callback(false);
  17026. }
  17027. $mask.remove();
  17028. return $img.removeData('mask').removeClass('loading');
  17029. };
  17030. return img.src = src;
  17031. };
  17032. ImageButton.prototype.createImage = function(name) {
  17033. var $img, range;
  17034. if (name == null) {
  17035. name = 'Image';
  17036. }
  17037. if (!this.editor.inputManager.focused) {
  17038. this.editor.focus();
  17039. }
  17040. range = this.editor.selection.range();
  17041. range.deleteContents();
  17042. this.editor.selection.range(range);
  17043. $img = $('<img/>').attr('alt', name);
  17044. range.insertNode($img[0]);
  17045. this.editor.selection.setRangeAfter($img, range);
  17046. this.editor.trigger('valuechanged');
  17047. return $img;
  17048. };
  17049. ImageButton.prototype.command = function(src) {
  17050. var $img;
  17051. $img = this.createImage();
  17052. return this.loadImage($img, src || this.defaultImage, (function(_this) {
  17053. return function() {
  17054. _this.editor.trigger('valuechanged');
  17055. _this.editor.util.reflow($img);
  17056. $img.click();
  17057. return _this.popover.one('popovershow', function() {
  17058. _this.popover.srcEl.focus();
  17059. return _this.popover.srcEl[0].select();
  17060. });
  17061. };
  17062. })(this));
  17063. };
  17064. return ImageButton;
  17065. })(Button);
  17066. ImagePopover = (function(superClass) {
  17067. extend(ImagePopover, superClass);
  17068. function ImagePopover() {
  17069. return ImagePopover.__super__.constructor.apply(this, arguments);
  17070. }
  17071. ImagePopover.prototype.offset = {
  17072. top: 6,
  17073. left: -4
  17074. };
  17075. ImagePopover.prototype.render = function() {
  17076. var tpl;
  17077. tpl = "<div class=\"link-settings\">\n <div class=\"settings-field\">\n <label>" + (this._t('imageUrl')) + "</label>\n <input class=\"image-src\" type=\"text\" tabindex=\"1\" />\n <a class=\"btn-upload\" href=\"javascript:;\"\n title=\"" + (this._t('uploadImage')) + "\" tabindex=\"-1\">\n <span class=\"simditor-icon simditor-icon-upload\"></span>\n </a>\n </div>\n <div class='settings-field'>\n <label>" + (this._t('imageAlt')) + "</label>\n <input class=\"image-alt\" id=\"image-alt\" type=\"text\" tabindex=\"1\" />\n </div>\n <div class=\"settings-field\">\n <label>" + (this._t('imageSize')) + "</label>\n <input class=\"image-size\" id=\"image-width\" type=\"text\" tabindex=\"2\" />\n <span class=\"times\">×</span>\n <input class=\"image-size\" id=\"image-height\" type=\"text\" tabindex=\"3\" />\n <a class=\"btn-restore\" href=\"javascript:;\"\n title=\"" + (this._t('restoreImageSize')) + "\" tabindex=\"-1\">\n <span class=\"simditor-icon simditor-icon-undo\"></span>\n </a>\n </div>\n</div>";
  17078. this.el.addClass('image-popover').append(tpl);
  17079. this.srcEl = this.el.find('.image-src');
  17080. this.widthEl = this.el.find('#image-width');
  17081. this.heightEl = this.el.find('#image-height');
  17082. this.altEl = this.el.find('#image-alt');
  17083. this.srcEl.on('keydown', (function(_this) {
  17084. return function(e) {
  17085. var range;
  17086. if (!(e.which === 13 && !_this.target.hasClass('uploading'))) {
  17087. return;
  17088. }
  17089. e.preventDefault();
  17090. range = document.createRange();
  17091. _this.button.editor.selection.setRangeAfter(_this.target, range);
  17092. return _this.hide();
  17093. };
  17094. })(this));
  17095. this.srcEl.on('blur', (function(_this) {
  17096. return function(e) {
  17097. return _this._loadImage(_this.srcEl.val());
  17098. };
  17099. })(this));
  17100. this.el.find('.image-size').on('blur', (function(_this) {
  17101. return function(e) {
  17102. _this._resizeImg($(e.currentTarget));
  17103. return _this.el.data('popover').refresh();
  17104. };
  17105. })(this));
  17106. this.el.find('.image-size').on('keyup', (function(_this) {
  17107. return function(e) {
  17108. var inputEl;
  17109. inputEl = $(e.currentTarget);
  17110. if (!(e.which === 13 || e.which === 27 || e.which === 9)) {
  17111. return _this._resizeImg(inputEl, true);
  17112. }
  17113. };
  17114. })(this));
  17115. this.el.find('.image-size').on('keydown', (function(_this) {
  17116. return function(e) {
  17117. var $img, inputEl, range;
  17118. inputEl = $(e.currentTarget);
  17119. if (e.which === 13 || e.which === 27) {
  17120. e.preventDefault();
  17121. if (e.which === 13) {
  17122. _this._resizeImg(inputEl);
  17123. } else {
  17124. _this._restoreImg();
  17125. }
  17126. $img = _this.target;
  17127. _this.hide();
  17128. range = document.createRange();
  17129. return _this.button.editor.selection.setRangeAfter($img, range);
  17130. } else if (e.which === 9) {
  17131. return _this.el.data('popover').refresh();
  17132. }
  17133. };
  17134. })(this));
  17135. this.altEl.on('keydown', (function(_this) {
  17136. return function(e) {
  17137. var range;
  17138. if (e.which === 13) {
  17139. e.preventDefault();
  17140. range = document.createRange();
  17141. _this.button.editor.selection.setRangeAfter(_this.target, range);
  17142. return _this.hide();
  17143. }
  17144. };
  17145. })(this));
  17146. this.altEl.on('keyup', (function(_this) {
  17147. return function(e) {
  17148. if (e.which === 13 || e.which === 27 || e.which === 9) {
  17149. return;
  17150. }
  17151. _this.alt = _this.altEl.val();
  17152. return _this.target.attr('alt', _this.alt);
  17153. };
  17154. })(this));
  17155. this.el.find('.btn-restore').on('click', (function(_this) {
  17156. return function(e) {
  17157. _this._restoreImg();
  17158. return _this.el.data('popover').refresh();
  17159. };
  17160. })(this));
  17161. this.editor.on('valuechanged', (function(_this) {
  17162. return function(e) {
  17163. if (_this.active) {
  17164. return _this.refresh();
  17165. }
  17166. };
  17167. })(this));
  17168. return this._initUploader();
  17169. };
  17170. ImagePopover.prototype._initUploader = function() {
  17171. var $uploadBtn, createInput;
  17172. $uploadBtn = this.el.find('.btn-upload');
  17173. if (this.editor.uploader == null) {
  17174. $uploadBtn.remove();
  17175. return;
  17176. }
  17177. createInput = (function(_this) {
  17178. return function() {
  17179. if (_this.input) {
  17180. _this.input.remove();
  17181. }
  17182. return _this.input = $('<input/>', {
  17183. type: 'file',
  17184. title: _this._t('uploadImage'),
  17185. multiple: true,
  17186. accept: 'image/*'
  17187. }).appendTo($uploadBtn);
  17188. };
  17189. })(this);
  17190. createInput();
  17191. this.el.on('click mousedown', 'input[type=file]', function(e) {
  17192. return e.stopPropagation();
  17193. });
  17194. return this.el.on('change', 'input[type=file]', (function(_this) {
  17195. return function(e) {
  17196. _this.editor.uploader.upload(_this.input, {
  17197. inline: true,
  17198. img: _this.target
  17199. });
  17200. return createInput();
  17201. };
  17202. })(this));
  17203. };
  17204. ImagePopover.prototype._resizeImg = function(inputEl, onlySetVal) {
  17205. var height, value, width;
  17206. if (onlySetVal == null) {
  17207. onlySetVal = false;
  17208. }
  17209. value = inputEl.val() * 1;
  17210. if (!(this.target && ($.isNumeric(value) || value < 0))) {
  17211. return;
  17212. }
  17213. if (inputEl.is(this.widthEl)) {
  17214. width = value;
  17215. height = this.height * value / this.width;
  17216. this.heightEl.val(height);
  17217. } else {
  17218. height = value;
  17219. width = this.width * value / this.height;
  17220. this.widthEl.val(width);
  17221. }
  17222. if (!onlySetVal) {
  17223. this.target.attr({
  17224. width: width,
  17225. height: height
  17226. });
  17227. return this.editor.trigger('valuechanged');
  17228. }
  17229. };
  17230. ImagePopover.prototype._restoreImg = function() {
  17231. var ref, size;
  17232. size = ((ref = this.target.data('image-size')) != null ? ref.split(",") : void 0) || [this.width, this.height];
  17233. this.target.attr({
  17234. width: size[0] * 1,
  17235. height: size[1] * 1
  17236. });
  17237. this.widthEl.val(size[0]);
  17238. this.heightEl.val(size[1]);
  17239. return this.editor.trigger('valuechanged');
  17240. };
  17241. ImagePopover.prototype._loadImage = function(src, callback) {
  17242. if (/^data:image/.test(src) && !this.editor.uploader) {
  17243. if (callback) {
  17244. callback(false);
  17245. }
  17246. return;
  17247. }
  17248. if (this.target.attr('src') === src) {
  17249. return;
  17250. }
  17251. return this.button.loadImage(this.target, src, (function(_this) {
  17252. return function(img) {
  17253. var blob;
  17254. if (!img) {
  17255. return;
  17256. }
  17257. if (_this.active) {
  17258. _this.width = img.width;
  17259. _this.height = img.height;
  17260. _this.widthEl.val(_this.width);
  17261. _this.heightEl.val(_this.height);
  17262. }
  17263. if (/^data:image/.test(src)) {
  17264. blob = _this.editor.util.dataURLtoBlob(src);
  17265. blob.name = "Base64 Image.png";
  17266. _this.editor.uploader.upload(blob, {
  17267. inline: true,
  17268. img: _this.target
  17269. });
  17270. } else {
  17271. _this.editor.trigger('valuechanged');
  17272. }
  17273. if (callback) {
  17274. return callback(img);
  17275. }
  17276. };
  17277. })(this));
  17278. };
  17279. ImagePopover.prototype.show = function() {
  17280. var $img, args;
  17281. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  17282. ImagePopover.__super__.show.apply(this, args);
  17283. $img = this.target;
  17284. this.width = $img.width();
  17285. this.height = $img.height();
  17286. this.alt = $img.attr('alt');
  17287. if ($img.hasClass('uploading')) {
  17288. return this.srcEl.val(this._t('uploading')).prop('disabled', true);
  17289. } else {
  17290. this.srcEl.val($img.attr('src')).prop('disabled', false);
  17291. this.widthEl.val(this.width);
  17292. this.heightEl.val(this.height);
  17293. return this.altEl.val(this.alt);
  17294. }
  17295. };
  17296. return ImagePopover;
  17297. })(Popover);
  17298. Simditor.Toolbar.addButton(ImageButton);
  17299. IndentButton = (function(superClass) {
  17300. extend(IndentButton, superClass);
  17301. function IndentButton() {
  17302. return IndentButton.__super__.constructor.apply(this, arguments);
  17303. }
  17304. IndentButton.prototype.name = 'indent';
  17305. IndentButton.prototype.icon = 'indent';
  17306. IndentButton.prototype._init = function() {
  17307. this.title = this._t(this.name) + ' (Tab)';
  17308. return IndentButton.__super__._init.call(this);
  17309. };
  17310. IndentButton.prototype._status = function() {};
  17311. IndentButton.prototype.command = function() {
  17312. return this.editor.indentation.indent();
  17313. };
  17314. return IndentButton;
  17315. })(Button);
  17316. Simditor.Toolbar.addButton(IndentButton);
  17317. OutdentButton = (function(superClass) {
  17318. extend(OutdentButton, superClass);
  17319. function OutdentButton() {
  17320. return OutdentButton.__super__.constructor.apply(this, arguments);
  17321. }
  17322. OutdentButton.prototype.name = 'outdent';
  17323. OutdentButton.prototype.icon = 'outdent';
  17324. OutdentButton.prototype._init = function() {
  17325. this.title = this._t(this.name) + ' (Shift + Tab)';
  17326. return OutdentButton.__super__._init.call(this);
  17327. };
  17328. OutdentButton.prototype._status = function() {};
  17329. OutdentButton.prototype.command = function() {
  17330. return this.editor.indentation.indent(true);
  17331. };
  17332. return OutdentButton;
  17333. })(Button);
  17334. Simditor.Toolbar.addButton(OutdentButton);
  17335. HrButton = (function(superClass) {
  17336. extend(HrButton, superClass);
  17337. function HrButton() {
  17338. return HrButton.__super__.constructor.apply(this, arguments);
  17339. }
  17340. HrButton.prototype.name = 'hr';
  17341. HrButton.prototype.icon = 'minus';
  17342. HrButton.prototype.htmlTag = 'hr';
  17343. HrButton.prototype._status = function() {};
  17344. HrButton.prototype.command = function() {
  17345. var $hr, $newBlock, $nextBlock, $rootBlock;
  17346. $rootBlock = this.editor.selection.rootNodes().first();
  17347. $nextBlock = $rootBlock.next();
  17348. if ($nextBlock.length > 0) {
  17349. this.editor.selection.save();
  17350. } else {
  17351. $newBlock = $('<p/>').append(this.editor.util.phBr);
  17352. }
  17353. $hr = $('<hr/>').insertAfter($rootBlock);
  17354. if ($newBlock) {
  17355. $newBlock.insertAfter($hr);
  17356. this.editor.selection.setRangeAtStartOf($newBlock);
  17357. } else {
  17358. this.editor.selection.restore();
  17359. }
  17360. return this.editor.trigger('valuechanged');
  17361. };
  17362. return HrButton;
  17363. })(Button);
  17364. Simditor.Toolbar.addButton(HrButton);
  17365. TableButton = (function(superClass) {
  17366. extend(TableButton, superClass);
  17367. function TableButton() {
  17368. return TableButton.__super__.constructor.apply(this, arguments);
  17369. }
  17370. TableButton.prototype.name = 'table';
  17371. TableButton.prototype.icon = 'table';
  17372. TableButton.prototype.htmlTag = 'table';
  17373. TableButton.prototype.disableTag = 'pre, li, blockquote';
  17374. TableButton.prototype.menu = true;
  17375. TableButton.prototype._init = function() {
  17376. TableButton.__super__._init.call(this);
  17377. $.merge(this.editor.formatter._allowedTags, ['thead', 'th', 'tbody', 'tr', 'td', 'colgroup', 'col']);
  17378. $.extend(this.editor.formatter._allowedAttributes, {
  17379. td: ['rowspan', 'colspan'],
  17380. col: ['width']
  17381. });
  17382. $.extend(this.editor.formatter._allowedStyles, {
  17383. td: ['text-align'],
  17384. th: ['text-align']
  17385. });
  17386. this._initShortcuts();
  17387. this.editor.on('decorate', (function(_this) {
  17388. return function(e, $el) {
  17389. return $el.find('table').each(function(i, table) {
  17390. return _this.decorate($(table));
  17391. });
  17392. };
  17393. })(this));
  17394. this.editor.on('undecorate', (function(_this) {
  17395. return function(e, $el) {
  17396. return $el.find('table').each(function(i, table) {
  17397. return _this.undecorate($(table));
  17398. });
  17399. };
  17400. })(this));
  17401. this.editor.on('selectionchanged.table', (function(_this) {
  17402. return function(e) {
  17403. var $container, range;
  17404. _this.editor.body.find('.simditor-table td, .simditor-table th').removeClass('active');
  17405. range = _this.editor.selection.range();
  17406. if (!range) {
  17407. return;
  17408. }
  17409. $container = _this.editor.selection.containerNode();
  17410. if (range.collapsed && $container.is('.simditor-table')) {
  17411. if (_this.editor.selection.rangeAtStartOf($container)) {
  17412. $container = $container.find('th:first');
  17413. } else {
  17414. $container = $container.find('td:last');
  17415. }
  17416. _this.editor.selection.setRangeAtEndOf($container);
  17417. }
  17418. return $container.closest('td, th', _this.editor.body).addClass('active');
  17419. };
  17420. })(this));
  17421. this.editor.on('blur.table', (function(_this) {
  17422. return function(e) {
  17423. return _this.editor.body.find('.simditor-table td, .simditor-table th').removeClass('active');
  17424. };
  17425. })(this));
  17426. this.editor.keystroke.add('up', 'td', (function(_this) {
  17427. return function(e, $node) {
  17428. _this._tdNav($node, 'up');
  17429. return true;
  17430. };
  17431. })(this));
  17432. this.editor.keystroke.add('up', 'th', (function(_this) {
  17433. return function(e, $node) {
  17434. _this._tdNav($node, 'up');
  17435. return true;
  17436. };
  17437. })(this));
  17438. this.editor.keystroke.add('down', 'td', (function(_this) {
  17439. return function(e, $node) {
  17440. _this._tdNav($node, 'down');
  17441. return true;
  17442. };
  17443. })(this));
  17444. return this.editor.keystroke.add('down', 'th', (function(_this) {
  17445. return function(e, $node) {
  17446. _this._tdNav($node, 'down');
  17447. return true;
  17448. };
  17449. })(this));
  17450. };
  17451. TableButton.prototype._tdNav = function($td, direction) {
  17452. var $anotherTr, $tr, action, anotherTag, index, parentTag, ref;
  17453. if (direction == null) {
  17454. direction = 'up';
  17455. }
  17456. action = direction === 'up' ? 'prev' : 'next';
  17457. ref = direction === 'up' ? ['tbody', 'thead'] : ['thead', 'tbody'], parentTag = ref[0], anotherTag = ref[1];
  17458. $tr = $td.parent('tr');
  17459. $anotherTr = this["_" + action + "Row"]($tr);
  17460. if (!($anotherTr.length > 0)) {
  17461. return true;
  17462. }
  17463. index = $tr.find('td, th').index($td);
  17464. return this.editor.selection.setRangeAtEndOf($anotherTr.find('td, th').eq(index));
  17465. };
  17466. TableButton.prototype._nextRow = function($tr) {
  17467. var $nextTr;
  17468. $nextTr = $tr.next('tr');
  17469. if ($nextTr.length < 1 && $tr.parent('thead').length > 0) {
  17470. $nextTr = $tr.parent('thead').next('tbody').find('tr:first');
  17471. }
  17472. return $nextTr;
  17473. };
  17474. TableButton.prototype._prevRow = function($tr) {
  17475. var $prevTr;
  17476. $prevTr = $tr.prev('tr');
  17477. if ($prevTr.length < 1 && $tr.parent('tbody').length > 0) {
  17478. $prevTr = $tr.parent('tbody').prev('thead').find('tr');
  17479. }
  17480. return $prevTr;
  17481. };
  17482. TableButton.prototype.initResize = function($table) {
  17483. var $colgroup, $resizeHandle, $wrapper;
  17484. $wrapper = $table.parent('.simditor-table');
  17485. $colgroup = $table.find('colgroup');
  17486. if ($colgroup.length < 1) {
  17487. $colgroup = $('<colgroup/>').prependTo($table);
  17488. $table.find('thead tr th').each(function(i, td) {
  17489. var $col;
  17490. return $col = $('<col/>').appendTo($colgroup);
  17491. });
  17492. this.refreshTableWidth($table);
  17493. }
  17494. $resizeHandle = $('<div />', {
  17495. "class": 'simditor-resize-handle',
  17496. contenteditable: 'false'
  17497. }).appendTo($wrapper);
  17498. $wrapper.on('mousemove', 'td, th', function(e) {
  17499. var $col, $td, index, ref, ref1, x;
  17500. if ($wrapper.hasClass('resizing')) {
  17501. return;
  17502. }
  17503. $td = $(e.currentTarget);
  17504. x = e.pageX - $(e.currentTarget).offset().left;
  17505. if (x < 5 && $td.prev().length > 0) {
  17506. $td = $td.prev();
  17507. }
  17508. if ($td.next('td, th').length < 1) {
  17509. $resizeHandle.hide();
  17510. return;
  17511. }
  17512. if ((ref = $resizeHandle.data('td')) != null ? ref.is($td) : void 0) {
  17513. $resizeHandle.show();
  17514. return;
  17515. }
  17516. index = $td.parent().find('td, th').index($td);
  17517. $col = $colgroup.find('col').eq(index);
  17518. if ((ref1 = $resizeHandle.data('col')) != null ? ref1.is($col) : void 0) {
  17519. $resizeHandle.show();
  17520. return;
  17521. }
  17522. return $resizeHandle.css('left', $td.position().left + $td.outerWidth() - 5).data('td', $td).data('col', $col).show();
  17523. });
  17524. $wrapper.on('mouseleave', function(e) {
  17525. return $resizeHandle.hide();
  17526. });
  17527. return $wrapper.on('mousedown', '.simditor-resize-handle', function(e) {
  17528. var $handle, $leftCol, $leftTd, $rightCol, $rightTd, minWidth, startHandleLeft, startLeftWidth, startRightWidth, startX, tableWidth;
  17529. $handle = $(e.currentTarget);
  17530. $leftTd = $handle.data('td');
  17531. $leftCol = $handle.data('col');
  17532. $rightTd = $leftTd.next('td, th');
  17533. $rightCol = $leftCol.next('col');
  17534. startX = e.pageX;
  17535. startLeftWidth = $leftTd.outerWidth() * 1;
  17536. startRightWidth = $rightTd.outerWidth() * 1;
  17537. startHandleLeft = parseFloat($handle.css('left'));
  17538. tableWidth = $leftTd.closest('table').width();
  17539. minWidth = 50;
  17540. $(document).on('mousemove.simditor-resize-table', function(e) {
  17541. var deltaX, leftWidth, rightWidth;
  17542. deltaX = e.pageX - startX;
  17543. leftWidth = startLeftWidth + deltaX;
  17544. rightWidth = startRightWidth - deltaX;
  17545. if (leftWidth < minWidth) {
  17546. leftWidth = minWidth;
  17547. deltaX = minWidth - startLeftWidth;
  17548. rightWidth = startRightWidth - deltaX;
  17549. } else if (rightWidth < minWidth) {
  17550. rightWidth = minWidth;
  17551. deltaX = startRightWidth - minWidth;
  17552. leftWidth = startLeftWidth + deltaX;
  17553. }
  17554. $leftCol.attr('width', (leftWidth / tableWidth * 100) + '%');
  17555. $rightCol.attr('width', (rightWidth / tableWidth * 100) + '%');
  17556. return $handle.css('left', startHandleLeft + deltaX);
  17557. });
  17558. $(document).one('mouseup.simditor-resize-table', function(e) {
  17559. $(document).off('.simditor-resize-table');
  17560. return $wrapper.removeClass('resizing');
  17561. });
  17562. $wrapper.addClass('resizing');
  17563. return false;
  17564. });
  17565. };
  17566. TableButton.prototype._initShortcuts = function() {
  17567. this.editor.hotkeys.add('ctrl+alt+up', (function(_this) {
  17568. return function(e) {
  17569. _this.editMenu.find('.menu-item[data-param=insertRowAbove]').click();
  17570. return false;
  17571. };
  17572. })(this));
  17573. this.editor.hotkeys.add('ctrl+alt+down', (function(_this) {
  17574. return function(e) {
  17575. _this.editMenu.find('.menu-item[data-param=insertRowBelow]').click();
  17576. return false;
  17577. };
  17578. })(this));
  17579. this.editor.hotkeys.add('ctrl+alt+left', (function(_this) {
  17580. return function(e) {
  17581. _this.editMenu.find('.menu-item[data-param=insertColLeft]').click();
  17582. return false;
  17583. };
  17584. })(this));
  17585. return this.editor.hotkeys.add('ctrl+alt+right', (function(_this) {
  17586. return function(e) {
  17587. _this.editMenu.find('.menu-item[data-param=insertColRight]').click();
  17588. return false;
  17589. };
  17590. })(this));
  17591. };
  17592. TableButton.prototype.decorate = function($table) {
  17593. var $headRow, $tbody, $thead;
  17594. if ($table.parent('.simditor-table').length > 0) {
  17595. this.undecorate($table);
  17596. }
  17597. $table.wrap('<div class="simditor-table"></div>');
  17598. if ($table.find('thead').length < 1) {
  17599. $thead = $('<thead />');
  17600. $headRow = $table.find('tr').first();
  17601. $thead.append($headRow);
  17602. this._changeCellTag($headRow, 'th');
  17603. $tbody = $table.find('tbody');
  17604. if ($tbody.length > 0) {
  17605. $tbody.before($thead);
  17606. } else {
  17607. $table.prepend($thead);
  17608. }
  17609. }
  17610. this.initResize($table);
  17611. return $table.parent();
  17612. };
  17613. TableButton.prototype.undecorate = function($table) {
  17614. if (!($table.parent('.simditor-table').length > 0)) {
  17615. return;
  17616. }
  17617. return $table.parent().replaceWith($table);
  17618. };
  17619. TableButton.prototype.renderMenu = function() {
  17620. var $table;
  17621. $("<div class=\"menu-create-table\">\n</div>\n<div class=\"menu-edit-table\">\n <ul>\n <li>\n <a tabindex=\"-1\" unselectable=\"on\" class=\"menu-item\"\n href=\"javascript:;\" data-param=\"deleteRow\">\n <span>" + (this._t('deleteRow')) + "</span>\n </a>\n </li>\n <li>\n <a tabindex=\"-1\" unselectable=\"on\" class=\"menu-item\"\n href=\"javascript:;\" data-param=\"insertRowAbove\">\n <span>" + (this._t('insertRowAbove')) + " ( Ctrl + Alt + ↑ )</span>\n </a>\n </li>\n <li>\n <a tabindex=\"-1\" unselectable=\"on\" class=\"menu-item\"\n href=\"javascript:;\" data-param=\"insertRowBelow\">\n <span>" + (this._t('insertRowBelow')) + " ( Ctrl + Alt + ↓ )</span>\n </a>\n </li>\n <li><span class=\"separator\"></span></li>\n <li>\n <a tabindex=\"-1\" unselectable=\"on\" class=\"menu-item\"\n href=\"javascript:;\" data-param=\"deleteCol\">\n <span>" + (this._t('deleteColumn')) + "</span>\n </a>\n </li>\n <li>\n <a tabindex=\"-1\" unselectable=\"on\" class=\"menu-item\"\n href=\"javascript:;\" data-param=\"insertColLeft\">\n <span>" + (this._t('insertColumnLeft')) + " ( Ctrl + Alt + ← )</span>\n </a>\n </li>\n <li>\n <a tabindex=\"-1\" unselectable=\"on\" class=\"menu-item\"\n href=\"javascript:;\" data-param=\"insertColRight\">\n <span>" + (this._t('insertColumnRight')) + " ( Ctrl + Alt + → )</span>\n </a>\n </li>\n <li><span class=\"separator\"></span></li>\n <li>\n <a tabindex=\"-1\" unselectable=\"on\" class=\"menu-item\"\n href=\"javascript:;\" data-param=\"deleteTable\">\n <span>" + (this._t('deleteTable')) + "</span>\n </a>\n </li>\n </ul>\n</div>").appendTo(this.menuWrapper);
  17622. this.createMenu = this.menuWrapper.find('.menu-create-table');
  17623. this.editMenu = this.menuWrapper.find('.menu-edit-table');
  17624. $table = this.createTable(6, 6).appendTo(this.createMenu);
  17625. this.createMenu.on('mouseenter', 'td, th', (function(_this) {
  17626. return function(e) {
  17627. var $td, $tr, $trs, num;
  17628. _this.createMenu.find('td, th').removeClass('selected');
  17629. $td = $(e.currentTarget);
  17630. $tr = $td.parent();
  17631. num = $tr.find('td, th').index($td) + 1;
  17632. $trs = $tr.prevAll('tr').addBack();
  17633. if ($tr.parent().is('tbody')) {
  17634. $trs = $trs.add($table.find('thead tr'));
  17635. }
  17636. return $trs.find("td:lt(" + num + "), th:lt(" + num + ")").addClass('selected');
  17637. };
  17638. })(this));
  17639. this.createMenu.on('mouseleave', function(e) {
  17640. return $(e.currentTarget).find('td, th').removeClass('selected');
  17641. });
  17642. return this.createMenu.on('mousedown', 'td, th', (function(_this) {
  17643. return function(e) {
  17644. var $closestBlock, $td, $tr, colNum, rowNum;
  17645. _this.wrapper.removeClass('menu-on');
  17646. if (!_this.editor.inputManager.focused) {
  17647. return;
  17648. }
  17649. $td = $(e.currentTarget);
  17650. $tr = $td.parent();
  17651. colNum = $tr.find('td').index($td) + 1;
  17652. rowNum = $tr.prevAll('tr').length + 1;
  17653. if ($tr.parent().is('tbody')) {
  17654. rowNum += 1;
  17655. }
  17656. $table = _this.createTable(rowNum, colNum, true);
  17657. $closestBlock = _this.editor.selection.blockNodes().last();
  17658. if (_this.editor.util.isEmptyNode($closestBlock)) {
  17659. $closestBlock.replaceWith($table);
  17660. } else {
  17661. $closestBlock.after($table);
  17662. }
  17663. _this.decorate($table);
  17664. _this.editor.selection.setRangeAtStartOf($table.find('th:first'));
  17665. _this.editor.trigger('valuechanged');
  17666. return false;
  17667. };
  17668. })(this));
  17669. };
  17670. TableButton.prototype.createTable = function(row, col, phBr) {
  17671. var $table, $tbody, $td, $thead, $tr, c, k, l, r, ref, ref1;
  17672. $table = $('<table/>');
  17673. $thead = $('<thead/>').appendTo($table);
  17674. $tbody = $('<tbody/>').appendTo($table);
  17675. for (r = k = 0, ref = row; 0 <= ref ? k < ref : k > ref; r = 0 <= ref ? ++k : --k) {
  17676. $tr = $('<tr/>');
  17677. $tr.appendTo(r === 0 ? $thead : $tbody);
  17678. for (c = l = 0, ref1 = col; 0 <= ref1 ? l < ref1 : l > ref1; c = 0 <= ref1 ? ++l : --l) {
  17679. $td = $(r === 0 ? '<th/>' : '<td/>').appendTo($tr);
  17680. if (phBr) {
  17681. $td.append(this.editor.util.phBr);
  17682. }
  17683. }
  17684. }
  17685. return $table;
  17686. };
  17687. TableButton.prototype.refreshTableWidth = function($table) {
  17688. var cols, tableWidth;
  17689. tableWidth = $table.width();
  17690. cols = $table.find('col');
  17691. return $table.find('thead tr th').each(function(i, td) {
  17692. var $col;
  17693. $col = cols.eq(i);
  17694. return $col.attr('width', ($(td).outerWidth() / tableWidth * 100) + '%');
  17695. });
  17696. };
  17697. TableButton.prototype.setActive = function(active) {
  17698. TableButton.__super__.setActive.call(this, active);
  17699. if (active) {
  17700. this.createMenu.hide();
  17701. return this.editMenu.show();
  17702. } else {
  17703. this.createMenu.show();
  17704. return this.editMenu.hide();
  17705. }
  17706. };
  17707. TableButton.prototype._changeCellTag = function($tr, tagName) {
  17708. return $tr.find('td, th').each(function(i, cell) {
  17709. var $cell;
  17710. $cell = $(cell);
  17711. return $cell.replaceWith("<" + tagName + ">" + ($cell.html()) + "</" + tagName + ">");
  17712. });
  17713. };
  17714. TableButton.prototype.deleteRow = function($td) {
  17715. var $newTr, $tr, index;
  17716. $tr = $td.parent('tr');
  17717. if ($tr.closest('table').find('tr').length < 1) {
  17718. return this.deleteTable($td);
  17719. } else {
  17720. $newTr = this._nextRow($tr);
  17721. if (!($newTr.length > 0)) {
  17722. $newTr = this._prevRow($tr);
  17723. }
  17724. index = $tr.find('td, th').index($td);
  17725. if ($tr.parent().is('thead')) {
  17726. $newTr.appendTo($tr.parent());
  17727. this._changeCellTag($newTr, 'th');
  17728. }
  17729. $tr.remove();
  17730. return this.editor.selection.setRangeAtEndOf($newTr.find('td, th').eq(index));
  17731. }
  17732. };
  17733. TableButton.prototype.insertRow = function($td, direction) {
  17734. var $newTr, $table, $tr, cellTag, colNum, i, index, k, ref;
  17735. if (direction == null) {
  17736. direction = 'after';
  17737. }
  17738. $tr = $td.parent('tr');
  17739. $table = $tr.closest('table');
  17740. colNum = 0;
  17741. $table.find('tr').each(function(i, tr) {
  17742. return colNum = Math.max(colNum, $(tr).find('td').length);
  17743. });
  17744. index = $tr.find('td, th').index($td);
  17745. $newTr = $('<tr/>');
  17746. cellTag = 'td';
  17747. if (direction === 'after' && $tr.parent().is('thead')) {
  17748. $tr.parent().next('tbody').prepend($newTr);
  17749. } else if (direction === 'before' && $tr.parent().is('thead')) {
  17750. $tr.before($newTr);
  17751. $tr.parent().next('tbody').prepend($tr);
  17752. this._changeCellTag($tr, 'td');
  17753. cellTag = 'th';
  17754. } else {
  17755. $tr[direction]($newTr);
  17756. }
  17757. for (i = k = 1, ref = colNum; 1 <= ref ? k <= ref : k >= ref; i = 1 <= ref ? ++k : --k) {
  17758. $("<" + cellTag + "/>").append(this.editor.util.phBr).appendTo($newTr);
  17759. }
  17760. return this.editor.selection.setRangeAtStartOf($newTr.find('td, th').eq(index));
  17761. };
  17762. TableButton.prototype.deleteCol = function($td) {
  17763. var $newTd, $table, $tr, index, noOtherCol, noOtherRow;
  17764. $tr = $td.parent('tr');
  17765. noOtherRow = $tr.closest('table').find('tr').length < 2;
  17766. noOtherCol = $td.siblings('td, th').length < 1;
  17767. if (noOtherRow && noOtherCol) {
  17768. return this.deleteTable($td);
  17769. } else {
  17770. index = $tr.find('td, th').index($td);
  17771. $newTd = $td.next('td, th');
  17772. if (!($newTd.length > 0)) {
  17773. $newTd = $tr.prev('td, th');
  17774. }
  17775. $table = $tr.closest('table');
  17776. $table.find('col').eq(index).remove();
  17777. $table.find('tr').each(function(i, tr) {
  17778. return $(tr).find('td, th').eq(index).remove();
  17779. });
  17780. this.refreshTableWidth($table);
  17781. return this.editor.selection.setRangeAtEndOf($newTd);
  17782. }
  17783. };
  17784. TableButton.prototype.insertCol = function($td, direction) {
  17785. var $col, $newCol, $newTd, $table, $tr, index, tableWidth, width;
  17786. if (direction == null) {
  17787. direction = 'after';
  17788. }
  17789. $tr = $td.parent('tr');
  17790. index = $tr.find('td, th').index($td);
  17791. $table = $td.closest('table');
  17792. $col = $table.find('col').eq(index);
  17793. $table.find('tr').each((function(_this) {
  17794. return function(i, tr) {
  17795. var $newTd, cellTag;
  17796. cellTag = $(tr).parent().is('thead') ? 'th' : 'td';
  17797. $newTd = $("<" + cellTag + "/>").append(_this.editor.util.phBr);
  17798. return $(tr).find('td, th').eq(index)[direction]($newTd);
  17799. };
  17800. })(this));
  17801. $newCol = $('<col/>');
  17802. $col[direction]($newCol);
  17803. tableWidth = $table.width();
  17804. width = Math.max(parseFloat($col.attr('width')) / 2, 50 / tableWidth * 100);
  17805. $col.attr('width', width + '%');
  17806. $newCol.attr('width', width + '%');
  17807. this.refreshTableWidth($table);
  17808. $newTd = direction === 'after' ? $td.next('td, th') : $td.prev('td, th');
  17809. return this.editor.selection.setRangeAtStartOf($newTd);
  17810. };
  17811. TableButton.prototype.deleteTable = function($td) {
  17812. var $block, $table;
  17813. $table = $td.closest('.simditor-table');
  17814. $block = $table.next('p');
  17815. $table.remove();
  17816. if ($block.length > 0) {
  17817. return this.editor.selection.setRangeAtStartOf($block);
  17818. }
  17819. };
  17820. TableButton.prototype.command = function(param) {
  17821. var $td;
  17822. $td = this.editor.selection.containerNode().closest('td, th');
  17823. if (!($td.length > 0)) {
  17824. return;
  17825. }
  17826. if (param === 'deleteRow') {
  17827. this.deleteRow($td);
  17828. } else if (param === 'insertRowAbove') {
  17829. this.insertRow($td, 'before');
  17830. } else if (param === 'insertRowBelow') {
  17831. this.insertRow($td);
  17832. } else if (param === 'deleteCol') {
  17833. this.deleteCol($td);
  17834. } else if (param === 'insertColLeft') {
  17835. this.insertCol($td, 'before');
  17836. } else if (param === 'insertColRight') {
  17837. this.insertCol($td);
  17838. } else if (param === 'deleteTable') {
  17839. this.deleteTable($td);
  17840. } else {
  17841. return;
  17842. }
  17843. return this.editor.trigger('valuechanged');
  17844. };
  17845. return TableButton;
  17846. })(Button);
  17847. Simditor.Toolbar.addButton(TableButton);
  17848. StrikethroughButton = (function(superClass) {
  17849. extend(StrikethroughButton, superClass);
  17850. function StrikethroughButton() {
  17851. return StrikethroughButton.__super__.constructor.apply(this, arguments);
  17852. }
  17853. StrikethroughButton.prototype.name = 'strikethrough';
  17854. StrikethroughButton.prototype.icon = 'strikethrough';
  17855. StrikethroughButton.prototype.htmlTag = 'strike';
  17856. StrikethroughButton.prototype.disableTag = 'pre';
  17857. StrikethroughButton.prototype._activeStatus = function() {
  17858. var active;
  17859. active = document.queryCommandState('strikethrough') === true;
  17860. this.setActive(active);
  17861. return this.active;
  17862. };
  17863. StrikethroughButton.prototype.command = function() {
  17864. document.execCommand('strikethrough');
  17865. if (!this.editor.util.support.oninput) {
  17866. this.editor.trigger('valuechanged');
  17867. }
  17868. return $(document).trigger('selectionchange');
  17869. };
  17870. return StrikethroughButton;
  17871. })(Button);
  17872. Simditor.Toolbar.addButton(StrikethroughButton);
  17873. AlignmentButton = (function(superClass) {
  17874. extend(AlignmentButton, superClass);
  17875. function AlignmentButton() {
  17876. return AlignmentButton.__super__.constructor.apply(this, arguments);
  17877. }
  17878. AlignmentButton.prototype.name = "alignment";
  17879. AlignmentButton.prototype.icon = 'align-left';
  17880. AlignmentButton.prototype.htmlTag = 'p, h1, h2, h3, h4, td, th';
  17881. AlignmentButton.prototype._init = function() {
  17882. this.menu = [
  17883. {
  17884. name: 'left',
  17885. text: this._t('alignLeft'),
  17886. icon: 'align-left',
  17887. param: 'left'
  17888. }, {
  17889. name: 'center',
  17890. text: this._t('alignCenter'),
  17891. icon: 'align-center',
  17892. param: 'center'
  17893. }, {
  17894. name: 'right',
  17895. text: this._t('alignRight'),
  17896. icon: 'align-right',
  17897. param: 'right'
  17898. }
  17899. ];
  17900. return AlignmentButton.__super__._init.call(this);
  17901. };
  17902. AlignmentButton.prototype.setActive = function(active, align) {
  17903. if (align == null) {
  17904. align = 'left';
  17905. }
  17906. if (align !== 'left' && align !== 'center' && align !== 'right') {
  17907. align = 'left';
  17908. }
  17909. if (align === 'left') {
  17910. AlignmentButton.__super__.setActive.call(this, false);
  17911. } else {
  17912. AlignmentButton.__super__.setActive.call(this, active);
  17913. }
  17914. this.el.removeClass('align-left align-center align-right');
  17915. if (active) {
  17916. this.el.addClass('align-' + align);
  17917. }
  17918. this.setIcon('align-' + align);
  17919. return this.menuEl.find('.menu-item').show().end().find('.menu-item-' + align).hide();
  17920. };
  17921. AlignmentButton.prototype._status = function() {
  17922. this.nodes = this.editor.selection.nodes().filter(this.htmlTag);
  17923. if (this.nodes.length < 1) {
  17924. this.setDisabled(true);
  17925. return this.setActive(false);
  17926. } else {
  17927. this.setDisabled(false);
  17928. return this.setActive(true, this.nodes.first().css('text-align'));
  17929. }
  17930. };
  17931. AlignmentButton.prototype.command = function(align) {
  17932. if (align !== 'left' && align !== 'center' && align !== 'right') {
  17933. throw new Error("simditor alignment button: invalid align " + align);
  17934. }
  17935. this.nodes.css({
  17936. 'text-align': align === 'left' ? '' : align
  17937. });
  17938. this.editor.trigger('valuechanged');
  17939. return this.editor.inputManager.throttledSelectionChanged();
  17940. };
  17941. return AlignmentButton;
  17942. })(Button);
  17943. Simditor.Toolbar.addButton(AlignmentButton);
  17944. return Simditor;
  17945. }));
  17946. /***/ }),
  17947. /***/ "lSXA":
  17948. /***/ (function(module, exports) {
  17949. // removed by extract-text-webpack-plugin
  17950. /***/ }),
  17951. /***/ "t4zo":
  17952. /***/ (function(module, exports, __webpack_require__) {
  17953. /* 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),
  17954. __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
  17955. (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
  17956. __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)});
  17957. //# sourceMappingURL=FileSaver.min.js.map
  17958. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__("DuR2")))
  17959. /***/ })
  17960. });